window.addEventListener('load', function() {

    // 1. Get references to ALL our interactive elements
    const music = document.getElementById('bg-music');
    const soundOnBtn = document.getElementById('sound-on-btn');
    const soundOffBtn = document.getElementById('sound-off-btn');
    const welcomeOverlay = document.getElementById('welcome-overlay');
    const enterButton = document.getElementById('enter-button');

    const reportPath = "./网页服务/分析报告/"; // Base path to the reports

    function fetchAndRenderReports() {
        return fetch('http://127.0.0.1:5000/reports') // Added return here
            .then(response => response.json())
            .then(reports => {
                const reportList = document.getElementById('report-list');
                reportList.innerHTML = '';
                if (reports.length === 0) {
                    reportList.innerHTML = '<li>暂无分析报告</li>';
                }
                reports.forEach(report => {
                    const listItem = document.createElement('li');
                    const link = document.createElement('a');
                    link.href = reportPath + report.name;
                    link.textContent = report.name.replace(/_analysis\.html$/, '').replace(/_/, ' ') + ' 的分析报告';
                    link.setAttribute('download', report.name);
                    listItem.appendChild(link);
                    reportList.appendChild(listItem);
                });
                return reports; // Pass the detailed list
            })
            .catch(error => {
                console.error('Error fetching reports:', error);
                const reportList = document.getElementById('report-list');
                reportList.innerHTML = '<li>获取报告列表失败，请检查服务是否运行。</li>';
                return Promise.reject(error);
            });
    }


    // 2. Set the initial state: Music is off, sound-off icon is ready.
    music.muted = true; // Start muted
    soundOnBtn.style.display = 'none';
    soundOffBtn.style.display = 'block';


    // 3. Main Logic: When user clicks the "Enter" button
    enterButton.addEventListener('click', function() {
        // Fade out and remove the overlay
        welcomeOverlay.style.opacity = '0';
        setTimeout(() => {
            welcomeOverlay.style.display = 'none';
        }, 500); // Wait for the fade-out transition to finish

        // NOW we can play the music, as it's triggered by a user click!
        music.muted = false;
        music.play();

        // Update the icons to show that the music is playing
        soundOnBtn.style.display = 'block';
        soundOffBtn.style.display = 'none';
    });


    // 4. Click event listener for the 'Sound On' button (to MUTE)
    soundOnBtn.addEventListener('click', function(e) {
        e.preventDefault();
        music.muted = true;
        soundOnBtn.style.display = 'none';
        soundOffBtn.style.display = 'block';
    });

    // 5. Click event listener for the 'Sound Off' button (to UNMUTE)
    soundOffBtn.addEventListener('click', function(e) {
        e.preventDefault();
        music.muted = false;
        music.play(); // Ensure it plays if it was paused
        soundOffBtn.style.display = 'none';
        soundOnBtn.style.display = 'block';
    });

    // --- Modal Logic ---
    const analysisBtn = document.querySelector('a[href="#analysis"]');
    const downloadBtn = document.querySelector('a[href="#download"]');
    const analysisModal = document.getElementById('analysis-modal');
    const downloadModal = document.getElementById('download-modal');
    const closeBtns = document.querySelectorAll('.close-btn');

    analysisBtn.addEventListener('click', (e) => {
        e.preventDefault();
        analysisModal.style.display = 'block';
    });

    downloadBtn.addEventListener('click', (e) => {
        e.preventDefault();
        fetchAndRenderReports(); // Fetch the latest reports list
        downloadModal.style.display = 'block';
    });

    closeBtns.forEach(btn => {
        btn.onclick = function() {
            analysisModal.style.display = "none";
            downloadModal.style.display = "none";
            analysisStatus.textContent = ''; // Clear status on close
        }
    });

    window.onclick = function(event) {
        if (event.target == analysisModal) {
            analysisModal.style.display = "none";
        }
        if (event.target == downloadModal) {
            downloadModal.style.display = "none";
        }
    }

    // --- Analysis Logic ---
    const startAnalysisBtn = document.getElementById('start-analysis-btn');
    const fileUpload = document.getElementById('file-upload');
    const analysisStatus = document.getElementById('analysis-status');

    startAnalysisBtn.addEventListener('click', () => {
        if (fileUpload.files.length === 0) {
            analysisStatus.textContent = '请先选择一个文件！';
            return;
        }

        let initialReports = [];

        // 1. Get the list of reports *before* analysis starts
        fetch('http://127.0.0.1:5000/reports').then(res => {
            if (!res.ok) throw new Error('Cannot connect to service');
            return res.json();
        }).then(reports => {
            initialReports = reports;
            analysisStatus.textContent = '正在上传并分析文件...';
            const formData = new FormData();
            formData.append('file', fileUpload.files[0]);
            return fetch('http://127.0.0.1:5000/analyze', { method: 'POST', body: formData });
        }).then(uploadRes => {
            if (!uploadRes.ok) throw new Error('File upload failed');
            return uploadRes.json();
        }).then(data => {
            alert('文件上传成功，后台已开始分析！');
            analysisModal.style.display = 'none';
            analysisStatus.textContent = '';

            // 3. Start polling for results
            const pollInterval = setInterval(() => {
                fetch('http://127.0.0.1:5000/reports').then(r => r.ok ? r.json() : null)
                .then(currentReports => {
                    if (!currentReports) return; // Ignore failed poll attempts

                    const initialReportMap = new Map(initialReports.map(r => [r.name, r.mtime]));
                    let newOrUpdated = false;

                    if (currentReports.length > initialReports.length) {
                        newOrUpdated = true;
                    } else {
                        for (const report of currentReports) {
                            if (!initialReportMap.has(report.name) || initialReportMap.get(report.name) < report.mtime) {
                                newOrUpdated = true;
                                break;
                            }
                        }
                    }

                    if (newOrUpdated) {
                        clearInterval(pollInterval);
                        fetchAndRenderReports();
                        alert('分析完成！');
                    }
                }).catch(() => {});
            }, 5000);
        }).catch(error => {
            console.error('Analysis process failed:', error);
            analysisStatus.textContent = error.message === 'Cannot connect to service' ? '无法连接到服务！' : '上传或分析失败。';
        });
    });

});
