document.addEventListener('DOMContentLoaded', function() {
    const scanBtn = document.getElementById('scanBtn');
    const loginSection = document.getElementById('loginSection');
    const scanSection = document.getElementById('scanSection');
    const resultArea = document.getElementById('resultArea');

    // User Info Elements
    const userInfo = document.getElementById('userInfo');
    const userNameEl = document.getElementById('userName');
    const userPlanEl = document.getElementById('userPlan');
    const upgradeMessage = document.getElementById('upgradeMessage');

    // Data Elements
    const videoTitleEl = document.getElementById('videoTitle');
    const totalLinksEl = document.getElementById('totalLinks');
    const brokenLinksEl = document.getElementById('brokenLinks');
    const seoScoreEl = document.getElementById('seoScore');
    const seoBarEl = document.getElementById('seoBar');
    const helperText = document.querySelector('.helper-text');

    // Helper function to reset the SEO bar
    function resetSeoBar() {
        seoBarEl.style.width = '0%';
        seoBarEl.style.backgroundColor = '#e5e7eb'; // Default gray
        seoScoreEl.textContent = '0/10';
    }

    scanBtn.addEventListener('click', async function() {
        // Reset UI State before new scan
        const originalText = scanBtn.innerHTML;
        scanBtn.innerHTML = 'Analyzing...';
        scanBtn.disabled = true;
        helperText.textContent = "Fetching video metadata...";
        helperText.style.color = ""; // Reset error color
        resultArea.classList.add('hidden');
        upgradeMessage.classList.add('hidden');
        resetSeoBar(); // Reset bar visual

        try {
            // 1. Get Current Tab
            let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

            if (!tab || !tab.url || !tab.url.includes("youtube.com/watch")) {
                throw new Error("Please open a valid YouTube video page.");
            }

            // 2. Call API
            // উল্লেখ্য: লোকাল টেস্ট করার সময় http://127.0.0.1:5000 ব্যবহার করবেন।
            // লাইভ সার্ভারে আপলোড হলে আপনার ডোমেইন ব্যবহার করবেন।
            const apiUrl = 'https://brokentube.com/api/extension/scan';

            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    // 'Origin' হেডার ব্রাউজার অটোমেটিক পাঠায়, ম্যানুয়ালি সেট করার দরকার নেই
                },
                credentials: 'include', // কুকি পাঠানোর জন্য জরুরি
                body: JSON.stringify({ video_url: tab.url })
            });

            const data = await response.json();

            // 3. Auth Check (Not Logged In)
            if (response.status === 401 && data.login_required) {
                scanSection.classList.add('hidden');
                loginSection.classList.remove('hidden');
                userInfo.classList.add('hidden');
                return; // Stop execution here
            }

            // Handle other API errors
            if (!response.ok) {
                throw new Error(data.error || "Scan failed due to server error.");
            }

            // 4. Show Results if successful
            scanSection.classList.remove('hidden');
            loginSection.classList.add('hidden');
            resultArea.classList.remove('hidden');

            // Update User Info in Header
            if (data.user_name) {
                userNameEl.textContent = data.user_name;
                userInfo.classList.remove('hidden');
            }

            const planName = data.plan ? data.plan.toUpperCase() : 'FREE';
            userPlanEl.textContent = planName;

            // Badge Color Logic
            userPlanEl.className = 'status-badge'; // Reset classes
            if(data.is_paid) {
                userPlanEl.classList.add('badge-pro');
            } else {
                userPlanEl.classList.add('badge-free');
            }

            // Populate Basic Data
            videoTitleEl.textContent = data.video_title || "Unknown Title";
            totalLinksEl.textContent = data.total_links || 0;

            // --- UPDATED SEO SCORE LOGIC ---

            // 1. Get numeric value safely (prefer 'seo_value' from backend)
            // যদি seo_value না আসে, তবে seo_score স্ট্রিং পার্স করার চেষ্টা করবে, তাও না হলে ০
            let scoreVal = (data.seo_value !== undefined && data.seo_value !== null)
                            ? data.seo_value
                            : (parseInt(data.seo_score) || 0);

            // Ensure range is 0-10
            scoreVal = Math.min(Math.max(scoreVal, 0), 10);

            // 2. Set Display Text (e.g., "7/10")
            seoScoreEl.textContent = data.seo_score || `${scoreVal}/10`;

            // 3. Set Bar Width with tiny delay for smooth CSS transition
            // (CSS এ transition প্রপার্টি থাকলে এটি সুন্দর দেখাবে)
            setTimeout(() => {
                seoBarEl.style.width = `${scoreVal * 10}%`;
            }, 50);

            // 4. Set Bar Color based on score
            let barColor = '#f87171'; // Default Red (< 4)
            if (scoreVal >= 7) {
                barColor = '#4ade80'; // Green (7-10)
            } else if (scoreVal >= 4) {
                barColor = '#facc15'; // Yellow (4-6)
            }
            seoBarEl.style.backgroundColor = barColor;


            // --- Broken Link Logic ---
            if (data.is_paid) {
                // Pro users see the count
                brokenLinksEl.textContent = data.broken_count !== undefined ? data.broken_count : 0;
                // Color based on broken count
                brokenLinksEl.style.color = (data.broken_count > 0) ? '#f87171' : '#4ade80';
            } else {
                // Free users see lock
                brokenLinksEl.textContent = "🔒";
                brokenLinksEl.style.color = "inherit";
                if(data.total_links > 0) {
                    upgradeMessage.classList.remove('hidden');
                }
            }

            helperText.textContent = "Scan Complete!";

        } catch (error) {
            console.error("Extension Error:", error);
            // Show error message in UI
            helperText.textContent = error.message || "An unexpected error occurred.";
            helperText.style.color = "#f87171"; // Red color for error

            // Hide results if they were partially shown
             resultArea.classList.add('hidden');
        } finally {
            // Reset button state
            scanBtn.innerHTML = originalText;
            scanBtn.disabled = false;
        }
    });
});