// publish_detail.js — 发行详情页状态轮询
(function() {
    const badge = document.getElementById('status-badge');
    if (!badge) return;

    let currentStatus = badge.textContent.trim();
    if (currentStatus === 'completed' || currentStatus === 'failed') return;

    const STATUS_URL = badge.dataset.statusUrl;
    const phaseEl = document.getElementById('phase-text');
    const albumEl = document.getElementById('album-id');
    const songEl = document.getElementById('song-ids');
    const phoneEl = document.getElementById('masked-phone');
    const jsErrorContainer = document.getElementById('js-error-container');
    const jsErrorText = document.getElementById('js-error-text');

    const timer = setInterval(async () => {
        try {
            const resp = await fetch(STATUS_URL);
            if (!resp.ok) return;
            const data = await resp.json();

            badge.textContent = data.status;
            badge.className = 'badge badge-' + data.status;
            if (data.phase) phaseEl.textContent = data.phase;
            if (data.album_id) albumEl.textContent = data.album_id;
            if (data.masked_phone) phoneEl.textContent = data.masked_phone;

            if (data.song_ids) {
                try {
                    const sids = JSON.parse(data.song_ids);
                    if (Array.isArray(sids)) {
                        songEl.innerHTML = sids.map(id => `<code style="display:block; margin-bottom:2px;">${id}</code>`).join('');
                    }
                } catch (e) {}
            }

            if (data.error_message) {
                jsErrorContainer.style.display = 'block';
                jsErrorText.textContent = data.error_message;
            }

            if (data.status === 'completed' || data.status === 'failed') {
                clearInterval(timer);
                setTimeout(() => location.reload(), 1000);
            }
        } catch (err) {
            console.error('Polling failed:', err);
        }
    }, 3000);
})();
