// lyrics_batch_detail.js — 批量作词详情页状态轮询
(function() {
    const badge = document.getElementById('batch-status');
    if (!badge) return;
    const status = badge.textContent.trim();
    if (status === 'completed' || status === 'failed') return;

    const PAGE = JSON.parse(document.getElementById('page-data').textContent);

    function updatePhaseSteps(data) {
        const steps = document.querySelectorAll('#phase-steps .step');
        if (!steps.length) return;

        const completed = data.completed_count || 0;
        const total = data.total_count || 1;
        const composed = data.composed_count || 0;

        let currentPhase = 1;
        if (completed >= total && composed < completed) currentPhase = 2;
        else if (completed >= total && composed >= completed) currentPhase = 3;

        steps.forEach(step => {
            const phase = parseInt(step.dataset.phase);
            step.classList.remove('active', 'done');
            if (phase < currentPhase) step.classList.add('done');
            else if (phase === currentPhase) step.classList.add('active');
        });
    }

    const timer = setInterval(async () => {
        try {
            const resp = await fetch(PAGE.statusUrl);
            const data = await resp.json();
            badge.textContent = data.status;
            badge.className = 'badge badge-' + data.status;

            const prog = document.getElementById('batch-progress');
            if (prog) prog.textContent = data.completed_count + ' / ' + data.total_count;

            const fill = document.getElementById('progress-fill');
            if (fill && data.total_count > 0) {
                fill.style.width = (data.completed_count / data.total_count * 100) + '%';
            }

            const composed = document.getElementById('batch-composed');
            if (composed && data.composed_count !== undefined) {
                composed.textContent = data.composed_count + ' 首';
            }
            const exported = document.getElementById('batch-exported');
            if (exported && data.exported_count !== undefined) {
                exported.textContent = data.exported_count + ' 首';
            }
            const published = document.getElementById('batch-published');
            if (published && data.published_count !== undefined) {
                published.textContent = data.published_count + ' 首';
            }

            updatePhaseSteps(data);

            if (data.status === 'completed' || data.status === 'failed') {
                clearInterval(timer);
                location.reload();
            }
        } catch {}
    }, 5000);

    // Initial phase update
    updatePhaseSteps({
        completed_count: PAGE.completedCount,
        total_count: PAGE.totalCount,
        composed_count: PAGE.composedCount,
        exported_count: PAGE.exportedCount,
        published_count: PAGE.publishedCount
    });
})();
