// --- GLOBAL VARIABLES ---
let isDrawing = false;
let startX, startY;
let overlay, selectionBox;
let aiCard = null;

let isDraggingCard = false;
let cardDragOffsetX = 0;
let cardDragOffsetY = 0;

let currentImageB64 = "";
let chatHistory = [];
let currentScanId = 0; 

function dataURLtoBlob(dataurl) {
    let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}

// 🚨 Smart Retry: Completely silent, handles all network hiccups invisibly.
async function fetchWithSmartRetry(url, options, retries = 3) {
    for (let i = 0; i <= retries; i++) {
        try {
            const res = await fetch(url, options);
            
            // Render Server Cold Starts
            if (!res.ok && (res.status === 502 || res.status === 503 || res.status === 504)) {
                if (i === retries) throw new Error("Server took too long to wake up. Please try again.");
                await new Promise(r => setTimeout(r, 4000));
                continue;
            }
            
            // Auth and Hard Limits
            if (res.status === 401) throw new Error("SILENT_AUTH_ERROR");
            if (res.status === 403) throw new Error("AUTH_LIMIT_ERROR");
            
            if (!res.ok) {
                const errText = await res.text();
                throw new Error(`Server Error ${res.status}: ${errText}`);
            }
            
            return await res.json();

        } catch (err) {
            if (err.message === "SILENT_AUTH_ERROR" || err.message === "AUTH_LIMIT_ERROR") throw err;
            if (i === retries || err.name === 'AbortError') throw err;
            await new Promise(r => setTimeout(r, 2000));
        }
    }
}

function killCrosshair() {
    document.body.style.cursor = 'default'; 
    document.body.style.overflow = ''; 
    document.documentElement.style.overflow = '';

    document.querySelectorAll('#ai-glass-ceiling, #ai-selection-box, #ai-close-btn, #kogvio-auth-wakeup').forEach(el => el.remove());
    
    isDrawing = false;
    overlay = null;
    selectionBox = null;
}

function activateCrosshair() {
    killCrosshair();

    document.body.style.overflow = 'hidden'; 
    document.documentElement.style.overflow = 'hidden';

    overlay = document.createElement('div');
    overlay.id = 'ai-glass-ceiling';
    overlay.style.position = 'fixed';
    overlay.style.top = '0';
    overlay.style.left = '0';
    overlay.style.width = '100vw';
    overlay.style.height = '100vh';
    overlay.style.cursor = 'crosshair';
    overlay.style.zIndex = '2147483645'; 
    overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.4)'; 

    selectionBox = document.createElement('div');
    selectionBox.id = 'ai-selection-box';
    selectionBox.style.position = 'fixed';
    selectionBox.style.border = '2px dashed #A64DFF';
    selectionBox.style.backgroundColor = 'rgba(166, 77, 255, 0.2)';
    selectionBox.style.display = 'none';
    selectionBox.style.zIndex = '2147483646'; 
    selectionBox.style.pointerEvents = 'none'; 

    const closeBtn = document.createElement('div');
    closeBtn.id = 'ai-close-btn';
    closeBtn.innerHTML = '<span style="opacity: 0.7; margin-right: 6px;">X</span> Cancel <span style="opacity: 0.4; font-size: 11px; margin-left: 6px; border: 1px solid rgba(255,255,255,0.2); padding: 2px 4px; border-radius: 4px;">ESC</span>';
    closeBtn.style.position = 'fixed';
    closeBtn.style.top = '24px';
    closeBtn.style.right = '24px';
    closeBtn.style.padding = '8px 16px';
    closeBtn.style.backgroundColor = 'rgba(30, 30, 36, 0.85)'; 
    closeBtn.style.backdropFilter = 'blur(8px)'; 
    closeBtn.style.border = '1px solid rgba(255, 255, 255, 0.1)';
    closeBtn.style.color = '#FFFFFF';
    closeBtn.style.borderRadius = '24px'; 
    closeBtn.style.fontFamily = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif';
    closeBtn.style.fontSize = '13px';
    closeBtn.style.fontWeight = '500';
    closeBtn.style.cursor = 'pointer';
    closeBtn.style.zIndex = '2147483647'; 
    closeBtn.style.display = 'flex';
    closeBtn.style.alignItems = 'center';

    closeBtn.addEventListener('mousedown', (e) => { e.stopPropagation(); killCrosshair(); });

    document.body.appendChild(overlay);
    document.body.appendChild(selectionBox);
    document.body.appendChild(closeBtn);

    const authWakeup = document.createElement('iframe');
    authWakeup.id = 'kogvio-auth-wakeup';
    authWakeup.src = 'https://kogvio-landing-page.vercel.app';
    authWakeup.style.display = 'none';
    document.body.appendChild(authWakeup);

    function getX(e) { return e.touches ? e.touches[0].clientX : e.clientX; }
    function getY(e) { return e.touches ? e.touches[0].clientY : e.clientY; }

    const startSelection = (e) => {
        if (e.touches) e.preventDefault(); 
        isDrawing = true;
        startX = getX(e);
        startY = getY(e);
        selectionBox.style.left = startX + 'px';
        selectionBox.style.top = startY + 'px';
        selectionBox.style.width = '0px';
        selectionBox.style.height = '0px';
        selectionBox.style.display = 'block';
    };

    const moveSelection = (e) => {
        if (!isDrawing) return;
        if (e.touches) e.preventDefault(); 
        const currentX = getX(e);
        const currentY = e.touches ? e.touches[0].clientY : e.clientY;
        selectionBox.style.width = Math.abs(currentX - startX) + 'px';
        selectionBox.style.height = Math.abs(currentY - startY) + 'px';
        selectionBox.style.left = Math.min(currentX, startX) + 'px';
        selectionBox.style.top = Math.min(currentY, startY) + 'px';
    };

    const endSelection = (e) => {
        if (!isDrawing) return;
        const rect = selectionBox.getBoundingClientRect();
        
        selectionBox.style.display = 'none';
        if (overlay) overlay.style.display = 'none';

        setTimeout(() => {
            killCrosshair(); 
            if (rect.width > 10 && rect.height > 10) cropImage(rect); 
        }, 50);
    };

    overlay.addEventListener('mousedown', startSelection);
    overlay.addEventListener('mousemove', moveSelection);
    overlay.addEventListener('mouseup', endSelection);
    overlay.addEventListener('touchstart', startSelection, { passive: false });
    overlay.addEventListener('touchmove', moveSelection, { passive: false });
    overlay.addEventListener('touchend', endSelection);
}

window.addEventListener('keydown', (e) => {
    if ((e.key === 'Escape' || e.key === 'Esc') && document.getElementById('ai-glass-ceiling')) {
        e.preventDefault(); e.stopPropagation(); killCrosshair();
    }
}, true); 

// 🚨 NEW UX: Premium, professional Auth Recovery UI
function injectAuthRecovery(container) {
    container.innerHTML = `
        <div style="background: rgba(20, 20, 25, 0.85); border: 1px solid rgba(255, 255, 255, 0.1); padding: 24px 20px; border-radius: 12px; margin: 12px 0; text-align: center; box-shadow: 0 10px 30px rgba(0,0,0,0.4); backdrop-filter: blur(8px);">
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#A64DFF" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="margin: 0 auto 12px auto; opacity: 0.9;">
                <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
            </svg>
            <strong style="font-size: 14px; color: #FFFFFF; display: block; margin-bottom: 8px; font-weight: 600; letter-spacing: 0.2px;">Authentication Required</strong>
            <span style="font-size: 13px; color: #A1A1AA; line-height: 1.6; display: block; margin-bottom: 20px;">Your secure session has expired. Please authenticate to resume processing.</span>
            <button id="quick-reconnect-btn" style="background: #EDEDED; color: #18181B; border: none; padding: 10px 16px; border-radius: 8px; font-weight: 600; font-size: 13px; cursor: pointer; width: 100%; transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1); display: flex; align-items: center; justify-content: center; gap: 8px;">
                Authenticate
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="opacity: 0.8;">
                    <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
                    <polyline points="15 3 21 3 21 9"></polyline>
                    <line x1="10" y1="14" x2="21" y2="3"></line>
                </svg>
            </button>
        </div>
    `;
    
    const reconBtn = container.querySelector('#quick-reconnect-btn');
    if (reconBtn) {
        reconBtn.addEventListener('mouseover', () => {
            reconBtn.style.transform = 'scale(1.02)';
            reconBtn.style.background = '#FFFFFF';
        });
        reconBtn.addEventListener('mouseout', () => {
            reconBtn.style.transform = 'scale(1)';
            reconBtn.style.background = '#EDEDED';
        });
        reconBtn.addEventListener('click', () => {
            window.open('https://kogvio-landing-page.vercel.app', '_blank');
            
            // Add a dynamic spinner when clicked
            if (!document.getElementById('spin-style')) {
                const style = document.createElement('style');
                style.id = 'spin-style';
                style.innerHTML = `@keyframes spin { to { transform: rotate(360deg); } }`;
                document.head.appendChild(style);
            }
            
            reconBtn.innerHTML = `<div style="width: 14px; height: 14px; border: 2px solid rgba(0,0,0,0.2); border-top-color: #000; border-radius: 50%; animation: spin 1s linear infinite;"></div> Awaiting Connection...`;
            reconBtn.style.opacity = '0.8';
            reconBtn.style.pointerEvents = 'none';
            
            setTimeout(() => { if (aiCard) { document.body.removeChild(aiCard); aiCard = null; } }, 3000);
        });
    }
}

function forceShowError(msg, rect) {
    if (!aiCard) return; 
    const loader = aiCard.querySelector('#as-loader');
    if (loader) loader.style.display = 'none';
    
    const previewContainer = aiCard.querySelector('#as-preview-container');
    if (previewContainer && !aiCard.querySelector('#initial-error-box')) {
        previewContainer.insertAdjacentHTML('beforeend', `
            <div id="initial-error-box" style="background:rgba(255,77,77,0.1);border:1px solid #FF4D4D;color:#FF4D4D;padding:12px;border-radius:8px;margin-top:12px;text-align:left;width:90%;">
                <strong style="font-size:13px;">Notice</strong><br>
                <span style="font-size:12px;opacity:0.9;">${msg}</span>
                <div style="margin-top:12px;text-align:right;">
                    <button id="retry-initial-scan-btn" style="background:#FF4D4D;color:white;border:none;padding:6px 12px;border-radius:4px;cursor:pointer;font-weight:bold;font-size:11px;">↻ Retry Scan</button>
                </div>
            </div>
        `);
        const retryBtn = aiCard.querySelector('#retry-initial-scan-btn');
        if (retryBtn) {
            retryBtn.addEventListener('click', () => {
                if (aiCard) { document.body.removeChild(aiCard); aiCard = null; }
                cropImage(rect); 
            });
        }
    } else if (!previewContainer) {
        updateAICard(`Error: ${msg}`);
    }
    const inputArea = aiCard.querySelector('#ai-followup-input');
    const sendBtn = aiCard.querySelector('#ai-send-btn');
    if(inputArea) inputArea.disabled = false;
    if(sendBtn) sendBtn.disabled = false;
}

function cropImage(rect) {
    currentScanId = Date.now();
    const myScanId = currentScanId;

    displayAICard(`
        <div id="as-preview-container" style="margin-bottom: 16px; text-align: center; display: flex; flex-direction: column; align-items: center;">
            <img id="as-preview-img" src="" style="max-width: 100%; max-height: 220px; border-radius: 8px; border: 1px solid rgba(255,255,255,0.1); box-shadow: 0 10px 30px rgba(0,0,0,0.5); display: none; margin-bottom: 12px; object-fit: contain;">
            
            <div id="as-loader" style="width: 100%; padding: 10px 20px; box-sizing: border-box;">
                <div style="display: flex; flex-direction: column; gap: 10px; margin-top: 10px;">
                    <div class="aura-shimmer-line" style="height: 12px; width: 90%;"></div>
                    <div class="aura-shimmer-line" style="height: 12px; width: 100%;"></div>
                    <div class="aura-shimmer-line" style="height: 12px; width: 75%;"></div>
                </div>
            </div>
        </div>
    `);

    const inputArea = aiCard.querySelector('#ai-followup-input');
    const sendBtn = aiCard.querySelector('#ai-send-btn');
    if(inputArea) inputArea.disabled = true;
    if(sendBtn) { sendBtn.disabled = true; sendBtn.style.opacity = '0.5'; }

    try {
        let screenshotResponded = false;
        const screenshotTimeout = setTimeout(() => {
            if (!screenshotResponded && myScanId === currentScanId) forceShowError("Screenshot capture timed out. Please refresh the page.", rect);
        }, 15000);

        chrome.runtime.sendMessage({action: "take_screenshot"}, (response) => {
            screenshotResponded = true;
            clearTimeout(screenshotTimeout);
            if (myScanId !== currentScanId) return;
            
            if (chrome.runtime.lastError || !response || !response.screenshotUrl) {
                forceShowError("Browser denied screenshot. Refresh the page and try again.", rect);
                return;
            }
            
            const img = new Image();
            img.onerror = () => {
                if (myScanId === currentScanId) forceShowError("Screenshot failed to process. Try again.", rect);
            };
            img.onload = () => {
                try {
                    if (myScanId !== currentScanId) return;

                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    const scale = window.devicePixelRatio;
                    canvas.width = rect.width * scale;
                    canvas.height = rect.height * scale;
                    ctx.drawImage(img, rect.left * scale, rect.top * scale, rect.width * scale, rect.height * scale, 0, 0, canvas.width, canvas.height);
                    const croppedDataUrl = canvas.toDataURL('image/png');
                    
                    if(aiCard) {
                        const previewImg = aiCard.querySelector('#as-preview-img');
                        if (previewImg) {
                            previewImg.src = croppedDataUrl;
                            previewImg.style.display = 'block';
                        }
                    }
                    
                    currentImageB64 = croppedDataUrl;
                    chatHistory = []; 

                    let authResponded = false;
                    const fallbackTimeout = setTimeout(() => {
                        if (!authResponded && myScanId === currentScanId) {
                            forceShowError("Authentication timeout. Ensure Kogvio is open in a tab.", rect);
                        }
                    }, 15000); 

                    chrome.runtime.sendMessage({ action: "get_auth_token" }, (authResponse) => {
                        authResponded = true;
                        clearTimeout(fallbackTimeout); 
                        if (myScanId !== currentScanId) return;

                        if (chrome.runtime.lastError) {
                            forceShowError("Extension connection lost. Please refresh the page.", rect);
                            return;
                        }
                        
                        const token = authResponse ? authResponse.token : null;
                        
                        if (!token) {
                            if(aiCard) {
                                const pImg = aiCard.querySelector('#as-preview-img');
                                if(pImg) pImg.style.display = 'none';
                                const loader = aiCard.querySelector('#as-loader');
                                if(loader) injectAuthRecovery(loader); // 🚨 Clean Reconnect UI
                                if(inputArea) inputArea.disabled = true;
                                if(sendBtn) sendBtn.disabled = true;
                            }
                            return;
                        }

                        const controller = new AbortController();
                        const signal = controller.signal;
                        const absoluteTimeout = setTimeout(() => controller.abort(), 120000); 

                        const blob = dataURLtoBlob(croppedDataUrl);
                        const formData = new FormData();
                        formData.append('file', blob, 'screenshot.png');
                        formData.append('prompt', 'Explain the core concepts in this image.');

                        fetchWithSmartRetry("https://aura-scholar-backend.onrender.com/analyze-image", {
                            method: "POST",
                            headers: { "Authorization": `Bearer ${token}` },
                            body: formData,
                            signal: signal 
                        })
                        .then(data => {
                            clearTimeout(absoluteTimeout);
                            if (myScanId !== currentScanId) return;

                            if(inputArea) { inputArea.disabled = false; inputArea.focus(); }
                            if(sendBtn) { sendBtn.disabled = false; sendBtn.style.opacity = '1'; }
                            
                            if (data.AI_Answer) {
                                if (data.AI_Answer.includes("⚠️")) {
                                    if (aiCard) {
                                        const pImg = aiCard.querySelector('#as-preview-img');
                                        if(pImg) pImg.style.display = 'none';
                                        
                                        let exactError = data.AI_Answer.replace("⚠️", "").replace(/\*\*/g, "").trim();
                                        const loader = aiCard.querySelector('#as-loader');
                                        
                                        if(loader) {
                                            // 🚨 AUTO-PILOT UX: Counts down and automatically retries!
                                            if (exactError.includes("limits reached") || exactError.includes("peak traffic")) {
                                                let timeLeft = 60;
                                                loader.innerHTML = `
                                                    <div style="background-color: rgba(255, 176, 32, 0.05); border: 1px solid rgba(255, 176, 32, 0.2); padding: 16px; border-radius: 8px; text-align: center; width: 90%;">
                                                        <div style="width: 24px; height: 24px; border: 3px solid rgba(255, 176, 32, 0.3); border-top-color: #FFB020; border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto 12px auto;"></div>
                                                        <strong style="font-size: 14px; color: #FFB020;">Google API Cooling Down</strong><br>
                                                        <span style="font-size: 12px; color: #E2E2E2; margin-top: 6px; display: block;">Auto-resuming in <span id="cd-timer" style="font-weight:bold; color:#fff;">60</span>s...</span>
                                                    </div>
                                                    <style>@keyframes spin { to { transform: rotate(360deg); } }</style>
                                                `;
                                                const timerSpan = aiCard.querySelector('#cd-timer');
                                                const cdInterval = setInterval(() => {
                                                    timeLeft--;
                                                    if (timerSpan) timerSpan.innerText = timeLeft;
                                                    if (timeLeft <= 0) {
                                                        clearInterval(cdInterval);
                                                        if (aiCard) { document.body.removeChild(aiCard); aiCard = null; }
                                                        cropImage(rect); // 🚨 Silently restarts the scan automatically!
                                                    }
                                                }, 1000);
                                            } else {
                                                loader.innerHTML = `
                                                    <div style="color: #FF4D4D; text-align: center; padding: 16px;">
                                                        <span style="font-size: 32px; display: block; margin-bottom: 12px;">⚠️</span>
                                                        <strong style="font-size: 14px; line-height: 1.5; display: block; margin-bottom: 16px;">${exactError}</strong>
                                                        <button id="retry-initial-btn" style="background-color: #FF4D4D; color: white; border: none; padding: 8px 16px; border-radius: 6px; cursor: pointer; font-weight: bold; font-size: 13px; display: inline-flex; align-items: center; gap: 6px;">↻ Retry Scan</button>
                                                    </div>
                                                `;
                                                const retryBtn = aiCard.querySelector('#retry-initial-btn');
                                                if (retryBtn) retryBtn.addEventListener('click', () => {
                                                     if (aiCard) { document.body.removeChild(aiCard); aiCard = null; }
                                                     cropImage(rect); 
                                                });
                                            }
                                        }
                                    }
                                } else {
                                    chatHistory.push({ role: "user", text: "Explain the core concepts in this image." });
                                    chatHistory.push({ role: "model", text: data.AI_Answer });
                                    if (aiCard) {
                                        const loader = aiCard.querySelector('#as-loader');
                                        if(loader) loader.style.display = 'none';
                                    }
                                    updateAICard(data.AI_Answer);
                                }
                            } else {
                                forceShowError("Server returned a blank answer.", rect);
                            }
                        })
                        .catch(err => {
                            clearTimeout(absoluteTimeout);
                            if (myScanId !== currentScanId) return;
                            
                            if (err.message === "AUTH_LIMIT_ERROR") {
                                if (aiCard) {
                                    const pImg = aiCard.querySelector('#as-preview-img');
                                    if(pImg) pImg.style.display = 'none';
                                    const loader = aiCard.querySelector('#as-loader');
                                    if(loader) {
                                        loader.innerHTML = `
                                            <div style="color: #A64DFF; text-align: center; padding: 16px; background: rgba(166, 77, 255, 0.05); border-radius: 8px; border: 1px solid rgba(166, 77, 255, 0.3);">
                                                <span style="font-size: 24px; display: block; margin-bottom: 8px;">👑</span>
                                                <strong style="font-size: 14px; color: white;">Daily Limit Reached</strong><br>
                                                <span style="font-size: 12px; opacity: 0.8; display: block; margin-top: 6px; color: #E2E2E2;">
                                                    You've used all 10 free scans for today.<br>
                                                    <a href="https://kogvio-landing-page.vercel.app/#pricing" target="_blank" style="background: #A64DFF; color: white; padding: 6px 12px; border-radius: 6px; text-decoration: none; font-weight: bold; margin-top: 12px; display: inline-block; transition: all 0.2s;">Upgrade to Pro</a>
                                                </span>
                                            </div>
                                        `;
                                    }
                                }
                            } else if (err.message === "SILENT_AUTH_ERROR") {
                                if (aiCard) {
                                    const pImg = aiCard.querySelector('#as-preview-img');
                                    if(pImg) pImg.style.display = 'none';
                                    const loader = aiCard.querySelector('#as-loader');
                                    if(loader) injectAuthRecovery(loader); // 🚨 Clean Reconnect UI
                                }
                            } else {
                                const msg = err.name === 'AbortError' ? "Request timed out. Please try again." : err.message;
                                forceShowError(msg, rect);
                            }
                        });
                    });
                } catch(canvasErr) {
                    if (myScanId === currentScanId) forceShowError(`Canvas Error: ${canvasErr.message}`, rect);
                }
            };
            img.src = response.screenshotUrl;
        });
    } catch(globalErr) {
        if (myScanId === currentScanId) forceShowError(`Unexpected Error: ${globalErr.message}`, rect);
    }
}

// --- 4. DRAGGABLE UI CARD BUILDER ---
function displayAICard(htmlContent) {
    document.querySelectorAll('#ai-scholar-card').forEach(el => el.remove());
    
    aiCard = document.createElement('div');
    aiCard.id = 'ai-scholar-card';
    aiCard.style.cssText = 'position:fixed;bottom:20px;right:20px;width:420px;height:500px;z-index:2147483647;overflow:hidden;resize:both;min-width:320px;min-height:350px;display:flex;flex-direction:column;';

    const styleBlock = document.createElement('style');
    styleBlock.innerHTML = `
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap');
        
        @keyframes auraSlideUp {
            0% { opacity: 0; transform: translateY(20px) scale(0.98); }
            100% { opacity: 1; transform: translateY(0) scale(1); }
        }
        
        #ai-scholar-card {
            font-family: 'Inter', -apple-system, sans-serif !important;
            animation: auraSlideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards;
            background: linear-gradient(145deg, rgba(30, 30, 36, 0.95), rgba(20, 20, 25, 0.98)) !important;
            box-shadow: 0 30px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255,255,255,0.08) inset !important;
            border-radius: 16px;
            backdrop-filter: blur(16px);
        }

        #ai-content-box::-webkit-scrollbar { width: 6px; }
        #ai-content-box::-webkit-scrollbar-track { background: transparent; }
        #ai-content-box::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.15); border-radius: 10px; }
        #ai-content-box::-webkit-scrollbar-thumb:hover { background: rgba(255, 255, 255, 0.3); }

        #ai-followup-input { transition: all 0.25s ease; font-family: 'Inter', sans-serif; }
        #ai-followup-input:focus { 
            border-color: #A64DFF !important; 
            box-shadow: 0 0 15px rgba(166, 77, 255, 0.2), 0 0 0 1px #A64DFF inset !important; 
            background-color: rgba(10, 10, 15, 0.8) !important;
        }

        #ai-send-btn { transition: all 0.25s cubic-bezier(0.16, 1, 0.3, 1); font-family: 'Inter', sans-serif; }
        #ai-send-btn:hover:not(:disabled) { 
            background-color: #B870FF !important; 
            transform: translateY(-2px); 
            box-shadow: 0 8px 20px rgba(166, 77, 255, 0.4);
        }
        #ai-send-btn:active:not(:disabled) { transform: translateY(0); }

        @keyframes shimmer {
            0% { transform: translateX(-100%); }
            100% { transform: translateX(100%); }
        }
        .aura-shimmer-line {
            position: relative; overflow: hidden; background: rgba(255, 255, 255, 0.05); border-radius: 4px;
        }
        .aura-shimmer-line::after {
            content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%;
            background: linear-gradient(90deg, transparent, rgba(166, 77, 255, 0.15), transparent);
            animation: shimmer 1.5s infinite ease-in-out;
        }

        @keyframes slideUpFade {
            from { opacity: 0; transform: translateY(12px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .chat-bubble-user {
            background: linear-gradient(135deg, #A64DFF, #7828D6);
            color: #FFFFFF;
            padding: 12px 18px;
            border-radius: 18px 18px 4px 18px;
            margin: 8px 0 16px auto;
            max-width: 85%;
            width: fit-content;
            box-shadow: 0 4px 14px rgba(166, 77, 255, 0.25), inset 0 1px 0 rgba(255, 255, 255, 0.2);
            animation: slideUpFade 0.3s cubic-bezier(0.2, 0.8, 0.2, 1) forwards;
            font-size: 13.5px;
            line-height: 1.5;
            letter-spacing: 0.2px;
        }

        .chat-bubble-ai {
            position: relative;
            background: rgba(30, 30, 35, 0.6);
            border: 1px solid rgba(255, 255, 255, 0.06);
            padding: 16px 18px;
            border-radius: 18px 18px 18px 4px;
            margin: 8px auto 16px 0;
            max-width: 92%;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
            animation: slideUpFade 0.3s cubic-bezier(0.2, 0.8, 0.2, 1) forwards;
            font-size: 13.5px;
            line-height: 1.6;
            color: #E2E2E2;
        }

        .typing-indicator {
            display: flex; gap: 5px; padding: 14px 18px;
            background: rgba(30, 30, 35, 0.6);
            border: 1px solid rgba(255, 255, 255, 0.04);
            border-radius: 18px 18px 18px 4px;
            width: fit-content; margin-bottom: 16px;
            animation: slideUpFade 0.3s cubic-bezier(0.2, 0.8, 0.2, 1) forwards;
        }
        .typing-dot {
            width: 6px; height: 6px; border-radius: 50%; background: #A64DFF;
            animation: typingBounce 1.4s infinite ease-in-out both;
        }
        .typing-dot:nth-child(1) { animation-delay: -0.32s; }
        .typing-dot:nth-child(2) { animation-delay: -0.16s; }
        @keyframes typingBounce {
            0%, 80%, 100% { transform: scale(0); opacity: 0.3; }
            40% { transform: scale(1); opacity: 1; box-shadow: 0 0 8px rgba(166,77,255,0.6); }
        }
    `;
    document.head.appendChild(styleBlock);
    
    const header = document.createElement('div');
    header.id = 'ai-drag-header';
    header.style.cssText = 'background:rgba(20, 20, 24, 0.5);padding:12px 16px;border-bottom:1px solid rgba(255, 255, 255, 0.08);display:flex;justify-content:space-between;align-items:center;cursor:grab;color:#fff;';
    
    const logoUrl = chrome.runtime.getURL("icon48.png");
    
    header.innerHTML = `
        <div style="display: flex; align-items: center; gap: 8px; pointer-events: none;">
            <img src="${logoUrl}" style="width: 18px; height: 18px; object-fit: contain;">
            <span style="font-weight: 600; font-size: 13px; color: #E2E2E2; letter-spacing: 0.5px; text-transform: uppercase;">Kogvio</span>
        </div>
        <div style="display: flex; gap: 12px; align-items: center;">
            <div id="ai-scan-new-btn" style="cursor: pointer; font-size: 11px; background: rgba(166,77,255,0.15); border: 1px solid rgba(166,77,255,0.4); padding: 4px 8px; border-radius: 4px; color: #E2E2E2; font-weight: 600; transition: all 0.2s ease;">
                + New Scan
            </div>
            <div id="ai-close-card-btn" style="cursor: pointer; padding: 0 4px;">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#888" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
            </div>
        </div>
    `;
    
    header.addEventListener('mousedown', (e) => {
        if(e.target.closest('#ai-scan-new-btn') || e.target.closest('#ai-close-card-btn')) return;
        isDraggingCard = true;
        header.style.cursor = 'grabbing';
        const rect = aiCard.getBoundingClientRect();
        cardDragOffsetX = e.clientX - rect.left;
        cardDragOffsetY = e.clientY - rect.top;
        
        aiCard.style.left = rect.left + 'px';
        aiCard.style.top = rect.top + 'px';
        aiCard.style.bottom = 'auto';
        aiCard.style.right = 'auto';
    });
    
    setTimeout(() => {
        aiCard.querySelector('#ai-close-card-btn').addEventListener('click', () => {
            document.body.removeChild(aiCard);
            aiCard = null;
        });
        
        const scanBtn = aiCard.querySelector('#ai-scan-new-btn');
        if (scanBtn) {
            scanBtn.addEventListener('mouseenter', () => scanBtn.style.backgroundColor = 'rgba(166,77,255,0.3)');
            scanBtn.addEventListener('mouseleave', () => scanBtn.style.backgroundColor = 'rgba(166,77,255,0.15)');
            scanBtn.addEventListener('click', () => {
                document.body.removeChild(aiCard);
                aiCard = null;
                activateCrosshair();
            });
        }
    }, 0);
    
    const contentBox = document.createElement('div');
    contentBox.id = 'ai-content-box';
    contentBox.style.cssText = 'padding:15px;flex:1;overflow-y:auto;line-height:1.6;';
    contentBox.innerHTML = htmlContent;
    
    const chatBox = document.createElement('div');
    chatBox.style.cssText = 'padding:10px 15px;background:rgba(0, 0, 0, 0.2);display:flex;gap:10px;';
    
    const inputField = document.createElement('input');
    inputField.type = 'text';
    inputField.id = 'ai-followup-input';
    inputField.placeholder = 'Ask a follow-up...';
    inputField.style.cssText = 'flex:1;padding:10px 12px;border-radius:6px;border:1px solid rgba(255, 255, 255, 0.1);background:rgba(0, 0, 0, 0.3);color:white;outline:none;';
    
    const sendBtn = document.createElement('button');
    sendBtn.id = 'ai-send-btn';
    sendBtn.innerText = 'Send';
    sendBtn.style.cssText = 'padding:10px 16px;background:#A64DFF;color:white;border:none;border-radius:6px;cursor:pointer;font-weight:bold;';
    
    const handleSend = () => {
        const userText = inputField.value.trim();
        if(!userText) return;
        
        contentBox.insertAdjacentHTML('beforeend', `
            <div class="chat-bubble-user">
                ${userText}
            </div>
        `);
        inputField.value = '';
        inputField.disabled = true;
        sendBtn.disabled = true;
        sendBtn.style.opacity = '0.5';
        
        const loadingId = 'loading-' + Date.now();
        contentBox.insertAdjacentHTML('beforeend', `
            <div id="${loadingId}" class="typing-indicator">
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
            </div>
        `);
        contentBox.scrollTo({ top: contentBox.scrollHeight, behavior: 'smooth' });
        
        chrome.runtime.sendMessage({ action: "get_auth_token" }, (authResponse) => {
            const token = authResponse ? authResponse.token : null;
            
            if (!token) {
                const loader = aiCard.querySelector(`#${loadingId}`);
                if(loader) loader.remove();
                
                inputField.disabled = false;
                sendBtn.disabled = false;
                sendBtn.style.opacity = '1';
                
                // 🚨 UX UPDATE: Inject the clean auth reconnect panel into chat
                const authBoxId = 'auth-' + Date.now();
                contentBox.insertAdjacentHTML('beforeend', `<div id="${authBoxId}"></div>`);
                injectAuthRecovery(contentBox.querySelector(`#${authBoxId}`));
                contentBox.scrollTo({ top: contentBox.scrollHeight, behavior: 'smooth' });
                return;
            }

            const chatController = new AbortController();
            const chatAbsoluteTimeout = setTimeout(() => {
                chatController.abort();
            }, 120000); 

            fetchWithSmartRetry("https://aura-scholar-backend.onrender.com/chat", {
                method: "POST",
                headers: { 
                    "Content-Type": "application/json",
                    "Authorization": `Bearer ${token}` 
                },
                body: JSON.stringify({ image_b64: currentImageB64, history: chatHistory, prompt: userText }),
                signal: chatController.signal
            })
            .then(data => {
                clearTimeout(chatAbsoluteTimeout);
                const loader = aiCard.querySelector(`#${loadingId}`);
                if(loader) loader.remove();
                
                inputField.disabled = false;
                sendBtn.disabled = false;
                sendBtn.style.opacity = '1';
                inputField.focus();
                
                if (data.AI_Answer) {
                    if (data.AI_Answer.includes("⚠️")) {
                        let exactError = data.AI_Answer.replace("⚠️", "").replace(/\*\*/g, "").trim();
                        
                        // 🚨 AUTO-PILOT UX: For chat rate limit
                        if (exactError.includes("limits reached") || exactError.includes("peak traffic")) {
                            const cdId = 'cd-' + Date.now();
                            contentBox.insertAdjacentHTML('beforeend', `
                                <div id="${cdId}" style="background-color: rgba(255, 176, 32, 0.05); border: 1px solid rgba(255, 176, 32, 0.2); padding: 12px; border-radius: 8px; margin: 12px 0; text-align: center;">
                                    <div style="width: 16px; height: 16px; border: 2px solid rgba(255, 176, 32, 0.3); border-top-color: #FFB020; border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto 8px auto;"></div>
                                    <strong style="font-size: 13px; color: #FFB020;">Google API Cooldown</strong><br>
                                    <span style="font-size: 12px; opacity: 0.9; color: #E2E2E2;">Auto-sending message in <span id="span-${cdId}">60</span>s...</span>
                                </div>
                            `);
                            let timeLeft = 60;
                            const timerSpan = contentBox.querySelector(`#span-${cdId}`);
                            const cdInterval = setInterval(() => {
                                timeLeft--;
                                if(timerSpan) timerSpan.innerText = timeLeft;
                                if(timeLeft <= 0) {
                                    clearInterval(cdInterval);
                                    const cdBox = contentBox.querySelector(`#${cdId}`);
                                    if(cdBox) cdBox.remove();
                                    inputField.value = userText; // put text back
                                    handleSend(); // Auto-retry chat!
                                }
                            }, 1000);
                        } else {
                            contentBox.insertAdjacentHTML('beforeend', `
                                <div style="background-color: rgba(255, 77, 77, 0.1); border: 1px solid #FF4D4D; color: #FF4D4D; padding: 12px; border-radius: 8px; margin: 12px 0;">
                                    <strong style="font-size: 13px;">⚠️ Notice</strong><br>
                                    <span style="font-size: 12px; opacity: 0.9;">${exactError}</span>
                                </div>
                            `);
                        }
                    } else {
                        chatHistory.push({ role: "user", text: userText });
                        chatHistory.push({ role: "model", text: data.AI_Answer });
                        updateAICard(data.AI_Answer, true); 
                    }
                    contentBox.scrollTo({ top: contentBox.scrollHeight, behavior: 'smooth' });
                } else {
                    throw new Error("Answer missing from server.");
                }
            })
            .catch(err => {
                clearTimeout(chatAbsoluteTimeout);
                const loader = aiCard.querySelector(`#${loadingId}`);
                if(loader) loader.remove();
                
                inputField.disabled = false;
                sendBtn.disabled = false;
                sendBtn.style.opacity = '1';
                
                if (err.message === "SILENT_AUTH_ERROR") {
                    const authBoxId = 'auth-' + Date.now();
                    contentBox.insertAdjacentHTML('beforeend', `<div id="${authBoxId}"></div>`);
                    injectAuthRecovery(contentBox.querySelector(`#${authBoxId}`));
                } else if (err.message === "AUTH_LIMIT_ERROR") {
                    contentBox.insertAdjacentHTML('beforeend', `
                        <div style="background-color: rgba(166, 77, 255, 0.1); border: 1px solid rgba(166, 77, 255, 0.4); color: white; padding: 16px; border-radius: 8px; margin: 12px 0;">
                            <span style="font-size: 18px; display: block; margin-bottom: 4px;">👑</span>
                            <strong style="font-size: 14px; color: #A64DFF;">Daily Limit Reached</strong><br>
                            <span style="font-size: 13px; opacity: 0.9; display: block; margin-top: 6px;">You've used all 10 free scans.</span>
                            <a href="https://kogvio-landing-page.vercel.app/#pricing" target="_blank" style="display: inline-block; margin-top: 10px; background: #A64DFF; color: white; padding: 6px 12px; border-radius: 4px; text-decoration: none; font-size: 12px; font-weight: bold;">Upgrade to Pro</a>
                        </div>
                    `);
                } else {
                    const msg = err.name === 'AbortError' ? "Request timed out." : err.message;
                    contentBox.insertAdjacentHTML('beforeend', `
                        <div style="background-color: rgba(255, 77, 77, 0.1); border: 1px solid #FF4D4D; color: #FF4D4D; padding: 12px; border-radius: 8px; margin: 12px 0;">
                            <span style="font-size: 12px; opacity: 0.9;">Chat Error: ${msg}</span>
                        </div>
                    `);
                }
                contentBox.scrollTo({ top: contentBox.scrollHeight, behavior: 'smooth' });
            });
        });
    };
    
    sendBtn.onclick = () => handleSend();
    inputField.onkeypress = (e) => { if(e.key === 'Enter') handleSend(); };
    
    chatBox.appendChild(inputField);
    chatBox.appendChild(sendBtn);
    
    aiCard.appendChild(header);
    aiCard.appendChild(contentBox);
    aiCard.appendChild(chatBox);
    document.body.appendChild(aiCard);
}

document.addEventListener('mousemove', (e) => {
    if (!isDraggingCard || !aiCard) return;
    e.preventDefault();
    aiCard.style.left = (e.clientX - cardDragOffsetX) + 'px';
    aiCard.style.top = (e.clientY - cardDragOffsetY) + 'px';
});
document.addEventListener('mouseup', () => { isDraggingCard = false; });

// --- 5. THE PREMIUM FORMATTER (Math, Code & Markdown) ---
function updateAICard(text, append = false) {
    const contentBox = document.getElementById('ai-content-box');
    if (contentBox) {
        
        let formattedText = text;

        formattedText = formattedText.replace(/\$\$([\s\S]*?)\$\$/g, function(match, math) {
            try { return katex.renderToString(math, { displayMode: true, throwOnError: false }); }
            catch (e) { return match; }
        });

        formattedText = formattedText.replace(/(?:\\\[|\\\(|\$)(.*?)(?:\\\]|\\\)|\$)/g, function(match, math) {
            if (match === '$') return match; 
            try { return katex.renderToString(math, { displayMode: false, throwOnError: false }); }
            catch (e) { return match; }
        });

        formattedText = formattedText.replace(/```(\w*)\n([\s\S]*?)```/g, function(match, language, code) {
            return `<div style="background: #18181D; border: 1px solid rgba(255,255,255,0.1); border-radius: 8px; margin: 12px 0; overflow: hidden;">
                        <div style="background: rgba(255,255,255,0.05); padding: 4px 12px; font-size: 11px; color: #888; text-transform: uppercase; border-bottom: 1px solid rgba(255,255,255,0.05);">${language || 'Code'}</div>
                        <pre style="margin: 0; padding: 12px; overflow-x: auto; font-family: 'Courier New', Courier, monospace; font-size: 13px; color: #E2E2E2;"><code>${code.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</code></pre>
                    </div>`;
        });

        formattedText = formattedText.replace(/`([^`]+)`/g, '<code style="background: rgba(166, 77, 255, 0.15); color: #C48CFF; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 12px;">$1</code>');
        formattedText = formattedText.replace(/^### (.*$)/gm, '<h3 style="margin: 16px 0 8px 0; color: #FFF; font-size: 15px;">$1</h3>');
        formattedText = formattedText.replace(/^## (.*$)/gm, '<h2 style="margin: 18px 0 8px 0; color: #FFF; font-size: 17px;">$1</h2>');
        formattedText = formattedText.replace(/^\s*[\*\-]\s+(.*)$/gm, '<li style="margin-left: 15px; margin-bottom: 6px; list-style-type: disc;">$1</li>');
        formattedText = formattedText.replace(/\*\*(.*?)\*\*/g, '<strong style="color: #FFF;">$1</strong>');
        formattedText = formattedText.replace(/\*(.*?)\*/g, '<em>$1</em>');
        
        formattedText = formattedText.replace(/\n/g, '<br>');
        formattedText = formattedText.replace(/<\/li><br>/g, '</li>');
        formattedText = formattedText.replace(/<\/h2><br>/g, '</h2>');
        formattedText = formattedText.replace(/<\/h3><br>/g, '</h3>');
        formattedText = formattedText.replace(/<\/div><br>/g, '</div>');

        const msgId = 'msg-' + Date.now();
        const copyBtnId = 'copy-' + Date.now();

        const messageHTML = `
            <div class="chat-bubble-ai">
                <button id="${copyBtnId}" style="position: absolute; top: 12px; right: 12px; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); color: #888; border-radius: 6px; padding: 4px 8px; font-size: 10px; text-transform: uppercase; letter-spacing: 0.5px; cursor: pointer; transition: all 0.2s ease; z-index: 10;">
                    Copy
                </button>
                <div id="${msgId}" style="padding-top: 4px;">${formattedText}</div>
            </div>`;

        if (append) {
            contentBox.insertAdjacentHTML('beforeend', messageHTML);
            const newBubble = contentBox.lastElementChild;
            if (newBubble) {
                contentBox.scrollTo({ top: newBubble.offsetTop - 15, behavior: 'smooth' });
            }
        } else {
            contentBox.innerHTML = messageHTML;
            contentBox.scrollTo({ top: 0, behavior: 'smooth' });
        }

        const copyBtn = document.getElementById(copyBtnId);
        if (copyBtn) {
            copyBtn.addEventListener('click', () => {
                const textToCopy = document.getElementById(msgId).innerText;
                
                if (navigator.clipboard) {
                    navigator.clipboard.writeText(textToCopy).catch(() => fallbackCopy(textToCopy));
                } else {
                    fallbackCopy(textToCopy);
                }

                copyBtn.innerText = '✓';
                copyBtn.style.color = '#A64DFF';
                setTimeout(() => {
                    copyBtn.innerText = 'Copy';
                    copyBtn.style.color = '#888';
                }, 2000);
            });
        }
    }
}

function fallbackCopy(text) {
    const textArea = document.createElement("textarea");
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    try { document.execCommand('copy'); } catch (err) {}
    document.body.removeChild(textArea);
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "trigger_crosshair") {
        activateCrosshair();
    }
    return true; 
});