
// --- GLOBAL STATE ---
let currentExportFilename = null;
const BASE_URL = "http://200.234.239.63:8000"; // Reverted to IP until Domain DNS propagates

document.addEventListener('DOMContentLoaded', () => {
    const analyzeBtn = document.getElementById('analyzeBtn');
    const statusDiv = document.getElementById('status');
    const resultDiv = document.getElementById('result');
    const progressContainer = document.getElementById('progressContainer');
    const progressBar = document.getElementById('progressBar');
    const progressLabel = document.getElementById('progressLabel');
    const progressPercent = document.getElementById('progressPercent');
    const exportMdBtn = document.getElementById('exportMdBtn');
    const targetLangSelect = document.getElementById('targetLang');

    // --- PROGRESS LOGIC ---
    let progressInterval = null;

    function startProgressSimulation() {
        clearInterval(progressInterval);
        progressBar.style.width = '0%';
        progressPercent.textContent = '0%';
        progressLabel.textContent = "Initializing...";

        // --- HEARTBEAT START ---
        const logo = document.querySelector('.logo-img');
        if (logo) logo.classList.add('heartbeat');
        // -----------------------

        const startTime = Date.now();
        const duration = 65000; // 65 seconds total

        progressInterval = setInterval(() => {
            const elapsed = Date.now() - startTime;
            let percent = Math.min((elapsed / duration) * 100, 95); // Cap at 95% until done

            // Phase Logic
            let label = "Processing...";
            if (percent < 20) label = "🎙️ Transcribing Audio...";
            else if (percent < 50) label = "🧠 Analyzing Visuals & Context...";
            else if (percent < 90) label = "✍️ Drafting Strategy & Reports...";
            else label = "✨ Finalizing Output...";

            updateProgress(Math.round(percent), label);

        }, 500);
    }

    function updateProgress(percent, label) {
        progressBar.style.width = `${percent}%`;
        progressPercent.textContent = `${percent}%`;
        progressLabel.textContent = label;
    }

    function completeProgress() {
        clearInterval(progressInterval);

        // --- HEARTBEAT STOP ---
        const logo = document.querySelector('.logo-img');
        if (logo) logo.classList.remove('heartbeat');
        // ----------------------

        updateProgress(100, "✅ Analysis Complete!");
        setTimeout(() => { progressContainer.classList.add('hidden'); }, 1500);
    }

    analyzeBtn.addEventListener('click', async () => {
        const targetLang = targetLangSelect.value;

        analyzeBtn.disabled = true;
        exportMdBtn.classList.add('hidden');
        resultDiv.innerHTML = "";
        statusDiv.textContent = "";
        progressContainer.classList.remove('hidden');

        currentExportFilename = null;
        try {
            startProgressSimulation();

            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 open a YouTube video first.");
            }

            const cleanUrl = tab.url.split('&')[0];

            // Execute script to get title from the page content (more reliable than tab.title)
            const [result] = await chrome.scripting.executeScript({
                target: { tabId: tab.id },
                func: () => {
                    const h1 = document.querySelector('h1.ytd-video-primary-info-renderer') || document.querySelector('h1');
                    return h1 ? h1.innerText.trim() : document.title.replace(' - YouTube', '');
                }
            });

            const videoTitle = result.result || "YouTube Video";
            console.log("Captured Title:", videoTitle);

            // Progress managed by simulation

            const response = await fetch(`${BASE_URL}/analyze`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-Owner-Secret": "GEEX_OWNER_SECRET_2026" // Master Key for Owner Bypass (V5.6)
                },
                body: JSON.stringify({
                    video_url: cleanUrl,
                    target_language: targetLang,
                    video_title: videoTitle
                })
            });

            // Progress managed by simulation

            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();
            console.log("API RAW Response:", data);
            console.log("DEBUG: Filename received:", data.filename);

            // Progress managed by simulation

            if (data.status === "error") {
                throw new Error(data.error_message || "Analysis failed.");
            }

            completeProgress();

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

            try {
                renderResults(data);
            } catch (renderError) {
                console.error("Rendering UI partial error:", renderError);
                // Continue to enable export button even if UI rendering glitches
            }

            try {
                if (data.filename) {
                    currentExportFilename = data.filename;
                    console.log("Analysis Success, filename is:", data.filename);
                    exportMdBtn.classList.remove('hidden');
                } else {
                    exportMdBtn.classList.add('hidden');
                }
            } catch (e) {
                console.error("Export button error:", e);
            }

        } catch (error) {
            statusDiv.textContent = `❌ ${error.message}`;
            statusDiv.style.color = "#dc3545";
            progressContainer.classList.add('hidden');
        } finally {
            analyzeBtn.disabled = false;
        }
    });

    exportMdBtn.addEventListener('click', () => {
        try {
            // Rollback to v3.6 stable download method
            window.open(`${BASE_URL}/download/latest-md`, '_blank');
        } catch (e) {
            console.error("Export click error:", e);
        }
    });

    function renderResults(data) {
        // Prompts Section
        if (data.executable_prompts && data.executable_prompts.length > 0) {
            const promptSection = document.createElement('div');
            promptSection.className = "section";
            promptSection.innerHTML = "<div class=\"section-header\"><h4>✨ Executable Prompts</h4><button class=\"copy-section-btn\">📋 Copy Section</button></div>";

            data.executable_prompts.forEach(p => {
                const pBox = document.createElement('div');
                pBox.className = "prompt-box";
                const promptId = `p-${Math.random().toString(36).substr(2, 9)}`;

                // V5.1 Logic: Restrict Refine Button
                const isRefinable = p.platform === 'Architect' || p.platform === 'General' || p.title.includes('Meta-Prompt') || p.title.includes('Blueprint');
                const refineBtnHtml = isRefinable
                    ? `<button class="refine-btn" data-pid="${promptId}" data-plat="${p.platform}">✨ Refine</button>`
                    : '';

                pBox.innerHTML = `
                    <div class="prompt-header">
                        <span class="platform-tag">${p.platform}</span>
                        <strong>${p.title}</strong>
                    </div>
                    <div class="prompt-content" id="${promptId}">${p.prompt_text}</div>
                    <div class="prompt-actions" style="display:flex; justify-content:space-between; margin-top:10px;">
                        <button class="copy-btn">📋 Copy</button>
                        ${refineBtnHtml}
                    </div>
                    <div class="refine-ui-container" id="rui-${promptId}"></div>
                `;

                // Copy Logic
                pBox.querySelector('.copy-btn').addEventListener('click', (e) => {
                    const text = document.getElementById(promptId).textContent;
                    navigator.clipboard.writeText(text).then(() => {
                        e.target.textContent = "✅ Copied!";
                        setTimeout(() => { e.target.textContent = "📋 Copy"; }, 2000);
                    });
                });

                // Refine Logic (Interactive Studio)
                if (isRefinable) {
                    pBox.querySelector('.refine-btn').addEventListener('click', (e) => {
                        const container = document.getElementById(`rui-${promptId}`);
                        // Toggle UI
                        if (container.innerHTML) {
                            container.innerHTML = "";
                            return;
                        }

                        container.innerHTML = `
                            <div class="refine-container">
                                <div class="refine-input-group">
                                    <input type="text" class="refine-input" placeholder="Make it simpler / Add error handling..." />
                                    <button class="refine-submit">🪄 Go</button>
                                </div>
                            </div>
                        `;

                        const input = container.querySelector('.refine-input');
                        const submit = container.querySelector('.refine-submit');

                        submit.addEventListener('click', async () => {
                            const instruction = input.value;
                            if (!instruction) return;

                            input.disabled = true;
                            submit.textContent = "⏳";

                            try {
                                const originalText = document.getElementById(promptId).textContent;
                                const res = await fetch(`${BASE_URL}/api/refine`, {
                                    method: 'POST',
                                    headers: { 'Content-Type': 'application/json' },
                                    body: JSON.stringify({
                                        prompt_text: originalText,
                                        instruction: instruction,
                                        platform: p.platform
                                    })
                                });

                                const json = await res.json();

                                // Persistent Result Update (V5.1 Fix)
                                const contentDiv = document.getElementById(promptId);
                                contentDiv.style.transition = "all 0.5s ease";
                                contentDiv.style.opacity = '0.5';

                                setTimeout(() => {
                                    contentDiv.textContent = json.refined_prompt;
                                    contentDiv.style.opacity = '1';
                                    contentDiv.style.borderLeft = "4px solid #6366f1";
                                    contentDiv.style.backgroundColor = "#f8f9fb";
                                    contentDiv.style.padding = "8px";
                                    contentDiv.style.borderRadius = "4px";
                                }, 300);

                                container.innerHTML = `<div style="color:#28a745; font-weight:bold; font-size:0.85em; margin-top:5px; text-align:right;">✅ Refined Successfully</div>`;
                                setTimeout(() => container.innerHTML = "", 2500);

                            } catch (err) {
                                console.error(err);
                                submit.textContent = "❌ Error";
                                input.disabled = false;
                            }
                        });
                    });
                }

                promptSection.appendChild(pBox);
            });

            // ... Copy Section logic remains same ...
            const copySectionBtn = promptSection.querySelector('.copy-section-btn');
            if (copySectionBtn) {
                copySectionBtn.addEventListener('click', () => {
                    const sectionText = data.executable_prompts.map(p => `${p.title}\n${p.prompt_text}`).join('\n\n');
                    navigator.clipboard.writeText(sectionText).then(() => {
                        copySectionBtn.textContent = "✅ Copied";
                        setTimeout(() => { copySectionBtn.textContent = "📋 Copy Section"; }, 2000);
                    });
                });
            }

            resultDiv.appendChild(promptSection);
        }

        // Summary & Blueprint Section
        const summaryDiv = document.createElement('div');
        summaryDiv.className = "section";
        summaryDiv.innerHTML = "<div class=\"section-header\"><h4>📝 Architectural Blueprint</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 || [];

        // Executive Brief
        summaryDiv.innerHTML += `<div class="summary-box" style="margin-bottom:15px; font-style:italic; border-left:3px solid #ccc; padding-left:10px;">${summaryText}</div>`;

        // 4-Pillar Blueprint / Actionable Steps
        if (keyPoints.length > 0) {
            const stepsContainer = document.createElement('div');
            stepsContainer.className = "steps-box";
            stepsContainer.innerHTML = "<h5>🏗️ Strategic Pillars</h5>";

            keyPoints.forEach(point => {
                // Check if it matches "Phase X: Title - Content" pattern
                const phaseMatch = point.match(/^(Phase \d+:.*?)(?:-|:)(.*)/s);

                if (phaseMatch) {
                    // Render as Blueprint Card
                    const title = phaseMatch[1].trim();
                    const content = phaseMatch[2].trim();
                    stepsContainer.innerHTML += `
                        <div class="blueprint-card">
                            <span class="blueprint-phase">${title}</span>
                            <div class="blueprint-content">${content}</div>
                        </div>
                    `;
                } else {
                    // Fallback to list for non-blueprint content
                    if (!stepsContainer.querySelector('ul')) stepsContainer.innerHTML += '<ul>';
                    stepsContainer.querySelector('ul').insertAdjacentHTML('beforeend', `<li>${point}</li>`);
                }
            });
            summaryDiv.appendChild(stepsContainer);
        }

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

        resultDiv.appendChild(summaryDiv);
    }

    // Support Email Copy Logic (V5.3)
    const copyEmailBtn = document.getElementById('copyEmailBtn');
    const supportEmail = document.getElementById('supportEmail');

    if (copyEmailBtn && supportEmail) {
        copyEmailBtn.addEventListener('click', () => {
            const email = supportEmail.textContent;
            navigator.clipboard.writeText(email).then(() => {
                const originalText = copyEmailBtn.textContent;
                copyEmailBtn.textContent = "✅ Copied";
                copyEmailBtn.style.borderColor = "#28a745";
                copyEmailBtn.style.color = "#28a745";

                setTimeout(() => {
                    copyEmailBtn.textContent = originalText;
                    copyEmailBtn.style.borderColor = "#ddd";
                    copyEmailBtn.style.color = "#555";
                }, 2000);
            });
        });
    }
});
