<?php
/**
 * AI Overview — Prompt detail page (multi-model).
 * @var array       $project
 * @var array       $prompt
 * @var array|null  $latestRun
 * @var array       $latestLinks
 * @var string      $pageTitle
 */
$analyticsBase = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/')), '/');
$countries = [
    'IN' => ['India', 'in'],          'US' => ['United States', 'us'],
    'GB' => ['United Kingdom', 'gb'], 'CA' => ['Canada', 'ca'],
    'AU' => ['Australia', 'au'],      'AE' => ['UAE', 'ae'],
    'SG' => ['Singapore', 'sg'],      'DE' => ['Germany', 'de'],
];
$promptCountry = $prompt['country_code'] ?? 'IN';
[$countryName, $countryFlag] = $countries[$promptCountry] ?? $countries['IN'];

$platforms = [
    ['ChatGPT',        'chatgpt.svg'],
    ['Claude',         'claude.svg'],
    ['Gemini',         'gemini.svg'],
    ['Perplexity',     'perplexity.svg'],
    ['Google AI Mode', ''],
];
?>

<style>
.detail-stat-card   { border-radius:10px;border:1px solid #e2e8f0;padding:1rem 1.25rem; }
.stat-label         { font-size:.65rem;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#94a3b8; }
.stat-value         { font-size:1.6rem;font-weight:800;color:#0f172a;line-height:1.1; }

/* Model picker panel */
.model-picker-panel { min-width:340px;max-height:440px;overflow-y:auto; }
.model-group-header { font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#94a3b8;padding:.5rem .75rem .25rem;border-top:1px solid #f1f5f9; }
.model-group-header:first-child { border-top:none; }
.model-check-row    { display:flex;align-items:center;gap:.5rem;padding:.3rem .75rem;border-radius:6px;cursor:pointer;transition:background .15s; }
.model-check-row:hover { background:#f8fafc; }
.model-check-row input[type=checkbox] { accent-color:#7c3aed;width:15px;height:15px;flex-shrink:0;cursor:pointer; }
.model-check-row label { font-size:.82rem;color:#334155;cursor:pointer;margin:0;line-height:1.3; }

/* Result cards */
.result-card        { border:1px solid #e2e8f0;border-radius:12px;overflow:hidden;margin-bottom:1rem; }
.result-card-header { display:flex;align-items:center;gap:.6rem;padding:.75rem 1rem;background:#fafbfc;border-bottom:1px solid #e2e8f0;font-size:.85rem;font-weight:600; }
.result-card-body   { padding:1.25rem; }
.result-badge       { font-size:.72rem;font-weight:600;padding:2px 8px;border-radius:100px;white-space:nowrap; }
.badge-mention      { background:rgba(124,58,237,.1);color:#7c3aed; }
.badge-citation     { background:rgba(16,185,129,.1);color:#065f46; }

/* Markdown */
.markdown-body      { line-height:1.75;color:#334155;font-size:.9rem; }
.markdown-body p    { margin-bottom:.85rem; }
.markdown-body ul,.markdown-body ol { margin-bottom:.85rem;padding-left:1.5rem; }
.markdown-body li   { margin-bottom:.3rem; }
.markdown-body h1,.markdown-body h2,.markdown-body h3 { margin-top:1.4rem;margin-bottom:.6rem;font-weight:700;color:#0f172a; }
.markdown-body a    { color:#7c3aed;text-decoration:none; }
.markdown-body a:hover { text-decoration:underline; }
.markdown-body sup  { font-size:.72rem; }
.markdown-body sup a { color:#7c3aed;font-weight:700; }
.markdown-body pre  { background:#f8fafc;border-radius:8px;padding:1rem;overflow-x:auto;font-size:.82rem; }
.markdown-body code { font-size:.82rem; }

/* Links collapse table */
.links-table-wrap   { background:#f8fafc;border-top:1px solid #e2e8f0;padding:.75rem 1rem; }

/* Google AI Mode */
.sge-container      { background:linear-gradient(135deg,#f0f4ff 0%,#fff 100%);border-radius:12px;padding:20px;border:1px solid #e0e4f0; }
.sge-badge          { display:inline-flex;align-items:center;gap:6px;background:#fff;padding:3px 10px;border-radius:100px;border:1px solid #e8eaed;font-size:.78rem;font-weight:600;color:#1a73e8;margin-bottom:14px; }
.sge-sources-label  { font-size:.7rem;font-weight:700;text-transform:uppercase;color:#70757a;margin:14px 0 6px; }
.sge-grid           { display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:8px; }
.sge-card           { background:#fff;border:1px solid #dadce0;border-radius:10px;padding:10px;text-decoration:none;display:flex;flex-direction:column;transition:box-shadow .2s; }
.sge-card:hover     { box-shadow:0 3px 10px rgba(32,33,36,.1); }
.sge-card-title     { font-size:.8rem;font-weight:600;color:#1a0dab;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;margin-bottom:5px; }
.sge-card-domain    { font-size:.7rem;color:#70757a;margin-top:auto;display:flex;align-items:center;gap:4px; }

/* Competitor */
.mentions-badge     { font-size:.72rem;font-weight:600;background:rgba(34,197,94,.12);color:#15803d;padding:2px 8px;border-radius:100px; }

/* Empty / loading states */
.result-placeholder { text-align:center;padding:3rem 1rem;color:#94a3b8; }
.result-spinner     { display:flex;flex-direction:column;align-items:center;gap:.75rem;padding:2.5rem 1rem;color:#7c3aed; }

/* Result card header wraps on small screens */
.result-card-header { flex-wrap:wrap; }

/* Sticky only on large screens */
.detail-right-col { position:sticky;top:1.25rem;align-self:flex-start;max-height:calc(100vh - 2rem);overflow-y:auto; }

/* Bootstrap ms-md-auto shim */
@media (min-width:768px) { .ms-md-auto { margin-left:auto !important; } }
@media (max-width:767.98px) { .w-md-auto { width:auto !important; } }

@media (max-width:991.98px) {
    .detail-right-col   { position:static;max-height:none;overflow-y:visible;align-self:auto; }
    .model-picker-panel { min-width:min(320px, calc(100vw - 1.5rem)); }
}
@media (max-width:575.98px) {
    .detail-stat-card   { padding:.65rem .85rem; }
    .stat-value         { font-size:1.25rem; }
    .stat-label         { font-size:.6rem; }
    .result-card-body   { padding:.85rem; }
    .model-picker-panel { min-width:calc(100vw - 1.5rem);max-width:calc(100vw - 1.5rem); }
    .result-card-header { font-size:.78rem; }
    .result-badge       { font-size:.68rem;padding:2px 6px; }
}
</style>

<!-- Breadcrumb & header -->
<div class="d-flex flex-column flex-sm-row justify-content-between align-items-sm-start mb-4 gap-2">
    <div>
        <nav aria-label="breadcrumb" style="font-size:.8rem;">
            <ol class="breadcrumb mb-1">
                <li class="breadcrumb-item"><a href="<?= $analyticsBase ?>/" class="text-decoration-none text-muted">Analytics</a></li>
                <li class="breadcrumb-item"><a href="<?= $analyticsBase ?>/ai-overview/<?= (int)$project['id'] ?>" class="text-decoration-none text-muted">
                    <?= htmlspecialchars($project['business_name']) ?> — AI Overview</a>
                </li>
                <li class="breadcrumb-item active text-truncate" style="max-width:min(220px,40vw);">
                    <?= htmlspecialchars($prompt['prompt_text']) ?>
                </li>
            </ol>
        </nav>
        <h1 class="h5 mb-1 fw-bold"><?= htmlspecialchars($prompt['prompt_text']) ?></h1>
        <small class="text-muted"><i class="bi bi-link-45deg me-1"></i><?= htmlspecialchars($project['website_url']) ?></small>
    </div>
    <div class="d-flex gap-2 flex-wrap">
        <a href="<?= $analyticsBase ?>/ai-overview/<?= (int)$project['id'] ?>" class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-arrow-left me-1"></i>Back to Prompts
        </a>
        <button id="delete-prompt-btn" class="btn btn-sm btn-outline-danger" data-id="<?= (int)$prompt['id'] ?>">
            <i class="bi bi-trash me-1"></i>Delete
        </button>
    </div>
</div>

<!-- Controls row -->
<div class="d-flex flex-wrap align-items-center gap-2 mb-4" id="controls-row">

    <!-- Country picker -->
    <div class="dropdown">
        <button class="btn btn-sm btn-outline-secondary dropdown-toggle d-flex align-items-center gap-2" data-bs-toggle="dropdown">
            <img id="sel-flag" src="https://flagcdn.com/<?= $countryFlag ?>.svg" width="16" style="border-radius:2px;">
            <span id="sel-country-name"><?= $countryName ?></span>
        </button>
        <ul class="dropdown-menu shadow-sm border-0">
            <?php foreach ($countries as $code => [$name, $flag]): ?>
            <li><a class="dropdown-item country-opt d-flex align-items-center gap-2" href="#"
                   data-code="<?= $code ?>" data-name="<?= $name ?>" data-flag="<?= $flag ?>">
                <img src="https://flagcdn.com/<?= $flag ?>.svg" width="16" style="border-radius:2px;"> <?= $name ?>
            </a></li>
            <?php endforeach; ?>
        </ul>
    </div>

    <!-- History picker -->
    <div class="dropdown">
        <button class="btn btn-sm btn-outline-secondary dropdown-toggle d-flex align-items-center gap-2" data-bs-toggle="dropdown">
            <i class="bi bi-clock-history"></i> History
        </button>
        <ul class="dropdown-menu shadow-sm border-0" id="history-dropdown" style="min-width:min(280px,calc(100vw - 1.5rem));max-height:320px;overflow-y:auto;">
            <li><span class="dropdown-item disabled small">Loading…</span></li>
        </ul>
    </div>

    <!-- Multi-model picker -->
    <div class="dropdown">
        <button class="btn btn-sm btn-outline-secondary dropdown-toggle d-flex align-items-center gap-2"
                data-bs-toggle="dropdown" data-bs-auto-close="outside" id="models-picker-btn">
            <i class="bi bi-cpu me-1"></i><span id="models-btn-label">Loading models…</span>
        </button>
        <div class="dropdown-menu shadow model-picker-panel p-0" id="model-picker-panel">
            <!-- Select-all header -->
            <div class="d-flex align-items-center justify-content-between px-3 py-2" style="border-bottom:1px solid #f1f5f9;">
                <span class="fw-semibold" style="font-size:.82rem;">Select Models to Run</span>
                <label class="d-flex align-items-center gap-1 mb-0" style="font-size:.78rem;cursor:pointer;">
                    <input type="checkbox" id="chk-select-all" style="accent-color:#7c3aed;cursor:pointer;">
                    <span class="text-muted">All</span>
                </label>
            </div>
            <!-- Platform groups injected here by JS -->
            <div id="model-groups-container" class="py-1">
                <div class="text-center py-4 text-muted small">Loading…</div>
            </div>
        </div>
    </div>

    <!-- Run button — pushed right on md+, full-width row on xs -->
    <div class="d-flex align-items-center gap-2 ms-md-auto w-100 w-md-auto mt-1 mt-sm-0" style="flex:0 0 auto;">
        <button id="run-now-btn" class="btn btn-sm d-flex align-items-center gap-1 flex-shrink-0" style="background:#7c3aed;color:#fff;">
            <i class="bi bi-play-fill"></i> Run
        </button>
        <small class="text-muted text-truncate" id="last-run-time" style="max-width:160px;">
            <?php if ($latestRun): ?>
                Last run: <?= date('M d, H:i', strtotime($latestRun['created_at'])) ?>
            <?php else: ?>
                Never run
            <?php endif; ?>
        </small>
    </div>
</div>

<!-- Stat cards (aggregate) -->
<div class="row g-3 mb-4">
    <div class="col-4"><div class="detail-stat-card h-100">
        <div class="stat-label">Mentions</div>
        <div class="stat-value" id="stat-mentions"><?= (int)($prompt['brand_mentions'] ?? 0) ?></div>
    </div></div>
    <div class="col-4"><div class="detail-stat-card h-100">
        <div class="stat-label">Citations</div>
        <div class="stat-value" id="stat-citations"><?= (int)($prompt['domain_citations'] ?? 0) ?></div>
    </div></div>
    <div class="col-4"><div class="detail-stat-card h-100">
        <div class="stat-label">Total Refs</div>
        <div class="stat-value" id="stat-total"><?= (int)($prompt['total_citations'] ?? 0) ?></div>
    </div></div>
</div>

<!-- Main 2-column layout -->
<div class="row g-4">

    <!-- Left: stacked AI result cards -->
    <div class="col-lg-7">
        <div id="ai-results-container">
            <?php if ($latestRun && $latestRun['ai_response']): ?>
            <!-- Initial server-rendered card will be replaced by JS on load -->
            <div class="result-placeholder">
                <div class="spinner-border text-secondary spinner-border-sm mb-2"></div>
                <div class="small">Loading latest results…</div>
            </div>
            <?php else: ?>
            <div class="result-card">
                <div class="result-card-body">
                    <div class="result-placeholder">
                        <i class="bi bi-robot fs-1 d-block mb-3 opacity-25"></i>
                        Select models above and click <strong>Run</strong> to generate AI responses.
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Right: Link Tracking + Competitor Footprint (sticky on lg+) -->
    <div class="col-lg-5 d-flex flex-column gap-4 detail-right-col">

        <!-- Link Tracking -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-0 py-3 d-flex align-items-center justify-content-between">
                <h6 class="mb-0 fw-bold">Link Tracking</h6>
                <span class="text-muted small" id="links-model-label"></span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0 no-datatable" style="font-size:.82rem;">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-3" style="width:36px;">#</th>
                                <th>Title / URL</th>
                                <th class="pe-3">Domain</th>
                            </tr>
                        </thead>
                        <tbody id="links-tbody">
                            <tr><td colspan="3" class="text-center py-4 text-muted small">No links tracked yet.</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Competitor Footprint -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-0 py-3">
                <h6 class="mb-0 fw-bold">Competitor Footprint</h6>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0 no-datatable" style="font-size:.82rem;" id="competitors-table">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-3">Competitor</th>
                                <th class="text-center">Mentions</th>
                                <th class="pe-3">Citations</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr><td colspan="3" class="text-center py-4 text-muted small">Run prompt to view competitor data.</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>
</div>

<!-- Delete modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content border-0 shadow">
            <div class="modal-body text-center p-4">
                <i class="bi bi-exclamation-triangle-fill text-danger fs-1 mb-3 d-block"></i>
                <h6 class="fw-bold mb-2">Delete this prompt?</h6>
                <p class="text-muted small">All run history will be permanently removed.</p>
                <div class="d-flex gap-2 justify-content-center mt-3">
                    <button class="btn btn-sm btn-light px-3" data-bs-dismiss="modal">Cancel</button>
                    <button class="btn btn-sm btn-danger px-3" id="confirm-delete-btn">Delete</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>

<script>
(function () {
'use strict';

const promptId      = <?= (int)$prompt['id'] ?>;
const projectId     = <?= (int)$project['id'] ?>;
const apiBase       = <?= json_encode($analyticsBase) ?>;
const imgBase       = apiBase + '/../../ai-tool/theme/img/';
let selectedCountry = <?= json_encode($promptCountry) ?>;

// {platform: [{name, web_search_supported}, ...]}
const allModels   = {};
// Set of 'platform||model' keys currently checked
const checkedKeys = new Set();

const PLATFORMS = [
    {label:'ChatGPT',        icon:'chatgpt.svg'},
    {label:'Claude',         icon:'claude.svg'},
    {label:'Gemini',         icon:'gemini.svg'},
    {label:'Perplexity',     icon:'perplexity.svg'},
    {label:'Google AI Mode', icon:''},
];

// ── Utilities ──────────────────────────────────────────────────────────────
function esc(str) {
    return String(str ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
function renderMd(text) {
    if (!text) return '';
    let t = (text + '').replace(/<br\s*\/?>/gi,'\n')
                       .replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&')
                       .replace(/&quot;/g,'"').replace(/&#039;/g,"'");
    t = t.replace(/\[\[(\d+)\]\]\(([^)]+)\)/g,'<sup><a href="$2" target="_blank">[$1]</a></sup>');
    return marked.parse(t);
}
function platformKey(platform, model) { return platform + '||' + model; }
function platformIcon(icon) {
    return icon
        ? `<img src="${imgBase}${icon}" width="15" height="15" style="flex-shrink:0;" onerror="this.style.display='none'">`
        : `<img src="https://www.google.com/favicon.ico" width="15" height="15" style="flex-shrink:0;">`;
}

// ── Country ────────────────────────────────────────────────────────────────
document.querySelectorAll('.country-opt').forEach(el => el.addEventListener('click', e => {
    e.preventDefault();
    selectedCountry = el.dataset.code;
    document.getElementById('sel-flag').src = `https://flagcdn.com/${el.dataset.flag}.svg`;
    document.getElementById('sel-country-name').textContent = el.dataset.name;
}));

// ── Model picker: one best model per platform ──────────────────────────────
function loadAllModels() {
    const container = document.getElementById('model-groups-container');
    container.innerHTML = '<div class="text-center py-4 text-muted small">Loading models…</div>';

    // Fetch best (single) model per platform — no `all` param
    const fetches = PLATFORMS.map(p =>
        fetch(`${apiBase}/api/ai-overview/models?platform=${encodeURIComponent(p.label)}`)
            .then(r => r.json())
            .then(data => ({ platform: p, model: (data.models || [])[0] || null }))
            .catch(() => ({ platform: p, model: null }))
    );

    Promise.all(fetches).then(results => {
        let html = '';

        results.forEach(({ platform, model }) => {
            if (!model) return;
            allModels[platform.label] = [model];

            const key    = platformKey(platform.label, model.name);
            const idAttr = 'mc_' + key.replace(/[^a-z0-9]/gi, '_');
            const webBadge = model.web_search_supported
                ? `<span style="font-size:.68rem;background:#e0f2fe;color:#0369a1;padding:1px 5px;border-radius:4px;margin-left:4px;">web</span>`
                : '';

            html += `
            <div class="model-check-row">
                <input type="checkbox" id="${idAttr}"
                       data-platform="${esc(platform.label)}" data-model="${esc(model.name)}"
                       data-web="${model.web_search_supported ? '1' : '0'}"
                       class="model-checkbox">
                <label for="${idAttr}" style="flex:1;display:flex;align-items:center;gap:.4rem;">
                    ${platformIcon(platform.icon)}
                    <span>${esc(platform.label)}</span>
                    <span class="text-muted" style="font-size:.76rem;">(${esc(model.name)})</span>
                    ${webBadge}
                </label>
            </div>`;
        });

        container.innerHTML = html || '<div class="text-center py-4 text-muted small">No models available.</div>';

        container.querySelectorAll('.model-checkbox').forEach(cb => {
            cb.addEventListener('change', () => {
                const key = platformKey(cb.dataset.platform, cb.dataset.model);
                cb.checked ? checkedKeys.add(key) : checkedKeys.delete(key);
                updatePickerLabel();
                syncSelectAll();
            });
        });

        updatePickerLabel();
        bindSelectAll();
    });
}

function updatePickerLabel() {
    const count = getSelectedModels().length;
    document.getElementById('models-btn-label').textContent =
        count === 0 ? 'No models selected'
        : count === 1 ? getSelectedModels()[0].model
        : `${count} models selected`;
}

function syncSelectAll() {
    const allCbs = document.querySelectorAll('.model-checkbox');
    const allChecked = [...allCbs].every(cb => cb.checked);
    const allUnchecked = [...allCbs].every(cb => !cb.checked);
    const allCb = document.getElementById('chk-select-all');
    allCb.checked = allChecked;
    allCb.indeterminate = !allChecked && !allUnchecked;
}

function bindSelectAll() {
    document.getElementById('chk-select-all').addEventListener('change', function () {
        document.querySelectorAll('.model-checkbox').forEach(cb => {
            cb.checked = this.checked;
            const key = platformKey(cb.dataset.platform, cb.dataset.model);
            this.checked ? checkedKeys.add(key) : checkedKeys.delete(key);
        });
        updatePickerLabel();
    });
}

function getSelectedModels() {
    const sel = [];
    document.querySelectorAll('.model-checkbox:checked').forEach(cb => {
        sel.push({
            platform:  cb.dataset.platform,
            model:     cb.dataset.model,
            webSearch: cb.dataset.web === '1',
        });
    });
    return sel;
}

loadAllModels();

// ── History ────────────────────────────────────────────────────────────────
function loadHistory() {
    fetch(`${apiBase}/api/ai-overview/prompts/${promptId}/history`)
        .then(r => r.json())
        .then(data => {
            const dd = document.getElementById('history-dropdown');
            if (!data.success || !data.history.length) {
                dd.innerHTML = '<li><span class="dropdown-item disabled small">No history</span></li>';
                return;
            }

            // Group runs by minute
            const sessions = {};
            data.history.forEach(h => {
                const minute = h.time.substring(0, 13); // "Apr 29, 10:2" → same minute groups
                if (!sessions[minute]) sessions[minute] = { time: h.time, runs: [] };
                sessions[minute].runs.push(h);
            });

            let html = '';
            Object.values(sessions).forEach(session => {
                const runIds   = session.runs.map(r => r.id);
                const models   = session.runs.map(r => r.model.split(' (')[0]); // just platform name
                const unique   = [...new Set(models)];
                const label    = unique.slice(0, 3).join(' · ') + (unique.length > 3 ? ` +${unique.length - 3}` : '');
                html += `<li>
                    <a class="dropdown-item history-session small px-3 py-2" href="#"
                       data-run-ids="${esc(JSON.stringify(runIds))}">
                        <div class="fw-semibold" style="font-size:.8rem;">${esc(label)}</div>
                        <div class="text-muted" style="font-size:.72rem;">${esc(session.time)}</div>
                    </a>
                </li>`;
            });
            dd.innerHTML = html;
        });
}
loadHistory();

document.getElementById('history-dropdown').addEventListener('click', e => {
    const item = e.target.closest('.history-session');
    if (!item) return;
    e.preventDefault();
    const runIds = JSON.parse(item.dataset.runIds || '[]');
    loadHistorySession(runIds);
});

function loadHistorySession(runIds) {
    const container = document.getElementById('ai-results-container');
    container.innerHTML = runIds.map(id =>
        `<div class="result-card" id="rcard-h-${id}">
            <div class="result-card-body">
                <div class="result-spinner">
                    <div class="spinner-border spinner-border-sm" style="color:#7c3aed;"></div>
                    <span class="small text-muted">Loading…</span>
                </div>
            </div>
         </div>`
    ).join('');

    // Reset right-side panels
    resetRightPanels();

    const fetches = runIds.map(id =>
        fetch(`${apiBase}/api/ai-overview/runs/${id}`)
            .then(r => r.json())
            .then(data => ({ id, data }))
    );

    Promise.allSettled(fetches).then(results => {
        let totalMentions = 0, totalCitations = 0, totalRefs = 0;
        let allLinks = [], allCompetitors = [];
        let firstDone = true;

        results.forEach(({ status, value }) => {
            if (status !== 'fulfilled') return;
            const { id, data } = value;
            const card = document.getElementById(`rcard-h-${id}`);
            if (!card) return;
            if (data.success) {
                fillCard(card, data.model, data);
                totalMentions   += data.brand_mentions   || 0;
                totalCitations  += data.domain_citations || 0;
                totalRefs       += (data.links || []).length;
                allLinks         = allLinks.concat(data.links || []);
                if (data.competitor_data?.length) allCompetitors = data.competitor_data;
                if (firstDone) {
                    updateLinksPanel(data.links || [], data.model);
                    firstDone = false;
                }
            } else if (data.in_progress) {
                card.innerHTML = inProgressCardBody(data.model || '');
            } else {
                card.innerHTML = errorCardBody(data.error || 'Unknown error');
            }
        });

        document.getElementById('stat-mentions').textContent  = totalMentions;
        document.getElementById('stat-citations').textContent = totalCitations;
        document.getElementById('stat-total').textContent     = totalRefs;
        renderCompetitors(allCompetitors);
        document.getElementById('last-run-time').textContent = results[0]?.value?.data?.run_time
            ? `Last run: ${results[0].value.data.run_time}` : '';
    });
}

// ── Run prompt (multi-model) ───────────────────────────────────────────────
document.getElementById('run-now-btn').addEventListener('click', () => {
    const selected = getSelectedModels();
    if (!selected.length) {
        alert('Please select at least one model.');
        return;
    }

    const btn = document.getElementById('run-now-btn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Running…';

    const container = document.getElementById('ai-results-container');

    // Create a spinner card per selected model
    container.innerHTML = selected.map(s => {
        const key = platformKey(s.platform, s.model);
        return `<div class="result-card" id="rcard-${CSS.escape(key)}">
            <div class="result-card-header">
                ${platformIcon(PLATFORMS.find(p => p.label === s.platform)?.icon || '')}
                <span>${esc(s.platform)} <span class="opacity-50 small">(${esc(s.model)})</span></span>
            </div>
            <div class="result-card-body">
                <div class="result-spinner">
                    <div class="spinner-border spinner-border-sm" style="color:#7c3aed;"></div>
                    <span class="small text-muted">Asking ${esc(s.platform)}… this may take up to 30 s</span>
                </div>
            </div>
        </div>`;
    }).join('');

    resetRightPanels();

    let completed  = 0;
    let totalMentions = 0, totalCitations = 0, totalRefs = 0;
    let allCompetitors = [];
    let firstDone  = true;

    const promises = selected.map(s =>
        fetch(`${apiBase}/api/ai-overview/prompts/${promptId}/run`, {
            method:  'POST',
            headers: {'Content-Type': 'application/json'},
            body:    JSON.stringify({
                platform:             s.platform,
                model_version:        s.model,
                web_search_supported: s.webSearch,
                country_code:         selectedCountry,
            }),
        })
        .then(r => r.json())
        .then(data => {
            const key  = platformKey(s.platform, s.model);
            const card = document.getElementById('rcard-' + CSS.escape(key));
            if (card) {
                const modelLabel = `${s.platform} (${s.model})`;
                const headerHtml = `<div class="result-card-header">
                    ${platformIcon(PLATFORMS.find(p => p.label === s.platform)?.icon || '')}
                    <span>${esc(modelLabel)}</span>
                </div>`;
                if (data.success) {
                    fillCard(card, modelLabel, data);
                    totalMentions   += data.brand_mentions   || 0;
                    totalCitations  += data.domain_citations || 0;
                    totalRefs       += (data.links || []).length;
                    if (data.competitor_data?.length) allCompetitors = data.competitor_data;
                    if (firstDone) {
                        updateLinksPanel(data.links || [], modelLabel);
                        firstDone = false;
                    }
                } else if (data.in_progress) {
                    card.innerHTML = headerHtml + inProgressCardBody(modelLabel);
                } else {
                    card.innerHTML = headerHtml + errorCardBody(data.error || 'Unknown error');
                }
            }
            completed++;
            btn.innerHTML = `<span class="spinner-border spinner-border-sm me-1"></span>${completed}/${selected.length}`;
            return data;
        })
        .catch(err => {
            const key  = platformKey(s.platform, s.model);
            const card = document.getElementById('rcard-' + CSS.escape(key));
            if (card) card.innerHTML = errorCardBody('Network error');
            completed++;
        })
    );

    Promise.allSettled(promises).then(() => {
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-play-fill"></i> Run';
        document.getElementById('stat-mentions').textContent  = totalMentions;
        document.getElementById('stat-citations').textContent = totalCitations;
        document.getElementById('stat-total').textContent     = totalRefs;
        document.getElementById('last-run-time').textContent  = `Last run: ${new Date().toLocaleString('en-GB',{month:'short',day:'2-digit',hour:'2-digit',minute:'2-digit'}).replace(',',',')}`;
        renderCompetitors(allCompetitors);
        loadHistory();
    });
});

// ── Fill a result card with response data ─────────────────────────────────
function fillCard(card, modelLabel, data) {
    const isGoogle = modelLabel.includes('Google AI Mode');
    const links    = data.links || [];

    let responseHtml = '';
    if (isGoogle) {
        const cards = links.map(l =>
            `<a href="${esc(l.url)}" target="_blank" class="sge-card">
                <div class="sge-card-title">${esc(l.title || 'Untitled')}</div>
                <div class="sge-card-domain">
                    <img src="https://www.google.com/s2/favicons?domain=${esc(l.domain)}&sz=16" width="12">
                    ${esc(l.domain)}
                </div>
             </a>`
        ).join('');
        responseHtml = `<div class="sge-container">
            <div class="sge-badge"><img src="https://www.google.com/favicon.ico" width="14"> AI Overview</div>
            <div class="markdown-body">${renderMd(data.ai_response)}</div>
            ${cards ? '<div class="sge-sources-label">Sources</div><div class="sge-grid">' + cards + '</div>' : ''}
        </div>`;
    } else {
        responseHtml = `<div class="markdown-body">${renderMd(data.ai_response)}</div>`;
    }

    // Inline links toggle
    const linksToggleId = 'links-' + Math.random().toString(36).slice(2);
    const linksHtml = links.length
        ? `<div class="links-table-wrap collapse" id="${linksToggleId}">
            <table class="table table-sm align-middle mb-0 no-datatable" style="font-size:.78rem;">
                <thead class="table-light">
                    <tr><th style="width:32px;">#</th><th>URL</th><th>Domain</th></tr>
                </thead>
                <tbody>${links.map(l => `<tr>
                    <td class="fw-bold text-center">${l.rank}</td>
                    <td><div class="fw-semibold" style="font-size:.75rem;">${esc(l.title)}</div>
                        <a href="${esc(l.url)}" target="_blank" class="text-truncate d-block small"
                           style="color:#7c3aed;max-width:260px;">${esc(l.url)}</a></td>
                    <td class="text-muted">${esc(l.domain)}</td>
                </tr>`).join('')}</tbody>
            </table>
        </div>`
        : '';

    const mentionBadge  = `<span class="result-badge badge-mention ms-auto">${data.brand_mentions || 0} mentions</span>`;
    const citationBadge = `<span class="result-badge badge-citation">${data.domain_citations || 0} citations</span>`;
    const linksBtn = links.length
        ? `<button class="btn btn-link btn-sm p-0 ms-2 text-decoration-none" style="font-size:.78rem;color:#7c3aed;"
                   data-bs-toggle="collapse" data-bs-target="#${linksToggleId}">
                <i class="bi bi-link-45deg"></i> ${links.length} link${links.length !== 1 ? 's' : ''}
           </button>
           <button class="btn btn-link btn-sm p-0 ms-1" style="font-size:.78rem;color:#64748b;"
                   onclick="window.aiCopyLinks && window.aiCopyLinks(this)"
                   data-links="${esc(JSON.stringify(links))}">
               <i class="bi bi-table"></i> show in panel
           </button>`
        : '';

    const platform = modelLabel.split(' (')[0];
    const icon     = PLATFORMS.find(p => p.label === platform)?.icon || '';

    card.innerHTML = `
        <div class="result-card-header">
            ${platformIcon(icon)}
            <span>${esc(modelLabel)}</span>
            ${mentionBadge}
            ${citationBadge}
            ${linksBtn}
        </div>
        <div class="result-card-body">${responseHtml}</div>
        ${linksHtml}`;
}

// "show in panel" button handler
window.aiCopyLinks = function(btn) {
    try {
        const links = JSON.parse(btn.dataset.links || '[]');
        const label = btn.closest('.result-card')?.querySelector('.result-card-header span')?.textContent?.trim() || '';
        updateLinksPanel(links, label);
        btn.innerHTML = '<i class="bi bi-check2"></i> shown';
        setTimeout(() => { btn.innerHTML = '<i class="bi bi-table"></i> show in panel'; }, 1500);
    } catch(e) {}
};

function errorCardBody(msg) {
    return `<div class="result-card-body">
        <div class="text-center py-4 text-danger">
            <i class="bi bi-exclamation-circle fs-2 d-block mb-2"></i>
            <p class="small mb-0">${esc(msg)}</p>
        </div>
    </div>`;
}

function inProgressCardBody(model) {
    return `<div class="result-card-body">
        <div class="text-center py-4" style="color:#7c3aed;">
            <div class="spinner-border spinner-border-sm mb-2"></div>
            <p class="small fw-semibold mb-1">Already running on another session</p>
            <p class="small text-muted mb-0">${esc(model)} is already being generated.<br>Open <strong>History</strong> in a moment to load the result.</p>
        </div>
    </div>`;
}

// ── Right-panel helpers ────────────────────────────────────────────────────
function updateLinksPanel(links, modelLabel) {
    document.getElementById('links-model-label').textContent = modelLabel || '';
    const tbody = document.getElementById('links-tbody');
    tbody.innerHTML = links.length
        ? links.map(l => `<tr>
            <td class="ps-3 fw-bold text-center">${l.rank}</td>
            <td>
                <div class="fw-semibold mb-1" style="font-size:.78rem;">${esc(l.title)}</div>
                <a href="${esc(l.url)}" target="_blank" class="text-truncate d-block text-decoration-none small"
                   style="color:#7c3aed;max-width:210px;">${esc(l.url)}</a>
            </td>
            <td class="pe-3 text-muted small">${esc(l.domain)}</td>
          </tr>`).join('')
        : '<tr><td colspan="3" class="text-center py-4 text-muted small">No links tracked.</td></tr>';
}

function resetRightPanels() {
    document.getElementById('links-tbody').innerHTML =
        '<tr><td colspan="3" class="text-center py-4 text-muted small"><div class="spinner-border spinner-border-sm opacity-25"></div></td></tr>';
    document.getElementById('links-model-label').textContent = '';
    document.querySelector('#competitors-table tbody').innerHTML =
        '<tr><td colspan="3" class="text-center py-4 text-muted small">Running…</td></tr>';
}

function renderCompetitors(list) {
    const tbody = document.querySelector('#competitors-table tbody');
    if (!list.length) {
        tbody.innerHTML = '<tr><td colspan="3" class="text-center py-4 text-muted small">No competitors configured.</td></tr>';
        return;
    }
    tbody.innerHTML = list.map(c => {
        const linksList = (c.links?.length)
            ? '<ul class="list-unstyled mb-0">' + c.links.map(cl =>
                `<li class="text-truncate mb-1" style="max-width:180px;">
                    <a href="${esc(cl.url)}" target="_blank" class="text-decoration-none small"
                       style="color:#7c3aed;" title="${esc(cl.title||'')}">[${cl.rank}] ${esc(cl.domain)}</a>
                </li>`).join('') + '</ul>'
            : '<span class="text-muted small">None</span>';
        return `<tr>
            <td class="ps-3 fw-semibold">${esc(c.name)}</td>
            <td class="text-center">
                ${c.mentions > 0 ? `<span class="mentions-badge">${c.mentions}</span>` : '<span class="text-muted">0</span>'}
            </td>
            <td class="pe-3">${linksList}</td>
        </tr>`;
    }).join('');
}

// ── Auto-load latest session on page load ──────────────────────────────────
<?php if ($latestRun): ?>
fetch(`${apiBase}/api/ai-overview/prompts/${promptId}/history`)
    .then(r => r.json())
    .then(data => {
        if (!data.success || !data.history.length) return;
        // Take the most recent minute-session
        const latest = data.history[0];
        const minute = latest.time.substring(0, 13);
        const sessionRuns = data.history.filter(h => h.time.substring(0, 13) === minute);
        loadHistorySession(sessionRuns.map(h => h.id));
    });
<?php endif; ?>

// ── Delete prompt ──────────────────────────────────────────────────────────
document.getElementById('delete-prompt-btn').addEventListener('click', () => {
    new bootstrap.Modal(document.getElementById('deleteModal')).show();
});
document.getElementById('confirm-delete-btn').addEventListener('click', () => {
    fetch(`${apiBase}/api/projects/${projectId}/ai-overview/prompts`, {
        method:  'DELETE',
        headers: {'Content-Type':'application/json'},
        body:    JSON.stringify({prompt_ids: [promptId]}),
    }).then(r => r.json()).then(data => {
        if (data.success) window.location.href = `${apiBase}/ai-overview/${projectId}`;
    });
});

})();
</script>
