document.addEventListener('DOMContentLoaded', () => {
    const analyzeBtn = document.getElementById('analyzeBtn');
    const statusDiv = document.getElementById('status');
    const resultDiv = document.getElementById('result');

    analyzeBtn.addEventListener('click', async () => {
        analyzeBtn.disabled = true;
        statusDiv.textContent = "⏳ Analyzing... This may take a moment.";
        statusDiv.style.color = "#0056b3";
        resultDiv.innerHTML = ""; // Clear previous results

        try {
            // Get current tab URL
            const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
            if (!tab || (!tab.url.includes("youtube.com/watch") && !tab.url.includes("youtu.be/"))) {
                throw new Error("Please use this extension on a YouTube video page.");
            }

            // Sanitizer: Remove time stamps and playlist parameters (e.g., &t=, &list=)
            const cleanUrl = tab.url.split('&')[0];

            // Call Backend API via Direct IP (V4.9 Hotfix)
            const response = await fetch("http://200.234.239.63:8000/analyze", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ video_url: cleanUrl })
            });

            if (!response.ok) {
                let errorData;
                try {
                    errorData = await response.json();
                } catch (e) { }
                const reason = errorData?.error_message || errorData?.detail || `HTTP ${response.status}`;
                throw new Error(`Server Issue: ${reason}`);
            }

            const data = await response.json();

            if (data.status === "error") {
                throw new Error(data.error_message || "The AI agent could not process this video.");
            }

            if (!data || !data.bilingual_summaries) {
                throw new Error("Empty response from server.");
            }

            renderResults(data);
            statusDiv.textContent = "";

        } catch (error) {
            statusDiv.textContent = `❌ ${error.message}`;
            statusDiv.style.color = "#dc3545"; // Modern red
            console.error("Popup Error:", error);
        } finally {
            analyzeBtn.disabled = false;
        }
    });

    function renderResults(data) {
        // Render Prompt Section (The "Gold")
        if (data.executable_prompts && data.executable_prompts.length > 0) {
            const promptSection = document.createElement('div');
            promptSection.className = "section";
            promptSection.innerHTML = "<h4>✨ Executable Prompts</h4>";

            data.executable_prompts.forEach(p => {
                const pBox = document.createElement('div');
                pBox.className = "prompt-box";
                pBox.innerHTML = `
                    <div class="prompt-header">
                        <span class="platform-tag">${p.platform}</span>
                        <strong>${p.title}</strong>
                    </div>
                    <div class="prompt-content" id="p-${Math.random().toString(36).substr(2, 9)}">${p.prompt_text}</div>
                    <button class="copy-btn">📋 Copy Prompt</button>
                    <div class="copy-feedback">Copied!</div>
                `;

                // Add Copy Functionality
                const copyBtn = pBox.querySelector('.copy-btn');
                const promptText = p.prompt_text;
                const feedback = pBox.querySelector('.copy-feedback');

                copyBtn.addEventListener('click', () => {
                    navigator.clipboard.writeText(promptText).then(() => {
                        feedback.style.display = 'block';
                        setTimeout(() => { feedback.style.display = 'none'; }, 2000);
                    });
                });

                promptSection.appendChild(pBox);
            });
            resultDiv.appendChild(promptSection);
        }

        // Render Summary Section
        const summaryDiv = document.createElement('div');
        summaryDiv.className = "section";
        summaryDiv.innerHTML = "<div class=\"section-header\"><h4>📝 Knowledge Extract</h4><button class=\"copy-section-btn\">📋 Copy Section</button></div>";

        const langKey = Object.keys(data.bilingual_summaries || {})[0];
        const summaryObj = (langKey && data.bilingual_summaries[langKey]) || {};
        const summaryText = summaryObj.summary_text || "No summary available.";
        const keyPoints = summaryObj.key_points || [];

        // Simple HTML formatting for common agent output
        let formattedText = summaryText
            .replace(/\n\n/g, '<p>')
            .replace(/\n/g, '<br>')
            .replace(/\|/g, '<span class="table-pipe">|</span>');

        summaryDiv.innerHTML += `<div class="summary-box">${formattedText}</div>`;

        if (keyPoints.length > 0) {
            summaryDiv.innerHTML += `<div class="steps-box"><h5>✅ Actionable Steps</h5><ol>${keyPoints.map(k => `<li>${k}</li>`).join('')}</ol></div>`;
        }

        const copySectionBtn = summaryDiv.querySelector('.copy-section-btn');
        copySectionBtn.addEventListener('click', () => {
            const stepsText = keyPoints.length ? `\n\nActionable Steps:\n${keyPoints.map((k, i) => `${i + 1}. ${k}`).join('\n')}` : "";
            navigator.clipboard.writeText(`${summaryText}${stepsText}`).then(() => {
                copySectionBtn.textContent = "✅ Copied";
                setTimeout(() => { copySectionBtn.textContent = "📋 Copy Section"; }, 2000);
            });
        });

        resultDiv.appendChild(summaryDiv);
    }
});
