// ── AI Tab ─────────────────────────────────────────────────────────────
// Configures the provider/key/model that powers the generated app's AI
// Assistant. The API key is write-only from the browser's perspective: the
// server never sends it back (only an `ai.has_key` flag), and a blank key on
// save means "keep the stored one".

// Provider hints + default-model placeholders (mirrors AiClient::providers()).
const AI_PROVIDER_META = {
    anthropic:  { hint: 'Claude — great reasoning. Key: console.anthropic.com', model: 'claude-sonnet-5' },
    openai:     { hint: 'ChatGPT models. Key: platform.openai.com', model: 'gpt-4o-mini' },
    gemini:     { hint: 'Google Gemini — generous free tier. Key: aistudio.google.com', model: 'gemini-2.0-flash' },
    deepseek:   { hint: 'DeepSeek — very low cost. Key: platform.deepseek.com', model: 'deepseek-chat' },
    groq:       { hint: 'Groq — fast, free Llama/Mixtral. Key: console.groq.com', model: 'llama-3.3-70b-versatile' },
    mistral:    { hint: 'Mistral — European models. Key: console.mistral.ai', model: 'mistral-small-latest' },
    openrouter: { hint: 'OpenRouter — one key, many models. Key: openrouter.ai', model: 'openai/gpt-4o-mini' },
    custom:     { hint: 'Any OpenAI-compatible endpoint — set a Base URL below.', model: '' },
};

function aiApplyProvider() {
    const prov = document.getElementById('aiProvider')?.value || 'anthropic';
    const meta = AI_PROVIDER_META[prov] || AI_PROVIDER_META.anthropic;
    const hint = document.getElementById('aiProviderHint'); if (hint) hint.textContent = meta.hint;
    const model = document.getElementById('aiModel'); if (model) model.placeholder = meta.model ? ('default: ' + meta.model) : 'model id (required for custom)';
    // Base URL is only relevant to the Custom (OpenAI-compatible) provider.
    const row = document.getElementById('aiBaseUrlRow');
    if (row) row.classList.toggle('d-none', prov !== 'custom' && !(document.getElementById('aiBaseUrl')?.value || '').trim());
}

function populateAiTab() {
    const cfg = currentConfig.ai || {};
    const set = (id, v) => { const el = document.getElementById(id); if (el) el.value = v; };
    set('aiProvider', cfg.provider || 'anthropic');
    set('aiModel', cfg.model || '');
    set('aiBaseUrl', cfg.base_url || '');
    set('aiMaxTokens', cfg.max_tokens || '');
    aiApplyProvider();
    // The key is never echoed back — leave it blank; the "key configured" badge
    // (synced from the has_key flag) tells the user one is stored.
    const badge = document.getElementById('aiKeyStatus');
    if (badge) badge.classList.toggle('d-none', !cfg.has_key);
    const keyInput = document.getElementById('aiApiKey');
    if (keyInput) keyInput.placeholder = cfg.has_key ? 'Leave blank to keep the saved key' : 'paste your provider API key';
}

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('aiProvider')?.addEventListener('change', () => { aiApplyProvider(); saveSection('ai'); });
    document.querySelectorAll('#aiPane input, #aiPane select').forEach(el => {
        if (el.id !== 'aiProvider') el.addEventListener('change', () => saveSection('ai'));
    });

    document.getElementById('btnToggleAiKey')?.addEventListener('click', () => {
        const input = document.getElementById('aiApiKey');
        const icon = document.querySelector('#btnToggleAiKey i');
        if (!input) return;
        if (input.type === 'password') { input.type = 'text'; if (icon) icon.className = 'bi bi-eye-slash'; }
        else { input.type = 'password'; if (icon) icon.className = 'bi bi-eye'; }
    });

    document.getElementById('btnClearAiKey')?.addEventListener('click', async () => {
        const ok = await pp.dialog.confirm('Remove API key?', 'The AI Assistant will stop working in the generated app until a new key is added.', 'warning');
        if (!ok) return;
        await saveSection('ai', { clear_key: true });
        pp.dialog.toast('success', 'API key removed.');
        document.getElementById('aiKeyStatus')?.classList.add('d-none');
        document.getElementById('btnClearAiKey')?.remove();
        const input = document.getElementById('aiApiKey'); if (input) input.placeholder = 'paste your provider API key';
    });

    document.getElementById('btnTestAi')?.addEventListener('click', async () => {
        const result = document.getElementById('aiTestResult');
        const provider = document.getElementById('aiProvider')?.value || 'anthropic';
        const key = document.getElementById('aiApiKey')?.value.trim() || '';
        const model = document.getElementById('aiModel')?.value.trim() || '';
        const base_url = document.getElementById('aiBaseUrl')?.value.trim() || '';
        if (result) { result.className = 'small ms-2 text-muted'; result.textContent = 'Testing…'; }
        try {
            const res = await fetch(`${baseUrl}/project/${projectSlug}/misc/test-ai`, {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ provider, api_key: key, model, base_url })
            });
            const data = await res.json();
            if (!result) return;
            if (data.success) { result.className = 'small ms-2 text-success'; result.innerHTML = '<i class="bi bi-check-circle"></i> ' + (data.message || 'Connection OK'); }
            else { result.className = 'small ms-2 text-danger'; result.innerHTML = '<i class="bi bi-x-circle"></i> ' + (data.message || 'Failed'); }
        } catch (err) {
            if (result) { result.className = 'small ms-2 text-danger'; result.textContent = 'Network error.'; }
        }
    });
});
