window.closeAIChatWindow = function() {
    let chatWindow = document.getElementById('ai-chat-window');
    if (chatWindow) {
        // Exit fullscreen if active
        chatWindow.classList.remove('ai-fullscreen');
        chatWindow.classList.remove('open');
        chatWindow.style.display = 'none';
    }
    let backdrop = document.getElementById('ai-chat-backdrop');
    if (backdrop) backdrop.style.display = 'none';
};
// --- AI SECURITY: Encryption/Decryption for API Keys ---
// Simple XOR encryption - not military-grade, but prevents casual viewing
const AI_SECURITY_KEY = 'webvidra-ai-secure-2025';

function simpleEncrypt(text, key) {
    let result = '';
    for (let i = 0; i < text.length; i++) {
        result += String.fromCharCode(text.charCodeAt(i) ^ key.charCodeAt(i % key.length));
    }
    return btoa(result); // Base64 encode
}

function simpleDecrypt(encoded, key) {
    try {
        let text = atob(encoded); // Base64 decode
        let result = '';
        for (let i = 0; i < text.length; i++) {
            result += String.fromCharCode(text.charCodeAt(i) ^ key.charCodeAt(i % key.length));
        }
        return result;
    } catch (e) {
        console.warn('Decryption failed:', e);
        return '';
    }
}

function saveAIKeyToStorage(apiKey) {
    try {
        if (!apiKey) {
            localStorage.removeItem('ai-api-key-encrypted');
            return;
        }
        const encrypted = simpleEncrypt(apiKey, AI_SECURITY_KEY);
        localStorage.setItem('ai-api-key-encrypted', encrypted);
        console.log('AI API key saved securely to localStorage');
    } catch (e) {
        console.warn('Could not save AI key:', e);
    }
}

function loadAIKeyFromStorage() {
    try {
        const encrypted = localStorage.getItem('ai-api-key-encrypted');
        if (!encrypted) return '';
        return simpleDecrypt(encrypted, AI_SECURITY_KEY);
    } catch (e) {
        console.warn('Could not load AI key:', e);
        return '';
    }
}

function clearAIKeyFromStorage() {
    try {
        localStorage.removeItem('ai-api-key-encrypted');
        console.log('AI API key cleared from localStorage');
    } catch (e) {
        console.warn('Could not clear AI key:', e);
    }
}

/**
 * Check if cached AI settings are still valid for the current project.
 * Returns true if settings match current project, false if they're stale.
 */
async function validateAISettingsForCurrentProject() {
    try {
        const currentProjectPath = await eel.get_current_project_path()();
        const cachedProjectId = localStorage.getItem('ai-settings-project-id');
        
        if (cachedProjectId !== currentProjectPath) {
            console.warn('[AISettings] Settings are for different project. Cached:', cachedProjectId, 'Current:', currentProjectPath);
            return false;
        }
        
        console.log('[AISettings] Validation passed for project:', currentProjectPath);
        return true;
    } catch (e) {
        console.warn('[AISettings] Validation check failed:', e);
        return false;
    }
}

/**
 * Clear all AI settings from localStorage to force fresh reload.
 * Called when switching projects to prevent cross-project contamination.
 */
function clearAISettingsFromStorage() {
    try {
        localStorage.removeItem('ai-provider');
        localStorage.removeItem('ai-model');
        localStorage.removeItem('ai-api-key-encrypted');
        localStorage.removeItem('ai-settings-project-id');
        localStorage.removeItem('ai-settings-loaded-at');
        console.log('[AISettings] All cached AI settings cleared from localStorage');
    } catch (e) {
        console.warn('Could not clear AI settings:', e);
    }
}

// --- AI SETTINGS PERSISTENCE (Backend Config File) ---
// Load AI settings from backend persistent storage (survives app restart and browser cache clear)
async function loadAISettingsFromBackend() {
    try {
        // Get current project path for validation
        let projectPath = "";
        try {
            projectPath = await eel.get_current_project_path()();
        } catch (e) {
            console.warn('[AISettings] Could not get current project path:', e);
        }
        
        const settings = await eel.get_ai_settings()();
        if (settings && typeof settings === 'object') {
            console.log('[AISettings] Loaded from backend:', settings.provider, settings.model);
            // Load into localStorage for fast access with project tracking
            localStorage.setItem('ai-provider', settings.provider || 'openai');
            localStorage.setItem('ai-model', settings.model || 'gpt-5');
            localStorage.setItem('ai-settings-project-id', projectPath); // Track which project these settings are for
            localStorage.setItem('ai-settings-loaded-at', new Date().toISOString());
            if (settings.api_key) {
                localStorage.setItem('ai-api-key-encrypted', simpleEncrypt(settings.api_key, AI_SECURITY_KEY));
            }
            console.log('[AISettings] Marked as loaded for project:', projectPath);
            return true;
        }
    } catch (e) {
        console.warn('[AISettings] Backend load error:', e);
    }
    return false;
}

// Save AI settings to backend persistent storage (config file in user home)
async function saveAISettingsToBackend(provider, model, apiKey) {
    try {
        const settings = {
            provider: provider || 'openai',
            model: model || 'gpt-5',
            api_key: apiKey || ''
        };
        const result = await eel.save_ai_settings(settings)();
        if (result) {
            console.log('[AISettings] Saved to backend:', settings.provider, settings.model);
            return true;
        }
    } catch (e) {
        console.warn('[AISettings] Backend save error:', e);
    }
    return false;
}

// Helper: Add a message to AI chat area
function addAIMessage(text, type = 'ai-response') {
    let messagesContainer = document.getElementById('ai-messages');
    if (!messagesContainer) {
        try { alert(text); } catch(e){}
        return;
    }

    let messageDiv = document.createElement('div');
    messageDiv.className = `ai-message ${type}`;
    
    // Format text as HTML for better readability (especially for SEO/chat responses)
    if (type === 'ai-response' || type === 'ai-chat') {
        let formattedText = text;
        
        // Convert bullet points to HTML list items
        if (formattedText.includes('•') || formattedText.includes('*')) {
            // Split by lines and process
            let lines = formattedText.split('\n');
            let inList = false;
            let htmlLines = [];
            
            for (let line of lines) {
                let trimmed = line.trim();
                if (trimmed.startsWith('•') || trimmed.startsWith('*')) {
                    if (!inList) {
                        htmlLines.push('<ul style="margin: 10px 0; padding-left: 20px; line-height: 1.6;">');
                        inList = true;
                    }
                    // Remove bullet and wrap in <li>
                    let content = trimmed.substring(1).trim();
                    htmlLines.push(`<li style="margin-bottom: 8px;">${content}</li>`);
                } else {
                    if (inList) {
                        htmlLines.push('</ul>');
                        inList = false;
                    }
                    if (trimmed) {
                        htmlLines.push(`<p style="margin: 8px 0;">${trimmed}</p>`);
                    }
                }
            }
            if (inList) {
                htmlLines.push('</ul>');
            }
            formattedText = htmlLines.join('');
        } else {
            // No bullets, just convert line breaks to <br> or <p> tags
            formattedText = formattedText.split('\n').map(line => {
                let trimmed = line.trim();
                return trimmed ? `<p style="margin: 8px 0;">${trimmed}</p>` : '';
            }).join('');
        }
        
        messageDiv.innerHTML = formattedText;
    } else {
        // For other message types (user, error, loading), use plain text
        messageDiv.textContent = text;
    }

    messagesContainer.appendChild(messageDiv);
    // Auto-scroll to bottom
    messagesContainer.scrollTop = messagesContainer.scrollHeight;

    // Save message to localStorage for persistence
    saveAIChatMessage(text, type);
}

// Global JS error reporting to help debugging UI issues
function reportJSProblem(msg) {
    // IMPORTANT: Demote to debug-level reporting to reduce noisy red logs
    try {
        console.debug('JS:', msg);
    } catch (e) {
        console.error('Could not report JS problem:', e);
    }
}

// Utility: scan stylesheets for rules that mention a token (e.g., 'ai-chat-window') and log matching rules
function scanStylesheetsForRules(token) {
    console.debug('Scanning stylesheets for rules mentioning:', token);
    for (let i = 0; i < document.styleSheets.length; i++) {
        const sheet = document.styleSheets[i];
        const href = sheet.href || '<inline>';
        let rules;
        try { rules = sheet.cssRules; } catch (e) { console.debug('Could not access stylesheet', href, e); continue; }
        for (let j = 0; j < rules.length; j++) {
            const rule = rules[j];
            try {
                const txt = rule.cssText || '';
                const sel = rule.selectorText || '';
                if (sel && sel.includes('.' + token)) {
                    console.debug('Style rule (selector match) in', href, ':', txt);
                } else if (txt && txt.includes(token)) {
                    console.debug('Style rule (text match) in', href, ':', txt);
                } else if (txt && (txt.includes('opacity') || txt.includes('display') || txt.includes('visibility'))) {
                    // heuristics: print rule if it seems relevant
                    if (txt.toLowerCase().includes('ai-chat-window') || txt.toLowerCase().includes('.ai-chat-window')) {
                        console.debug('Potential relevant style in', href, ':', txt);
                    }
                }
            } catch (e) {
                // ignore
            }
        }
    }
}

window.addEventListener('error', function(e) {
    const message = `${e.message} at ${e.filename || ''}:${e.lineno || '?'}:${e.colno || '?'} `;
    console.error('Global JS error caught:', message, e.error);
    reportJSProblem(message);
});

window.addEventListener('unhandledrejection', function(e) {
    const reason = (e && e.reason) ? (e.reason.message || String(e.reason)) : 'Unknown';
    console.error('Unhandled promise rejection:', reason);
    reportJSProblem('Unhandled promise rejection: ' + reason);
});

// --- AI ASSISTANT CHAT WIDGET ---

// This function is called by Python when AI finishes processing
eel.expose(on_ai_finished);
function on_ai_finished(result) {
    console.log("AI finished:", result);
    
    // Remove loading message
    let messagesContainer = document.getElementById('ai-messages');
    let lastMsg = messagesContainer.lastChild;
    if (lastMsg && lastMsg.classList.contains('ai-loading')) {
        lastMsg.remove();
    }
    
    // Display result
    if (result.success) {
        // If this was a chat response, show plain message without the checkmark/count
        if (result.is_chat) {
            addAIMessage(result.message, 'ai-response');
            // Agent mode may have modified blocks — reload to reflect changes
            if (result.blocks_modified && result.blocks_modified > 0) {
                loadProject().then(() => {
                    console.log("Project reloaded after Agent");
                    renderCanvas();
                });
                _addAIUndoButton();
            }
        } else {
            let msg = `✓ ${result.message} (${result.blocks_modified || 0} changes)`;
            if (result.blocks_rejected && result.blocks_rejected > 0) {
                msg = `⚠ ${result.message}`;
            }
            addAIMessage(msg, result.blocks_rejected ? 'ai-warning' : 'ai-response');
            
            // IMPORTANT: Reload project data from Python to sync with new blocks
            // This ensures appData is updated with the blocks that Python saved
            loadProject().then(() => {
                console.log("Project reloaded after AI");
                renderCanvas(); // Now render with updated data
                
                // If global settings modal is open, refresh it too
                if (document.getElementById('settings-overlay') && document.getElementById('settings-overlay').style.display !== 'none') {
                    openGlobalSettings();
                }
            });
            // Show undo button when actual changes were applied
            if (result.blocks_modified && result.blocks_modified > 0) {
                _addAIUndoButton();
            }
        }
    } else {
        // Map known error codes to Hungarian-friendly messages
        let display = `✗ Error: ${result.message}`;
        if (result.error_code) {
            const code = result.error_code;
            if (code === 'timeout') display = '✗ Hiba: időtúllépés — a kérelem lejárt, próbáld újra.';
            else if (code === 'bad_key') display = '✗ Hiba: rossz vagy hiányzó API kulcs (rossz kulcs). Ellenőrizd a beállításokat.';
            else if (code === 'conn') display = '✗ Hiba: kapcsolódási probléma (pl. helyi Ollama nem fut).' ;
            else if (code === 'http') display = `✗ Hiba: szerver visszaadott hibát — ${result.message || 'HTTP hiba'}`;
            else if (code === 'unknown_provider') display = '✗ Hiba: ismeretlen AI szolgáltató.';
            else if (code === 'exception') display = `✗ Hiba: ${result.message}`;
            else display = `✗ Hiba: ${result.message}`;
        } else {
            // Try to detect substrings for better Hungarian messages
            const lower = (result.message||'').toLowerCase();
            if (lower.includes('timeout') || lower.includes('lejárt')) display = '✗ Hiba: időtúllépés — a kérelem lejárt.';
            else if (lower.includes('api') && lower.includes('key')) display = '✗ Hiba: rossz vagy hiányzó API kulcs (rossz kulcs).';
            else if (lower.includes('no json') || lower.includes('no json found')) display = '✗ Hiba: az AI nem adott vissza értelmezhető JSON-t.';
        }
        addAIMessage(display, 'ai-error');
    }
    
    // Re-enable send button and keep AI window in focus
    document.getElementById('ai-send-btn').disabled = false;
    
    // Ensure AI chat window is visible and scroll to bottom
    let chatWindow = document.getElementById('ai-chat-window');
    if (chatWindow && getComputedStyle(chatWindow).display === 'none') {
        chatWindow.classList.add('open');
        chatWindow.style.display = 'flex';
    }
    
    // Scroll chat messages to bottom to show latest response
    setTimeout(() => {
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
        document.getElementById('ai-input').focus();
    }, 100);
}

// --- AI Undo helpers ---

function _addAIUndoButton() {
    // Remove any previous undo button to avoid duplicates
    document.querySelectorAll('.ai-undo-row').forEach(el => el.remove());
    let messagesContainer = document.getElementById('ai-messages');
    let row = document.createElement('div');
    row.className = 'ai-message ai-undo-row';
    row.innerHTML = '<button class="ai-undo-btn" onclick="undoAIChanges(this)">↩ Visszaállítás az AI előtti állapotra</button>';
    messagesContainer.appendChild(row);
    setTimeout(() => { messagesContainer.scrollTop = messagesContainer.scrollHeight; }, 80);
}

async function undoAIChanges(btn) {
    // Determine UI language for the confirmation message
    let lang = 'hu';
    try { if (typeof getUILang === 'function') lang = getUILang(); } catch(e) {}

    const title   = lang === 'en' ? 'Restore checkpoint?' : 'Visszaállítás megerősítése';
    const body    = lang === 'en'
        ? 'This will restore the project to the state it was in just before the last AI action.\n\nAny manual edits made after that point will also be lost.\n\nAre you sure?'
        : 'Ez visszaállítja a projektet az utolsó AI-művelet előtti mentési pontra.\n\nAz azóta végzett kézi szerkesztések is elvesznek.\n\nBiztosan folytatod?';
    const okLabel = lang === 'en' ? 'Restore' : 'Visszaállítás';

    // Show custom confirmation dialog (reuse the app's generic confirm pattern)
    const confirmed = await new Promise(resolve => {
        const overlay = document.createElement('div');
        overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:9999;display:flex;align-items:center;justify-content:center';
        overlay.innerHTML = `
            <div style="background:var(--bg-color,#1e1e2e);color:var(--text-color,#cdd6f4);border:1px solid var(--border-color,#444);border-radius:10px;padding:28px 32px;max-width:420px;width:90%;box-shadow:0 8px 32px #0008">
                <div style="font-size:1.1em;font-weight:600;margin-bottom:12px">⚠ ${title}</div>
                <div style="font-size:.93em;line-height:1.6;white-space:pre-line;margin-bottom:22px">${body}</div>
                <div style="display:flex;gap:10px;justify-content:flex-end">
                    <button id="_ai_undo_cancel" style="padding:7px 20px;border-radius:6px;border:1px solid var(--border-color,#555);background:transparent;color:inherit;cursor:pointer">${lang === 'en' ? 'Cancel' : 'Mégsem'}</button>
                    <button id="_ai_undo_ok" style="padding:7px 20px;border-radius:6px;border:none;background:#e74c3c;color:#fff;cursor:pointer;font-weight:600">${okLabel}</button>
                </div>
            </div>`;
        document.body.appendChild(overlay);
        overlay.querySelector('#_ai_undo_ok').onclick     = () => { document.body.removeChild(overlay); resolve(true); };
        overlay.querySelector('#_ai_undo_cancel').onclick = () => { document.body.removeChild(overlay); resolve(false); };
        overlay.addEventListener('keydown', e => { if (e.key === 'Escape') { document.body.removeChild(overlay); resolve(false); } });
    });

    if (!confirmed) return;

    if (btn) btn.disabled = true;
    let result = await eel.undo_ai_changes()();
    // Remove undo button regardless of outcome
    document.querySelectorAll('.ai-undo-row').forEach(el => el.remove());
    if (result.success) {
        await loadProject();
        renderCanvas();
        addAIMessage('↩ Projekt visszaállítva az AI előtti mentési pontra.', 'ai-response');
    } else {
        if (btn) btn.disabled = false;
        addAIMessage('✗ Visszaállítás sikertelen: ' + result.message, 'ai-error');
    }
}

// Called by Python during agent mode to show live step progress
eel.expose(on_ai_step);
function on_ai_step(message) {
    let messagesContainer = document.getElementById('ai-messages');
    if (!messagesContainer) return;
    // Reuse the last loading bubble for live updates — avoids message spam
    let lastMsg = messagesContainer.lastChild;
    if (lastMsg && lastMsg.classList.contains('ai-loading')) {
        lastMsg.textContent = message;
    } else {
        let stepDiv = document.createElement('div');
        stepDiv.className = 'ai-message ai-loading';
        stepDiv.textContent = message;
        messagesContainer.appendChild(stepDiv);
    }
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
}


function toggleAIChat() {
    try {
        console.debug('toggleAIChat called');
        let chatWindow = document.getElementById('ai-chat-window');
        if (!chatWindow) {
            console.warn('toggleAIChat: ai-chat-window not found');
            return;
        }

        const cs = getComputedStyle(chatWindow);
        const isVisible = cs.display !== 'none' && cs.visibility !== 'hidden';

        if (!isVisible) {
            // Open the small chat
            chatWindow.classList.add('open');
            chatWindow.style.display = 'flex';

            // Auto-scroll messages to bottom
            setTimeout(() => {
                let messagesContainer = document.getElementById('ai-messages');
                if (messagesContainer) {
                    messagesContainer.scrollTop = messagesContainer.scrollHeight;
                }
                let input = document.getElementById('ai-input');
                if (input) input.focus();
            }, 100);

            console.log('toggleAIChat: opened chat');
        } else {
            // Close
            closeAIChatWindow();
            console.log('toggleAIChat: closed chat');
        }
    } catch (e) {
        console.error('toggleAIChat error:', e);
        reportJSProblem('toggleAIChat exception: ' + (e && e.message));
    }
}

/**
 * Toggle between small floating chat and fullscreen mode.
 */
function toggleAIChatFullscreen() {
    let chatWindow = document.getElementById('ai-chat-window');
    let backdrop = document.getElementById('ai-chat-backdrop');
    let expandBtn = document.getElementById('ai-expand-btn');
    if (!chatWindow) return;

    const goingFullscreen = !chatWindow.classList.contains('ai-fullscreen');

    if (goingFullscreen) {
        chatWindow.classList.add('ai-fullscreen');
        if (backdrop) backdrop.style.display = 'block';
        if (expandBtn) expandBtn.textContent = '⛶'; // shrink icon
        if (expandBtn) expandBtn.title = 'Exit fullscreen';

        // Refresh models on first fullscreen open
        let modelSelect = document.getElementById('ai-chat-model');
        if (modelSelect && modelSelect.options.length <= 1 && modelSelect.options[0]?.value === '') {
            refreshModelList();
        }
    } else {
        chatWindow.classList.remove('ai-fullscreen');
        if (backdrop) backdrop.style.display = 'none';
        if (expandBtn) expandBtn.textContent = '⛶'; // expand icon
        if (expandBtn) expandBtn.title = 'Expand to fullscreen';
    }

    // Scroll to bottom
    setTimeout(() => {
        let mc = document.getElementById('ai-messages');
        if (mc) mc.scrollTop = mc.scrollHeight;
        let input = document.getElementById('ai-input');
        if (input) input.focus();
    }, 50);
}
window.toggleAIChatFullscreen = toggleAIChatFullscreen;

async function repairProjectDataManual() {
    let repairBtn = document.getElementById('ai-repair-btn');
    if (!repairBtn) return;
    
    repairBtn.disabled = true;
    addAIMessage('🔧 Repairing project data structure...', 'ai-loading');
    
    try {
        let result = await eel.repair_project_data_manual()();
        
        // Remove loading message
        let messagesContainer = document.getElementById('ai-messages');
        let lastMsg = messagesContainer.lastChild;
        if (lastMsg && lastMsg.classList.contains('ai-loading')) {
            lastMsg.remove();
        }
        
        if (result.success) {
            addAIMessage(`✓ ${result.message}`, 'ai-response');
            // Reload project to show any changes
            await loadProject();
            renderCanvas();
        } else {
            addAIMessage(`✗ Repair failed: ${result.message}`, 'ai-error');
        }
    } catch (err) {
        let messagesContainer = document.getElementById('ai-messages');
        let lastMsg = messagesContainer.lastChild;
        if (lastMsg && lastMsg.classList.contains('ai-loading')) {
            lastMsg.remove();
        }
        console.error('Repair error:', err);
        addAIMessage(`✗ Repair error: ${err}`, 'ai-error');
    }
    
    repairBtn.disabled = false;
}

document.addEventListener('DOMContentLoaded', () => {
    // Note: toggle button click is handled via inline onclick in HTML — do NOT add another listener here
    
    // Restore AI chat history from localStorage
    restoreAIChatHistory();

    // Restore AI mode selection
    try {
        const modeSelect = document.getElementById('ai-mode');
        if (modeSelect) {
            const mode = localStorage.getItem('ai-mode') || 'edit';
            modeSelect.value = mode;
            modeSelect.addEventListener('change', (e) => {
                localStorage.setItem('ai-mode', e.target.value);
            });
        }
    } catch (e) { console.warn('AI mode restore failed', e); }

    // Setup auto-resize textarea
    setupAutoResizeTextarea();

    // Setup model selector change handler - save selection to localStorage
    const modelSelect = document.getElementById('ai-chat-model');
    if (modelSelect) {
        modelSelect.addEventListener('change', async (e) => {
            const selected = e.target.value;
            if (selected) {
                localStorage.setItem('ai-model', selected);
                // Also update the global settings model input if it exists
                const settingsModelInput = document.getElementById('ai-model');
                if (settingsModelInput) settingsModelInput.value = selected;
                // Save to backend
                const provider = localStorage.getItem('ai-provider') || 'openai';
                const apiKey = loadAIKeyFromStorage() || '';
                await saveAISettingsToBackend(provider, selected, apiKey);
                console.log('[AI] Model changed to:', selected);
            }
        });
    }

    // Close on overlay background click (no longer needed — backdrop onclick handles fullscreen close)

    // Quick runtime diagnostics to help detect missing DOM elements
    try {
        const required = ['ai-chat-window','ai-mode','settings-overlay','ai-toggle-btn','ai-send-btn'];
        let missing = [];
        required.forEach(id => { if (!document.getElementById(id)) missing.push(id); });
        if (missing.length > 0) {
            const msg = 'Missing AI UI elements: ' + missing.join(', ');
            console.warn(msg);
            reportJSProblem(msg);
        } else {
            console.log('AI UI checks OK');
        }
    } catch (e) { console.warn('AI UI diagnostics failed', e); }
});

function saveAIChatMessage(text, type) {
    try {
        let history = JSON.parse(localStorage.getItem('ai-chat-history') || '[]');
        history.push({
            text: text,
            type: type,
            timestamp: new Date().toISOString()
        });
        localStorage.setItem('ai-chat-history', JSON.stringify(history));
    } catch (e) {
        console.warn('Could not save AI chat message:', e);
    }
}

function restoreAIChatHistory() {
    try {
        let history = JSON.parse(localStorage.getItem('ai-chat-history') || '[]');
        let messagesContainer = document.getElementById('ai-messages');
        
        if (!messagesContainer || history.length === 0) return;
        
        // Clear default system message (only keep if no history)
        if (history.length > 0) {
            messagesContainer.innerHTML = '';
        }
        
        // Restore all messages
        history.forEach(msg => {
            let messageDiv = document.createElement('div');
            messageDiv.className = `ai-message ${msg.type}`;
            messageDiv.textContent = msg.text;
            messagesContainer.appendChild(messageDiv);
        });
        
        // Scroll to bottom
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    } catch (e) {
        console.warn('Could not restore AI chat history:', e);
    }
}

function clearAIChatHistory() {
    try {
        localStorage.removeItem('ai-chat-history');
        let messagesContainer = document.getElementById('ai-messages');
        if (messagesContainer) {
            messagesContainer.innerHTML = '<div class="ai-message ai-system"><p>Hello! I can help you edit your project. Describe what you\'d like to change, and I\'ll modify the blocks for you.</p></div>';
        }
    } catch (e) {
        console.warn('Could not clear AI chat history:', e);
    }
}

/**
 * Build a conversation history array for the AI backend.
 * Reads saved messages from localStorage, filters to real user/assistant turns,
 * and returns a slice appropriate for the current mode.
 *
 * The current user message is excluded to avoid duplication (it is already passed
 * as `user_instruction` to the backend).
 *
 * @param {string} currentUserMessage - The message the user is about to send.
 * @param {boolean} isAgent - Whether agent mode is active (agents get more history;
 *                            they can also call the get_conversation_history tool).
 * @returns {Array<{role: string, text: string}>}
 */
function buildConversationHistoryForAI(currentUserMessage, isAgent) {
    try {
        let rawHistory = JSON.parse(localStorage.getItem('ai-chat-history') || '[]');
        // Keep only real user and AI response messages (skip system, loading, error, warning-as-noise)
        let filtered = rawHistory
            .filter(m => m.type === 'ai-user' || m.type === 'ai-response' || m.type === 'ai-warning')
            .map(m => ({ role: m.type === 'ai-user' ? 'user' : 'assistant', text: m.text }));
        // Exclude the current message (it was just saved before this function is called)
        if (filtered.length > 0) {
            const last = filtered[filtered.length - 1];
            if (last.role === 'user' && last.text === currentUserMessage) {
                filtered = filtered.slice(0, -1);
            }
        }
        // Agent mode: pass up to last 20 messages so the agent can call
        // get_conversation_history(scope) to retrieve the slice it needs.
        // Non-agent modes (chat / edit / seo): pass last 5 messages which
        // approximate ~2 user + ~3 AI turns and are injected inline into the prompt.
        return isAgent ? filtered.slice(-20) : filtered.slice(-5);
    } catch (e) {
        console.warn('[AI] Could not build conversation history:', e);
        return [];
    }
}

async function sendAIMessage() {
    let input = document.getElementById('ai-input');
    let sendBtn = document.getElementById('ai-send-btn');
    
    // Determine mode first to check if this is SEO mode
    let mode = 'edit';
    try {
        const sel = document.getElementById('ai-mode');
        if (sel) mode = sel.value || 'edit';
    } catch (e) { }

    // Build user message based on mode
    let userMessage = '';
    if (mode === 'seo') {
        // In SEO mode, use user input if provided, otherwise analyze entire website
        if (input.value.trim()) {
            userMessage = input.value.trim();
            addAIMessage(userMessage, 'ai-user');
        } else {
            // If user didn't provide input, analyze entire website
            userMessage = '__ANALYZE_WEBSITE_SEO__'; // Special indicator for Python backend
        }
        input.value = '';
        addAIMessage('🔍 A weboldal SEO elemzése... (kis türelmet)', 'ai-loading');
    } else {
        // For chat and edit modes, require user input
        if (!input.value.trim()) return;
        userMessage = input.value.trim();
        input.value = '';
        addAIMessage(userMessage, 'ai-user');
    }

    // --- Page scope + attachment chips logic ---
    let pageScope = 'current';
    let selectedPages = [];
    let attachedFiles = [];
    let externalFileContents = [];
    try {
        const scopeSel = document.getElementById('ai-page-scope');
        if (scopeSel) pageScope = scopeSel.value || 'current';

        // If user has attachment chips, use those as the source of truth
        const chipPageIds = getAttachedPageIds().map(id => id.replace('page:', ''));
        attachedFiles = getAttachedFilePaths().map(id => id.replace('file:', ''));

        // Collect external file contents from cache
        const extAttachments = window._aiAttachments.filter(a => a.type === 'external');
        if (extAttachments.length > 0 && window._aiExternalFileContents) {
            extAttachments.forEach(att => {
                const content = window._aiExternalFileContents[att.id];
                if (content) {
                    externalFileContents.push({ name: att.name, content: content });
                }
            });
        }

        if (chipPageIds.length > 0) {
            // Chips override the page scope selector
            pageScope = 'custom';
            selectedPages = chipPageIds;
        }
        console.log(`[AI] Page scope: ${pageScope}, Selected pages: ${JSON.stringify(selectedPages)}, Files: ${JSON.stringify(attachedFiles)}, External: ${externalFileContents.length}`);
    } catch (e) {
        addAIMessage('✗ Error: ' + (e && e.message ? e.message : e), 'ai-error');
        console.error('[AI] Error in page scope logic:', e);
        return;
    }

    // Disable send button and show loading (different text for chat vs edit vs seo)
    sendBtn.disabled = true;
    if (mode === 'chat' && !userMessage.startsWith('__')) addAIMessage('💬 Chatting... (the local version might be slow...)', 'ai-loading');
    else if (mode === 'edit' && !userMessage.startsWith('__')) addAIMessage('🤔 Thinking... (the local version might be slow...)', 'ai-loading');
    else if (mode === 'agent') addAIMessage('🤖 Agent starting — will work step by step…', 'ai-loading');

    try {
        // Load AI configuration from localStorage
        let aiProvider = localStorage.getItem('ai-provider') || 'openai';
        let aiModel = localStorage.getItem('ai-model') || 'gpt-5';
        let apiKey = loadAIKeyFromStorage() || '';

        // If model selector in chat header has a value, prefer it
        let chatModelSelect = document.getElementById('ai-chat-model');
        if (chatModelSelect && chatModelSelect.value) {
            aiModel = chatModelSelect.value;
            localStorage.setItem('ai-model', aiModel);
        }

        // Get UI language (from translations.js)
        let uiLang = 'hu'; // default
        try {
            if (typeof getUILang === 'function') {
                uiLang = getUILang();
            } else {
                uiLang = localStorage.getItem('ui_language') || 'hu';
            }
        } catch (e) {
            console.debug('Could not get UI language, using default:', e);
        }

        // --- Page scope + attached files logging ---
        console.log('AI page scope:', pageScope, selectedPages, 'files:', attachedFiles, 'external:', externalFileContents.length);

        // Build conversation history so the AI (and agent tools) can understand prior context
        let conversationHistory = buildConversationHistoryForAI(userMessage, mode === 'agent');
        console.log(`[AI] Conversation history: ${conversationHistory.length} message(s) attached`);

        // START the AI request (with page scope, file attachments, external file contents, and conversation history)
        let startResponse = await eel.ask_ai_to_edit(userMessage, aiProvider, aiModel, apiKey, mode, uiLang, pageScope, selectedPages, attachedFiles, externalFileContents, conversationHistory)();
        console.log("AI Request sent:", startResponse);
        if (startResponse && startResponse.status === 'error') {
            let messagesContainer = document.getElementById('ai-messages');
            let lastMsg = messagesContainer.lastChild;
            if (lastMsg && lastMsg.classList.contains('ai-loading')) {
                lastMsg.remove();
            }
            let errMsg = startResponse.message || 'Ismeretlen hiba';
            if (typeof errMsg === 'string' && errMsg.toLowerCase().includes('no project')) errMsg = 'Nincs betöltött projekt.';
            addAIMessage(`✗ ${errMsg}`, 'ai-error');
            sendBtn.disabled = false;
            return;
        }
        // A háttérben dolgozik tovább, on_ai_finished hívódik majd.
    } catch (err) {
        let messagesContainer = document.getElementById('ai-messages');
        let lastMsg = messagesContainer.lastChild;
        if (lastMsg && lastMsg.classList.contains('ai-loading')) {
            lastMsg.remove();
        }
        console.error('AI start error:', err);
        let errorMsg = 'Connection error';
        if (err) {
            if (err.message) errorMsg = err.message;
            else if (typeof err === 'string') errorMsg = err;
            else errorMsg = String(err);
        }
        addAIMessage(`✗ ${errorMsg}`, 'ai-error');
        sendBtn.disabled = false;
    }
}
// --- AI page scope change handler ---
document.addEventListener('DOMContentLoaded', () => {
    const pageScopeSel = document.getElementById('ai-page-scope');

    if (pageScopeSel) {
        pageScopeSel.addEventListener('change', function() {
            // Sync attachment chips to match page scope
            syncAttachmentsFromPageScope();
        });
    }
});

// AI Provider UI Handler
window.updateAIProviderUI = function() {
    let provider = document.getElementById('ai-provider').value;
    let keyWrapper = document.getElementById('ai-key-wrapper');
    let keyHint = document.getElementById('ai-key-hint');
    let currentModel = localStorage.getItem('ai-model') || '';
    
    // Show/hide API key input based on provider
    if (provider === 'ollama') {
        keyWrapper.style.display = 'none';
        // Set default model for Ollama if current one is from another provider
        if (!currentModel || currentModel === 'llama3-70b-8192' || currentModel === 'gemini-1.5-flash' || currentModel === 'gpt-5') {
            localStorage.setItem('ai-model', 'phi3');
        }
    } else {
        keyWrapper.style.display = 'block';
        
        // Set default models and hints based on cloud provider
        if (provider === 'groq') {
            keyHint.textContent = 'Get your API key from https://console.groq.com';
            document.getElementById('ai-api-key').placeholder = 'gsk_...';
            if (!currentModel || currentModel === 'phi3' || currentModel === 'gemini-1.5-flash' || currentModel === 'gpt-5') {
                localStorage.setItem('ai-model', 'llama3-70b-8192');
            }
        } else if (provider === 'gemini') {
            keyHint.textContent = 'Get your API key from https://aistudio.google.com';
            document.getElementById('ai-api-key').placeholder = 'AIza...';
            if (!currentModel || currentModel === 'phi3' || currentModel === 'llama3-70b-8192' || currentModel === 'gpt-5') {
                localStorage.setItem('ai-model', 'gemini-1.5-flash');
            }
        } else if (provider === 'openai') {
            keyHint.textContent = 'Get your API key from https://platform.openai.com';
            document.getElementById('ai-api-key').placeholder = 'sk-...';
            if (!currentModel || currentModel === 'phi3' || currentModel === 'llama3-70b-8192' || currentModel === 'gemini-1.5-flash') {
                localStorage.setItem('ai-model', 'gpt-5');
            }
        }
    }
    // Refresh both model dropdowns (chat + settings) for the selected provider
    refreshModelList();
};

// --- MODEL LISTING & SELECTOR ---

/**
 * Refresh the model dropdown in the AI chat header.
 * Fetches available models from the backend based on current provider/key.
 */
async function refreshModelList() {
    const modelSelect = document.getElementById('ai-chat-model');
    const settingsModelSelect = document.getElementById('ai-model');
    const refreshBtn = document.getElementById('ai-refresh-models-btn');
    const settingsRefreshBtn = document.getElementById('ai-settings-refresh-models-btn');
    if (!modelSelect && !settingsModelSelect) return;

    const provider = localStorage.getItem('ai-provider') || 'openai';
    const apiKey = loadAIKeyFromStorage() || '';
    const currentModel = localStorage.getItem('ai-model') || '';

    // Show loading in both selects
    if (modelSelect) { modelSelect.innerHTML = '<option value="">Fetching models...</option>'; modelSelect.disabled = true; }
    if (settingsModelSelect) { settingsModelSelect.innerHTML = '<option value="">Fetching models...</option>'; settingsModelSelect.disabled = true; }
    if (refreshBtn) refreshBtn.disabled = true;
    if (settingsRefreshBtn) settingsRefreshBtn.disabled = true;

    const _buildOptions = (sel, result) => {
        sel.innerHTML = '';
        if (result && result.models && result.models.length > 0) {
            result.models.forEach(m => {
                const opt = document.createElement('option');
                opt.value = m;
                opt.textContent = m;
                if (m === currentModel) opt.selected = true;
                sel.appendChild(opt);
            });
            // If current model isn't in list, add it as first option
            if (currentModel && !result.models.includes(currentModel)) {
                const opt = document.createElement('option');
                opt.value = currentModel;
                opt.textContent = currentModel + ' (current)';
                opt.selected = true;
                sel.insertBefore(opt, sel.firstChild);
            }
        } else if (result && result.error) {
            const opt = document.createElement('option');
            opt.value = currentModel || '';
            opt.textContent = currentModel ? currentModel + ' (manual)' : 'Error: ' + result.error;
            sel.appendChild(opt);
            console.warn('[AI Models] Error:', result.error);
        } else {
            const opt = document.createElement('option');
            opt.value = currentModel || '';
            opt.textContent = currentModel || 'No models found';
            sel.appendChild(opt);
        }
    };

    try {
        const result = await eel.list_ai_models(provider, apiKey)();
        if (modelSelect) _buildOptions(modelSelect, result);
        if (settingsModelSelect) _buildOptions(settingsModelSelect, result);
    } catch (e) {
        console.error('[AI Models] Failed to fetch:', e);
        const _errOption = (sel) => {
            sel.innerHTML = '';
            const opt = document.createElement('option');
            opt.value = currentModel || '';
            opt.textContent = currentModel || 'Failed to load';
            sel.appendChild(opt);
        };
        if (modelSelect) _errOption(modelSelect);
        if (settingsModelSelect) _errOption(settingsModelSelect);
    }

    if (modelSelect) modelSelect.disabled = false;
    if (settingsModelSelect) settingsModelSelect.disabled = false;
    if (refreshBtn) refreshBtn.disabled = false;
    if (settingsRefreshBtn) settingsRefreshBtn.disabled = false;
}
window.refreshModelList = refreshModelList;

// ============================================================
// --- AI ATTACHMENT CHIPS (Copilot-style context attachments) ---
// ============================================================

/** Current set of attached context items. Each: { id, type:'page'|'file', name, icon } */
window._aiAttachments = [];

/** Render the chips strip above the input box */
function renderAIAttachmentChips() {
    const container = document.getElementById('ai-attachments');
    if (!container) return;

    // Gather IDs currently in DOM for diff
    const existingIds = new Set(
        Array.from(container.querySelectorAll('.ai-chip')).map(el => el.dataset.id)
    );
    const newIds = new Set(window._aiAttachments.map(a => a.id));

    // Remove chips that are no longer in the list (with animation)
    container.querySelectorAll('.ai-chip').forEach(el => {
        if (!newIds.has(el.dataset.id)) {
            el.classList.add('removing');
            el.addEventListener('animationend', () => el.remove(), { once: true });
        }
    });

    // Add new chips that don't exist yet
    window._aiAttachments.forEach((att, idx) => {
        if (existingIds.has(att.id)) return; // already in DOM
        const chip = document.createElement('span');
        chip.className = 'ai-chip';
        chip.dataset.id = att.id;
        chip.style.animationDelay = (idx * 0.04) + 's';
        chip.innerHTML = `<span class="ai-chip-icon">${att.icon}</span><span class="ai-chip-name" title="${att.name}">${att.name}</span><button class="ai-chip-remove" onclick="removeAIAttachment('${att.id}')" title="Remove">×</button>`;
        container.appendChild(chip);
    });

    // Toggle the has-items class for expand/collapse animation
    container.classList.toggle('has-items', window._aiAttachments.length > 0);
}

/** Add an attachment (page or file) */
function addAIAttachment(id, type, name, icon) {
    // Prevent duplicates
    if (window._aiAttachments.some(a => a.id === id)) return;
    window._aiAttachments.push({ id, type, name, icon });
    renderAIAttachmentChips();
    // Update attach menu checkmarks if open
    updateAttachMenuState();
}
window.addAIAttachment = addAIAttachment;

/** Remove an attachment with animation */
function removeAIAttachment(id) {
    window._aiAttachments = window._aiAttachments.filter(a => a.id !== id);
    renderAIAttachmentChips();
    updateAttachMenuState();
}
window.removeAIAttachment = removeAIAttachment;

/** Toggle an attachment on/off */
function toggleAIAttachment(id, type, name, icon) {
    if (window._aiAttachments.some(a => a.id === id)) {
        removeAIAttachment(id);
    } else {
        addAIAttachment(id, type, name, icon);
    }
}
window.toggleAIAttachment = toggleAIAttachment;

/** Clear all attachments */
function clearAIAttachments() {
    window._aiAttachments = [];
    renderAIAttachmentChips();
}
window.clearAIAttachments = clearAIAttachments;

/** Get attached page IDs (for sending to backend) */
function getAttachedPageIds() {
    return window._aiAttachments.filter(a => a.type === 'page').map(a => a.id);
}
/** Get attached file paths */
function getAttachedFilePaths() {
    return window._aiAttachments.filter(a => a.type === 'file').map(a => a.id);
}

/** Open the attach context menu (pages + project files) */
function openAIAttachMenu() {
    // If menu already exists and is open, close it
    let existing = document.querySelector('.ai-attach-menu');
    if (existing && existing.classList.contains('open')) {
        existing.classList.remove('open');
        setTimeout(() => existing.remove(), 150);
        return;
    }
    if (existing) existing.remove();

    const menu = document.createElement('div');
    menu.className = 'ai-attach-menu open';

    // --- "Other file" button at the top ---
    const otherFileBtn = document.createElement('button');
    otherFileBtn.className = 'ai-attach-item ai-attach-other-file';
    otherFileBtn.innerHTML = `<span class="ai-chip-icon">📂</span><span>${t('ai_attach_other_file')}</span>`;
    otherFileBtn.onclick = async () => {
        try {
            const result = await eel.pick_external_file_for_ai()();
            if (!result) return; // cancelled
            if (result.error) {
                addAIMessage('✗ ' + result.error, 'ai-error');
                return;
            }
            const fileId = 'ext:' + result.path;
            const icon = getFileIcon(result.name);
            // Store the content so we can send it later without re-reading
            if (!window._aiExternalFileContents) window._aiExternalFileContents = {};
            window._aiExternalFileContents[fileId] = result.content;
            addAIAttachment(fileId, 'external', result.name, icon);
            // Close menu after picking
            menu.classList.remove('open');
            setTimeout(() => menu.remove(), 150);
        } catch (e) {
            console.error('[AI Attach] External file pick error:', e);
        }
    };
    menu.appendChild(otherFileBtn);

    // Show already-attached external files
    const extAttachments = window._aiAttachments.filter(a => a.type === 'external');
    if (extAttachments.length > 0) {
        const extTitle = document.createElement('div');
        extTitle.className = 'ai-attach-section-title';
        extTitle.textContent = t('ai_attach_external');
        menu.appendChild(extTitle);
        extAttachments.forEach(att => {
            const item = document.createElement('button');
            item.className = 'ai-attach-item attached';
            item.dataset.attachId = att.id;
            item.innerHTML = `<span class="ai-chip-icon">✓</span><span>${att.name}</span>`;
            item.onclick = () => {
                removeAIAttachment(att.id);
                // Also remove cached content
                if (window._aiExternalFileContents) delete window._aiExternalFileContents[att.id];
                item.remove();
            };
            menu.appendChild(item);
        });
    }

    // --- Pages section ---
    const pagesTitle = document.createElement('div');
    pagesTitle.className = 'ai-attach-section-title';
    pagesTitle.textContent = t('ai_attach_pages');
    menu.appendChild(pagesTitle);

    if (typeof appData === 'object' && appData && appData.pages) {
        const pageOrder = appData.page_order || Object.keys(appData.pages);
        pageOrder.forEach(pageId => {
            const pageTitle = (appData.page_titles && appData.page_titles[pageId]) ? appData.page_titles[pageId] : pageId;
            const isAttached = window._aiAttachments.some(a => a.id === 'page:' + pageId);
            const item = document.createElement('button');
            item.className = 'ai-attach-item' + (isAttached ? ' attached' : '');
            item.dataset.attachId = 'page:' + pageId;
            item.innerHTML = `<span class="ai-chip-icon">${isAttached ? '✓' : '📄'}</span><span>${pageTitle}</span>`;
            item.onclick = () => {
                toggleAIAttachment('page:' + pageId, 'page', pageTitle, '📄');
                // Update this item's state immediately
                const nowAttached = window._aiAttachments.some(a => a.id === 'page:' + pageId);
                item.className = 'ai-attach-item' + (nowAttached ? ' attached' : '');
                item.querySelector('.ai-chip-icon').textContent = nowAttached ? '✓' : '📄';
            };
            menu.appendChild(item);
        });
    }

    // --- Project files section ---
    const filesTitle = document.createElement('div');
    filesTitle.className = 'ai-attach-section-title';
    filesTitle.textContent = t('ai_attach_project_files');
    menu.appendChild(filesTitle);

    // Attempt to list files from backend
    const loadingItem = document.createElement('div');
    loadingItem.className = 'ai-attach-item';
    loadingItem.innerHTML = `<span class="ai-chip-icon">⏳</span><span>${t('ai_attach_loading')}</span>`;
    menu.appendChild(loadingItem);

    // Position relative to the input area
    const inputArea = document.querySelector('.ai-input-area');
    if (inputArea) {
        inputArea.style.position = 'relative';
        inputArea.appendChild(menu);
    }

    // Close on outside click
    setTimeout(() => {
        function closeHandler(e) {
            if (!menu.contains(e.target) && !e.target.closest('.ai-attach-btn')) {
                menu.classList.remove('open');
                setTimeout(() => menu.remove(), 150);
                document.removeEventListener('mousedown', closeHandler);
            }
        }
        document.addEventListener('mousedown', closeHandler);
    }, 10);

    // Fetch files from backend
    fetchProjectFiles().then(files => {
        loadingItem.remove();
        if (!files || files.length === 0) {
            const noFiles = document.createElement('div');
            noFiles.className = 'ai-attach-item';
            noFiles.innerHTML = `<span class="ai-chip-icon">—</span><span style="color:#777;">${t('ai_attach_no_files')}</span>`;
            menu.appendChild(noFiles);
            return;
        }
        files.forEach(f => {
            const fileId = 'file:' + f.path;
            const isAttached = window._aiAttachments.some(a => a.id === fileId);
            const icon = getFileIcon(f.name);
            const item = document.createElement('button');
            item.className = 'ai-attach-item' + (isAttached ? ' attached' : '');
            item.dataset.attachId = fileId;
            item.innerHTML = `<span class="ai-chip-icon">${isAttached ? '✓' : icon}</span><span>${f.name}</span>`;
            item.onclick = () => {
                toggleAIAttachment(fileId, 'file', f.name, icon);
                const nowAttached = window._aiAttachments.some(a => a.id === fileId);
                item.className = 'ai-attach-item' + (nowAttached ? ' attached' : '');
                item.querySelector('.ai-chip-icon').textContent = nowAttached ? '✓' : icon;
            };
            menu.appendChild(item);
        });
    });
}
window.openAIAttachMenu = openAIAttachMenu;

/** Update attach menu items' checked state (when chips are removed directly) */
function updateAttachMenuState() {
    document.querySelectorAll('.ai-attach-menu .ai-attach-item[data-attach-id]').forEach(item => {
        const id = item.dataset.attachId;
        const isAttached = window._aiAttachments.some(a => a.id === id);
        item.className = 'ai-attach-item' + (isAttached ? ' attached' : '');
        const iconEl = item.querySelector('.ai-chip-icon');
        if (iconEl) {
            if (id.startsWith('page:')) {
                iconEl.textContent = isAttached ? '✓' : '📄';
            } else if (id.startsWith('file:')) {
                iconEl.textContent = isAttached ? '✓' : getFileIcon(id.split('/').pop());
            }
        }
    });
}

/** Get an appropriate icon for a file type */
function getFileIcon(filename) {
    const ext = (filename || '').split('.').pop().toLowerCase();
    const icons = {
        'css': '🎨', 'js': '⚡', 'json': '📋', 'html': '🌐', 'htm': '🌐',
        'txt': '📝', 'md': '📝', 'xml': '📋', 'svg': '🖼️',
        'py': '🐍', 'sh': '⚙️', 'yaml': '📋', 'yml': '📋',
    };
    return icons[ext] || '📎';
}

/** Fetch project files from backend */
async function fetchProjectFiles() {
    try {
        const files = await eel.list_project_files()();
        return files || [];
    } catch (e) {
        console.warn('[AI Attach] Could not list project files:', e);
        return [];
    }
}

// --- Auto-attach pages when page scope changes ---
// When the user selects "current", "all", or "custom" pages, auto-populate chips
function syncAttachmentsFromPageScope() {
    const scopeSel = document.getElementById('ai-page-scope');
    if (!scopeSel) return;

    const scope = scopeSel.value;

    // Remove all page-type attachments first
    window._aiAttachments = window._aiAttachments.filter(a => a.type !== 'page');

    if (scope === 'current') {
        // Attach the current page
        let currentPageId = '';
        try {
            currentPageId = typeof state !== 'undefined' && state.current_page
                ? state.current_page
                : (typeof appData !== 'undefined' && appData.current_page ? appData.current_page : '');
        } catch(e) {}
        if (!currentPageId && typeof appData === 'object' && appData && appData.pages) {
            const pageOrder = appData.page_order || Object.keys(appData.pages);
            currentPageId = pageOrder[0] || '';
        }
        if (currentPageId) {
            const title = (typeof appData === 'object' && appData && appData.page_titles && appData.page_titles[currentPageId])
                ? appData.page_titles[currentPageId] : currentPageId;
            addAIAttachment('page:' + currentPageId, 'page', title, '📄');
        }
    } else if (scope === 'all') {
        if (typeof appData === 'object' && appData && appData.pages) {
            const pageOrder = appData.page_order || Object.keys(appData.pages);
            pageOrder.forEach(pid => {
                const title = (appData.page_titles && appData.page_titles[pid]) ? appData.page_titles[pid] : pid;
                addAIAttachment('page:' + pid, 'page', title, '📄');
            });
        }
    }
    // For 'custom', user picks pages from the checklist or attach menu — no auto-population
    renderAIAttachmentChips();
}

/**
 * Open AI settings - navigates to the App Settings page in Global Settings.
 */
function openAISettings() {
    // If in fullscreen, exit fullscreen first so settings overlay is clearly on top
    let chatWindow = document.getElementById('ai-chat-window');
    if (chatWindow && chatWindow.classList.contains('ai-fullscreen')) {
        toggleAIChatFullscreen();
    }
    // Open global settings and switch to app page
    if (typeof openGlobalSettings === 'function') {
        openGlobalSettings();
    } else {
        let overlay = document.getElementById('settings-overlay');
        if (overlay) overlay.style.display = 'flex';
    }
    // Switch to the app settings page (which contains AI config)
    setTimeout(() => {
        if (typeof switchSettingsPage === 'function') {
            switchSettingsPage('app');
        }
    }, 100);
}
window.openAISettings = openAISettings;

/**
 * Auto-resize textarea as user types (like ChatGPT).
 */
function setupAutoResizeTextarea() {
    const textarea = document.getElementById('ai-input');
    if (!textarea) return;
    textarea.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = Math.min(this.scrollHeight, 200) + 'px';
    });
}

/**
 * Open the AI settings help page in a new window
 */
window.openAIHelp = function() {
    try {
        window.open('ai_help.html', '_blank', 'width=900,height=800,scrollbars=yes');
    } catch (err) {
        console.error('Failed to open AI help page:', err);
    }
};