// settings.js — Briefing settings, news topics, credentials, routing
// Extracted from dashboard.html (lines 7089-7572)

// ── Daily Briefing settings ────────────────────────────────────────
async function loadBriefingSettings() {
    try {
        const res = await apiFetch(API + '/api/settings/briefing');
        const data = await res.json();
        const tog = document.getElementById('toggle-briefing');
        const row = document.getElementById('briefing-time-row');
        const inp = document.getElementById('briefing-time-input');
        const status = document.getElementById('briefing-status');
        if (!tog) return;
        if (data.enabled) {
            tog.classList.add('on');
            row.style.display = 'block';
        } else {
            tog.classList.remove('on');
            row.style.display = 'none';
        }
        inp.value = data.time || '08:00';
        status.textContent = data.enabled ? 'Briefing active at ' + (data.time || '08:00') : 'Briefing off';
    } catch (_) {}
}

async function toggleBriefing() {
    const tog = document.getElementById('toggle-briefing');
    const row = document.getElementById('briefing-time-row');
    const inp = document.getElementById('briefing-time-input');
    const willEnable = !tog.classList.contains('on');
    tog.classList.toggle('on', willEnable);
    row.style.display = willEnable ? 'block' : 'none';
    try {
        await apiFetch(API + '/api/settings/briefing', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({enabled: willEnable, time: inp.value || '08:00'})
        });
        await loadBriefingSettings();
    } catch (_) {}
}

async function saveBriefingTime() {
    const tog = document.getElementById('toggle-briefing');
    const inp = document.getElementById('briefing-time-input');
    const status = document.getElementById('briefing-status');
    const enabled = tog.classList.contains('on');
    try {
        const res = await apiFetch(API + '/api/settings/briefing', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({enabled, time: inp.value || '08:00'})
        });
        const data = await res.json();
        if (data.error) { status.textContent = data.error; return; }
        status.textContent = data.message || 'Saved';
        setTimeout(() => loadBriefingSettings(), 1200);
    } catch (_) {}
}

// ── News Topics settings ────────────────────────────────────────────
let _newsTopics = [];

async function loadNewsTopics() {
    try {
        const res = await apiFetch(API + '/api/settings/news-topics');
        const data = await res.json();
        _newsTopics = data.topics || [];
        renderNewsTopics();
        const addRow = document.getElementById('news-add-row');
        if (addRow) addRow.style.display = _newsTopics.length >= 5 ? 'none' : 'flex';
    } catch (_) {}
}

function renderNewsTopics() {
    const el = document.getElementById('news-topics-list');
    if (!el) return;
    if (!_newsTopics.length) {
        el.innerHTML = '<span style="font-size:0.8rem;color:var(--text-dim);">No topics yet</span>';
        return;
    }
    el.innerHTML = _newsTopics.map((t, i) =>
        '<span style="display:inline-flex;align-items:center;gap:4px;margin:3px 4px 3px 0;padding:3px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:20px;font-size:0.8rem;">'
        + escapeHtml(t)
        + '<button onclick="removeNewsTopic(' + i + ')" style="background:none;border:none;cursor:pointer;color:var(--text-dim);font-size:0.85rem;padding:0 0 0 4px;line-height:1;" title="Remove">&times;</button>'
        + '</span>'
    ).join('');
}

async function addNewsTopic() {
    if (_newsTopics.length >= 5) return;
    const inp = document.getElementById('news-topic-input');
    const msg = document.getElementById('news-topics-msg');
    const topic = inp.value.trim().toLowerCase();
    if (!topic) return;
    if (_newsTopics.includes(topic)) {
        msg.textContent = 'Already tracking "' + topic + '"';
        return;
    }
    _newsTopics.push(topic);
    inp.value = '';
    msg.textContent = '';
    await saveNewsTopics();
}

async function removeNewsTopic(idx) {
    _newsTopics.splice(idx, 1);
    await saveNewsTopics();
}

async function saveNewsTopics() {
    try {
        const res = await apiFetch(API + '/api/settings/news-topics', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({topics: _newsTopics})
        });
        const data = await res.json();
        if (data.topics) _newsTopics = data.topics;
        renderNewsTopics();
        const addRow = document.getElementById('news-add-row');
        if (addRow) addRow.style.display = _newsTopics.length >= 5 ? 'none' : 'flex';
    } catch (_) {}
}

// ── Settings Tab Switching + Credential Cards ─────────────────
let _credData = [];
let _credFilter = 'all';

function switchSettingsTab(tab) {
    const tabs = ['general', 'credentials', 'activity'];
    document.querySelectorAll('.set-tab').forEach((t, i) => {
        t.classList.toggle('active', tabs[i] === tab);
    });
    tabs.forEach(t => {
        const el = document.getElementById('set-' + t + '-tab');
        if (el) el.style.display = t === tab ? '' : 'none';
    });
    if (tab === 'credentials') loadCredentialCards();
    if (tab === 'activity') loadCredentialAudit();
}

async function loadCredentialAudit() {
    const list = document.getElementById('cred-audit-list');
    list.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
    try {
        const res = await apiFetch(API + '/api/credentials/audit?limit=50');
        const data = await res.json();
        const events = data.events || [];
        if (events.length === 0) {
            list.innerHTML = '<div class="cred-empty-lg">No credential events recorded yet.</div>';
            return;
        }
        const typeIcons = {
            validated: '<i class="fas fa-check-circle cred-audit-icon-validated"></i>',
            refreshed: '<i class="fas fa-sync-alt cred-audit-icon-refreshed"></i>',
            updated: '<i class="fas fa-pen cred-audit-icon-updated"></i>',
            failed: '<i class="fas fa-times-circle cred-audit-icon-failed"></i>',
            accessed: '<i class="fas fa-eye cred-audit-icon-accessed"></i>',
            invalidated: '<i class="fas fa-ban cred-audit-icon-invalidated"></i>',
            created: '<i class="fas fa-plus-circle cred-audit-icon-created"></i>',
            deleted: '<i class="fas fa-trash cred-audit-icon-deleted"></i>',
            preflight_blocked: '<i class="fas fa-shield-alt cred-audit-icon-preflight_blocked"></i>',
            retry_refresh: '<i class="fas fa-redo cred-audit-icon-retry_refresh"></i>',
        };
        list.innerHTML = events.map(ev => {
            const icon = typeIcons[ev.event_type] || '<i class="fas fa-circle cred-audit-icon-accessed"></i>';
            const ts = ev.timestamp ? formatDate(ev.timestamp, 'datetime') : '';
            const svc = (ev.service_key || '').replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
            const typ = (ev.event_type || '').replace(/_/g, ' ');
            const detail = ev.details ? '<span class="cred-audit-detail">' + ev.details.substring(0, 80) + '</span>' : '';
            const src = ev.source ? '<span class="cred-audit-src">' + ev.source + '</span>' : '';
            return '<div class="cred-audit-entry">'
                + icon
                + '<strong class="cred-audit-svc">' + svc + '</strong>'
                + '<span class="cred-audit-type">' + typ + '</span>'
                + detail + src
                + '<span class="cred-audit-ts">' + ts + '</span>'
                + '</div>';
        }).join('');
    } catch (e) {
        list.innerHTML = '<div style="text-align:center;color:var(--error);padding:20px;">Failed to load audit events.</div>';
    }
}

async function loadCredentialCards() {
    const grid = document.getElementById('cred-cards-grid');
    grid.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
    try {
        const res = await apiFetch(API + '/api/credentials/status');
        const data = await res.json();
        _credData = data.credentials || [];
        renderCredentialCards();
        updateCredSummary();
    } catch (e) {
        grid.innerHTML = '<div class="cred-empty">Could not load credential status.</div>';
    }
}

function updateCredSummary() {
    const total = _credData.length;
    const configured = _credData.filter(c => c.configured).length;
    const valid = _credData.filter(c => c.valid === true).length;
    const attention = _credData.filter(c => c.attention_needed).length;
    let text = configured + ' of ' + total + ' credentials configured';
    if (valid > 0) text += ' · ' + valid + ' valid';
    if (attention > 0) text += ' · <span class="cred-attention-count">' + attention + ' need' + (attention === 1 ? 's' : '') + ' attention</span>';
    document.getElementById('cred-summary-text').innerHTML = text;
}

function filterCredentials(cat) {
    _credFilter = cat;
    document.querySelectorAll('.cred-filter').forEach(b => {
        b.classList.toggle('active', b.dataset.cat === cat);
    });
    renderCredentialCards();
}

function renderCredentialCards() {
    const grid = document.getElementById('cred-cards-grid');
    const items = _credFilter === 'all' ? _credData : _credData.filter(c => c.category === _credFilter);
    if (items.length === 0) {
        grid.innerHTML = '<div class="cred-empty">No credentials in this category.</div>';
        return;
    }
    let html = '';
    for (const c of items) {
        const badge = _credBadge(c);
        const icon = _credIcon(c.category);
        let detail = '';
        if (c.last_validated) {
            detail = 'Validated ' + formatDate(c.last_validated, 'datetime');
        }
        if (c.last_error) {
            detail = '<span class="cred-error-detail">' + _escHtml(c.last_error) + '</span>';
        }
        if (!c.configured) {
            detail = c.doc_hint || 'Not configured';
        }
        html += '<div class="cred-card" data-cat="' + c.category + '">'
            + '<div class="cred-card-head">'
            + '<i class="fas ' + icon + ' cred-card-icon"></i>'
            + '<span class="cred-name">' + _escHtml(c.display_name) + '</span>'
            + badge
            + '</div>'
            + '<div class="cred-card-detail">' + detail + '</div>'
            + '<div class="cred-card-actions">'
            + '<button class="btn btn-secondary" onclick="testCredential(\'' + c.service_key + '\')"><i class="fas fa-vial" style="margin-right:3px"></i>Test</button>';
        // Action button based on reauth_type
        if (c.reauth_type === 'simple_token' || c.reauth_type === 'multi_field') {
            const label = c.configured ? (c.attention_needed ? 'Re-authorize' : 'Update') : 'Set Up';
            html += ' <button class="btn btn-primary" onclick="openCredUpdateModal(\'' + c.service_key + '\')">'
                + '<i class="fas fa-pen" style="margin-right:3px"></i>' + label + '</button>';
        } else if (c.reauth_type === 'oauth_redirect') {
            html += ' <button class="btn btn-primary" onclick="credOAuthRedirect(\'' + c.service_key + '\')">'
                + '<i class="fas fa-key" style="margin-right:3px"></i>Re-authorize</button>';
        } else if (c.reauth_type === 'wizard_only') {
            html += ' <button class="btn btn-secondary" onclick="credOpenWizard(\'' + c.service_key + '\')">'
                + '<i class="fas fa-magic" style="margin-right:3px"></i>Setup Wizard</button>';
        }
        if (c.doc_url) {
            html += ' <a href="' + c.doc_url + '" target="_blank" rel="noopener"><i class="fas fa-external-link-alt" style="margin-right:2px"></i>Docs</a>';
        }
        html += '</div></div>';
    }
    grid.innerHTML = html;
}

function _credBadge(c) {
    if (c.attention_needed) return '<span class="cred-badge attention">Needs Attention</span>';
    if (c.valid === true) return '<span class="cred-badge valid">Valid</span>';
    if (!c.configured) return '<span class="cred-badge unconfigured">Not Set Up</span>';
    if (c.valid === null || c.valid === undefined) return '<span class="cred-badge untested">Untested</span>';
    return '<span class="cred-badge attention">Invalid</span>';
}

function _credIcon(category) {
    const map = {
        llm: 'fa-brain', integrations: 'fa-plug', apis: 'fa-cloud',
        social: 'fa-share-alt', selfhosted: 'fa-server', channels: 'fa-comments',
        security: 'fa-shield-alt', mesh: 'fa-network-wired'
    };
    return map[category] || 'fa-key';
}

async function testCredential(serviceKey) {
    // Find the card and show a spinner on the badge
    const cards = document.querySelectorAll('.cred-card');
    let targetCard = null;
    for (const card of cards) {
        if (card.querySelector('.cred-name') && card.innerHTML.includes(serviceKey)) {
            targetCard = card;
            break;
        }
    }
    // Visual feedback
    if (targetCard) {
        const badge = targetCard.querySelector('.cred-badge');
        if (badge) { badge.textContent = 'Testing...'; badge.className = 'cred-badge untested'; }
    }
    try {
        const res = await apiFetch(API + '/api/credentials/validate/' + serviceKey, {method: 'POST'});
        const data = await res.json();
        // Update in-memory data
        const idx = _credData.findIndex(c => c.service_key === serviceKey);
        if (idx >= 0) {
            Object.assign(_credData[idx], data);
        }
        renderCredentialCards();
        updateCredSummary();
    } catch (e) {
        if (targetCard) {
            const badge = targetCard.querySelector('.cred-badge');
            if (badge) { badge.textContent = 'Error'; badge.className = 'cred-badge attention'; }
        }
    }
}

function _escHtml(s) {
    if (!s) return '';
    const d = document.createElement('div'); d.textContent = s; return d.innerHTML;
}

// ── Credential Update Modal ─────────────────────────────────
let _credModalServiceKey = null;

async function openCredUpdateModal(serviceKey) {
    _credModalServiceKey = serviceKey;
    const modal = document.getElementById('cred-update-modal');
    const errEl = document.getElementById('cred-modal-error');
    const okEl = document.getElementById('cred-modal-success');
    errEl.style.display = 'none';
    okEl.style.display = 'none';
    document.getElementById('cred-modal-save').disabled = false;
    document.getElementById('cred-modal-fields').innerHTML = '<div class="loading"><div class="spinner"></div></div>';
    modal.style.display = 'flex';

    try {
        const res = await apiFetch(API + '/api/credentials/fields/' + serviceKey);
        const data = await res.json();
        document.getElementById('cred-modal-title').textContent = 'Update ' + data.display_name;
        document.getElementById('cred-modal-hint').textContent = data.doc_hint || '';
        const docsLink = document.getElementById('cred-modal-docs');
        if (data.doc_url) { docsLink.href = data.doc_url; docsLink.style.display = ''; }
        else { docsLink.style.display = 'none'; }

        let html = '';
        for (const f of data.fields) {
            html += '<div class="form-group" style="margin-bottom:12px;">'
                + '<label style="display:block;font-size:0.82rem;color:var(--text-dim);margin-bottom:4px;">' + _escHtml(f.label) + '</label>'
                + '<input type="' + (f.is_secret ? 'password' : 'text') + '" '
                + 'id="cred-field-' + f.env_var + '" '
                + 'placeholder="' + (f.masked_value || f.env_var) + '" '
                + 'style="width:100%;padding:8px 10px;background:var(--bg-input);border:1px solid var(--border);border-radius:6px;color:var(--text-primary);font-size:0.9rem;" '
                + 'autocomplete="off">'
                + '</div>';
        }
        document.getElementById('cred-modal-fields').innerHTML = html;
    } catch (e) {
        document.getElementById('cred-modal-fields').innerHTML = '<div style="color:var(--text-dim)">Could not load fields.</div>';
    }
}

function closeCredModal() {
    document.getElementById('cred-update-modal').style.display = 'none';
    _credModalServiceKey = null;
}

async function saveCredModal() {
    if (!_credModalServiceKey) return;
    const errEl = document.getElementById('cred-modal-error');
    const okEl = document.getElementById('cred-modal-success');
    const saveBtn = document.getElementById('cred-modal-save');
    errEl.style.display = 'none';
    okEl.style.display = 'none';
    saveBtn.disabled = true;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin" style="margin-right:4px"></i>Testing...';

    // Collect values from inputs
    const inputs = document.querySelectorAll('#cred-modal-fields input');
    const values = {};
    let anyFilled = false;
    for (const inp of inputs) {
        const key = inp.id.replace('cred-field-', '');
        if (inp.value.trim()) {
            values[key] = inp.value.trim();
            anyFilled = true;
        }
    }
    if (!anyFilled) {
        errEl.textContent = 'Please enter at least one value.';
        errEl.style.display = '';
        saveBtn.disabled = false;
        saveBtn.innerHTML = '<i class="fas fa-check" style="margin-right:4px"></i>Save & Test';
        return;
    }

    try {
        const res = await apiFetch(API + '/api/credentials/update/' + _credModalServiceKey, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({values: values})
        });
        const data = await res.json();
        if (data.valid) {
            okEl.textContent = 'Saved and validated successfully!';
            okEl.style.display = '';
            saveBtn.innerHTML = '<i class="fas fa-check" style="margin-right:4px"></i>Saved!';
            setTimeout(() => { closeCredModal(); loadCredentialCards(); }, 1200);
        } else {
            errEl.textContent = data.error || data.last_error || 'Validation failed';
            errEl.style.display = '';
            saveBtn.disabled = false;
            saveBtn.innerHTML = '<i class="fas fa-check" style="margin-right:4px"></i>Save & Test';
        }
    } catch (e) {
        errEl.textContent = 'Request failed. Please try again.';
        errEl.style.display = '';
        saveBtn.disabled = false;
        saveBtn.innerHTML = '<i class="fas fa-check" style="margin-right:4px"></i>Save & Test';
    }
}

// Close modal on overlay click
document.getElementById('cred-update-modal').addEventListener('click', function(e) {
    if (e.target === this) closeCredModal();
});

function credOAuthRedirect(serviceKey) {
    // Map to existing Google OAuth flow or show instructions
    const googleServices = {google_workspace:1, google_calendar:1, google_gmail:1, google_drive:1, google_contacts:1};
    if (serviceKey in googleServices) {
        // Switch to Connect panel and start Google OAuth
        document.querySelector('[data-panel="connect"]').click();
        setTimeout(() => loadConnectWizard(), 200);
    } else {
        // For other OAuth services, open the update modal with instructions
        openCredUpdateModal(serviceKey);
    }
}

function credOpenWizard(serviceKey) {
    // Switch to Connect panel for the wizard-only services
    document.querySelector('[data-panel="connect"]').click();
    setTimeout(() => loadConnectWizard(), 200);
}

async function loadJobClasses() {
    const grid = document.getElementById('job-class-grid');
    if (!grid) return;
    try {
        const res = await apiFetch(API + '/api/config/job-class');
        const data = await res.json();
        const active = data.active || '';
        const classes = data.classes || [];
        let html = '<div class="jc-card' + (!active ? ' active' : '') + '" onclick="switchJobClass(\'\')">'
            + '<div class="jc-icon"><i class="fas fa-times-circle"></i></div>'
            + '<div class="jc-name">None</div>'
            + '<div class="jc-desc">No specialization</div></div>';
        for (const jc of classes) {
            const isActive = jc.key === active;
            html += '<div class="jc-card' + (isActive ? ' active' : '') + '" onclick="switchJobClass(\'' + jc.key + '\')">'
                + '<div class="jc-icon"><i class="fas ' + jc.icon + '"></i></div>'
                + '<div class="jc-name">' + jc.name + '</div>'
                + '<div class="jc-desc">' + jc.description + '</div></div>';
        }
        grid.innerHTML = html;
    } catch (e) {
        grid.innerHTML = '<div style="color:var(--text-dim);">Could not load job classes.</div>';
    }
}

async function switchJobClass(key) {
    try {
        const res = await apiFetch(API + '/api/config/job-class', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({job_class: key})
        });
        const data = await res.json();
        if (data.result) {
            loadJobClasses();
            updateWorkspaceNav();
        }
    } catch (e) {}
}

