<?php
/**
 * AI Overview — Prompts list for a project.
 * @var array  $project
 * @var string $pageTitle
 */
$analyticsBase = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/')), '/');
?>

<style>
.aio-badge          { display:inline-flex;align-items:center;gap:6px;font-size:.72rem;font-weight:600;padding:3px 10px;border-radius:100px; }
.aio-badge-purple   { background:rgba(124,58,237,.1);color:#7c3aed; }
.platform-icon      { width:16px;height:16px;object-fit:contain;flex-shrink:0; }
.prompt-cell        { display:-webkit-box;-webkit-line-clamp:1;line-clamp:1;-webkit-box-orient:vertical;overflow:hidden; }
.status-icon        { width:20px;text-align:center; }
.vis-bar            { height:6px;border-radius:3px;background:#e2e8f0;overflow:hidden;min-width:60px; }
.vis-bar-fill       { height:100%;border-radius:3px;transition:width .3s; }
.tbl-count          { font-size:.85rem;font-weight:600; }
.tbl-muted          { font-size:.8rem;color:#94a3b8; }
.filter-row         { display:flex;flex-wrap:wrap;gap:.5rem;align-items:center; }
.page-link          { cursor:pointer; }

/* Competitor & Variations modal lists */
.var-tag            { display:inline-flex;align-items:center;gap:6px;background:#f1f5f9;border-radius:6px;padding:4px 10px;font-size:.78rem; }
.var-tag button     { border:none;background:none;padding:0;line-height:1;color:#ef4444;cursor:pointer; }

/* Model picker rows */
.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; }
</style>

<!-- Page header -->
<div class="d-flex flex-column flex-sm-row justify-content-between align-items-sm-center 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 active"><?= htmlspecialchars($project['business_name']) ?> — AI Overview</li>
            </ol>
        </nav>
        <h1 class="h5 mb-0 fw-bold">AI Overview Prompts</h1>
        <p class="text-muted small mb-0"><?= htmlspecialchars($project['website_url']) ?></p>
    </div>
    <div class="d-flex gap-2 flex-wrap">
        <button class="btn btn-outline-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#manageSidepanelModal">
            <i class="bi bi-sliders me-1"></i> Manage Project
        </button>
        <button class="btn btn-sm" style="background:#7c3aed;color:#fff;" data-bs-toggle="modal" data-bs-target="#addPromptModal">
            <i class="bi bi-plus-lg me-1"></i> Add Prompt
        </button>
    </div>
</div>

<!-- Filters row -->
<div class="filter-row mb-3">
    <!-- Date range picker -->
    <div class="position-relative">
        <button class="btn btn-sm btn-outline-secondary d-flex align-items-center gap-2" id="date-range-picker">
            <i class="bi bi-calendar3"></i>
            <span id="selected-date-text">Last 14 days</span>
            <i class="bi bi-chevron-down small opacity-50"></i>
        </button>
        <input type="hidden" id="date-range-input">
    </div>

    <!-- Country dropdown -->
    <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="selected-flag" src="https://flagcdn.com/in.svg" width="16" style="border-radius:2px;">
            <span id="selected-country-text">India</span>
        </button>
        <ul class="dropdown-menu shadow-sm border-0">
            <?php foreach ([
                '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'],
            ] 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>

    <!-- 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="idx-models-btn">
            <i class="bi bi-cpu me-1"></i><span id="idx-models-label">No models selected</span>
        </button>
        <div class="dropdown-menu shadow p-0" id="idx-model-panel" style="min-width:300px;">
            <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</span>
                <label class="d-flex align-items-center gap-1 mb-0" style="font-size:.78rem;cursor:pointer;">
                    <input type="checkbox" id="idx-chk-all-models" style="accent-color:#7c3aed;cursor:pointer;">
                    <span class="text-muted">All</span>
                </label>
            </div>
            <div id="idx-model-groups" class="py-1">
                <div class="text-center py-3 text-muted small">Loading…</div>
            </div>
        </div>
    </div>

    <!-- Search -->
    <div class="input-group input-group-sm ms-auto" style="width:220px;">
        <input type="text" id="prompt-search" class="form-control" placeholder="Search prompts…">
        <span class="input-group-text bg-white"><i class="bi bi-search"></i></span>
    </div>

    <!-- Bulk actions -->
    <button class="btn btn-sm btn-primary d-flex align-items-center gap-1" id="run-selected-btn">
        <i class="bi bi-play-fill"></i> Run Selected
    </button>
    <button class="btn btn-sm btn-outline-danger d-flex align-items-center gap-1" id="delete-selected-btn">
        <i class="bi bi-trash"></i> Delete
    </button>
</div>

<!-- Table card -->
<div class="card border-0 shadow-sm overflow-hidden">
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0 no-datatable" style="font-size:.85rem;">
            <thead class="table-light">
                <tr>
                    <th class="ps-3" style="width:36px;">
                        <input class="form-check-input" type="checkbox" id="chk-all">
                    </th>
                    <th style="width:32px;"></th>
                    <th style="width:40%;">Prompt</th>
                    <th class="text-center">Mentions</th>
                    <th class="text-center">Citations</th>
                    <th class="text-center">Total Refs</th>
                    <th class="text-center">Visibility</th>
                    <th class="pe-3 text-end">Competitors</th>
                </tr>
            </thead>
            <tbody id="prompts-tbody">
                <tr>
                    <td colspan="8" class="text-center py-5 text-muted">
                        <div class="spinner-border spinner-border-sm text-primary me-2"></div> Loading…
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

    <div class="card-footer bg-white border-top d-flex justify-content-between align-items-center py-2">
        <small class="text-muted" id="results-count">Loading…</small>
        <div class="d-flex align-items-center gap-3">
            <nav><ul class="pagination pagination-sm mb-0" id="pagination"></ul></nav>
            <div class="dropdown">
                <button class="btn btn-sm btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown" id="per-page-btn">10 / page</button>
                <ul class="dropdown-menu dropdown-menu-end shadow-sm border-0">
                    <?php foreach ([10, 20, 50] as $n): ?>
                    <li><a class="dropdown-item per-page-opt" href="#" data-val="<?= $n ?>"><?= $n ?> / page</a></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
    </div>
</div>

<!-- ─── Add Prompt Modal ────────────────────────────────────────────────────── -->
<div class="modal fade" id="addPromptModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header border-0">
                <h5 class="modal-title fw-bold">Add AI Prompt</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body pb-0">
                <label class="form-label small text-muted fw-semibold text-uppercase">Prompt Text</label>
                <textarea class="form-control" id="new-prompt-text" rows="4"
                    placeholder="e.g. What are the best website design services in India?"></textarea>
            </div>
            <div class="modal-footer border-0">
                <button class="btn btn-sm btn-light px-3" data-bs-dismiss="modal">Cancel</button>
                <button class="btn btn-sm px-4" id="save-prompt-btn" style="background:#7c3aed;color:#fff;">Save Prompt</button>
            </div>
        </div>
    </div>
</div>

<!-- ─── Manage Project Modal (Competitors & Variations) ───────────────────── -->
<div class="modal fade" id="manageSidepanelModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content border-0 shadow">
            <div class="modal-header border-0">
                <h5 class="modal-title fw-bold">Manage Project — <?= htmlspecialchars($project['business_name']) ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <ul class="nav nav-tabs mb-3" id="manageTabs">
                    <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tab-competitors">Competitors</a></li>
                    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-variations">Brand &amp; Domain Variations</a></li>
                </ul>
                <div class="tab-content">
                    <!-- Competitors tab -->
                    <div class="tab-pane fade show active" id="tab-competitors">
                        <p class="text-muted small">Track competitor mentions and citations in AI responses.</p>
                        <div class="row g-2 mb-3">
                            <div class="col-5"><input type="text" class="form-control form-control-sm" id="comp-name" placeholder="Competitor name"></div>
                            <div class="col-5"><input type="text" class="form-control form-control-sm" id="comp-url" placeholder="https://competitor.com"></div>
                            <div class="col-2"><button class="btn btn-sm btn-primary w-100" id="add-comp-btn">Add</button></div>
                        </div>
                        <div id="comp-list" class="d-flex flex-column gap-2"></div>
                    </div>
                    <!-- Variations tab -->
                    <div class="tab-pane fade" id="tab-variations">
                        <p class="text-muted small">Add alternate brand names and domains for more accurate mention matching.</p>
                        <div class="mb-4">
                            <div class="fw-semibold small mb-2">Brand Name Variations</div>
                            <div class="d-flex gap-2 mb-2">
                                <input type="text" class="form-control form-control-sm" id="brand-var-input" placeholder="e.g. Savit Digital">
                                <button class="btn btn-sm btn-outline-primary" id="add-brand-var-btn" style="white-space:nowrap;">Add</button>
                            </div>
                            <div id="brand-var-list" class="d-flex flex-wrap gap-2"></div>
                        </div>
                        <div>
                            <div class="fw-semibold small mb-2">Domain Variations</div>
                            <div class="d-flex gap-2 mb-2">
                                <input type="text" class="form-control form-control-sm" id="domain-var-input" placeholder="e.g. savit.io">
                                <button class="btn btn-sm btn-outline-primary" id="add-domain-var-btn" style="white-space:nowrap;">Add</button>
                            </div>
                            <div id="domain-var-list" class="d-flex flex-wrap gap-2"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<!-- Flatpickr -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

<script>
(function () {
    const projectId = <?= (int)$project['id'] ?>;
    const apiBase   = <?= json_encode($analyticsBase) ?>;
    const imgBase   = apiBase + '/../../ai-tool/theme/img/';
    let selectedCountry = 'IN';
    let currentPage     = 1;
    let limit           = 10;

    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:''},
    ];
    // [{platform, model, webSearch}] — populated after model load
    let selectedModels = [];

    // ── Date picker ────────────────────────────────────────────────────────
    flatpickr('#date-range-picker', {
        mode: 'range', dateFormat: 'Y-m-d',
        onClose(dates, str) {
            if (dates.length === 2) {
                document.getElementById('selected-date-text').textContent = str;
                document.getElementById('date-range-input').value = str;
                fetchPrompts();
            }
        }
    });

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

    // ── Multi-model picker ─────────────────────────────────────────────────
    function loadAllModels() {
        const container = document.getElementById('idx-model-groups');
        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;
                const idAttr  = 'idx_mc_' + platform.label.replace(/[^a-z0-9]/gi, '_');
                const webBadge = model.web_search_supported
                    ? `<span style="font-size:.66rem;background:#e0f2fe;color:#0369a1;padding:1px 5px;border-radius:4px;margin-left:4px;">web</span>` : '';
                const icon = platform.icon
                    ? `<img src="${imgBase}${platform.icon}" width="14" height="14" style="flex-shrink:0;" onerror="this.style.display='none'">`
                    : `<img src="https://www.google.com/favicon.ico" width="14" height="14" style="flex-shrink:0;">`;
                html += `<div class="model-check-row">
                    <input type="checkbox" id="${idAttr}" class="idx-model-chk"
                           data-platform="${escHtml(platform.label)}" data-model="${escHtml(model.name)}"
                           data-web="${model.web_search_supported ? '1' : '0'}"
                           style="accent-color:#7c3aed;width:15px;height:15px;flex-shrink:0;cursor:pointer;">
                    <label for="${idAttr}" style="flex:1;display:flex;align-items:center;gap:.4rem;font-size:.82rem;cursor:pointer;margin:0;">
                        ${icon}
                        <span>${escHtml(platform.label)}</span>
                        <span style="color:#94a3b8;font-size:.76rem;">(${escHtml(model.name)})</span>
                        ${webBadge}
                    </label>
                </div>`;
            });
            container.innerHTML = html || '<div class="text-center py-3 text-muted small">No models available.</div>';
            container.querySelectorAll('.idx-model-chk').forEach(cb => cb.addEventListener('change', syncModelSelection));
            document.getElementById('idx-chk-all-models').addEventListener('change', function () {
                container.querySelectorAll('.idx-model-chk').forEach(cb => { cb.checked = this.checked; });
                syncModelSelection();
            });
            syncModelSelection();
        });
    }

    function syncModelSelection() {
        selectedModels = [];
        document.querySelectorAll('.idx-model-chk:checked').forEach(cb => {
            selectedModels.push({ platform: cb.dataset.platform, model: cb.dataset.model, webSearch: cb.dataset.web === '1' });
        });
        const count = selectedModels.length;
        document.getElementById('idx-models-label').textContent =
            count === 0 ? 'No models selected' :
            count === 1 ? selectedModels[0].platform :
            `${count} models selected`;
        const allCbs = document.querySelectorAll('.idx-model-chk');
        const allCk  = document.getElementById('idx-chk-all-models');
        allCk.checked       = allCbs.length > 0 && [...allCbs].every(c => c.checked);
        allCk.indeterminate = count > 0 && count < allCbs.length;
    }

    loadAllModels();

    // ── Checkbox select-all ────────────────────────────────────────────────
    document.getElementById('chk-all').addEventListener('change', function () {
        document.querySelectorAll('.prompt-chk').forEach(c => c.checked = this.checked);
    });

    // ── Search ─────────────────────────────────────────────────────────────
    let searchTimer;
    document.getElementById('prompt-search').addEventListener('input', () => {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(() => { currentPage = 1; fetchPrompts(); }, 300);
    });

    // ── Per-page ───────────────────────────────────────────────────────────
    document.querySelectorAll('.per-page-opt').forEach(el => el.addEventListener('click', e => {
        e.preventDefault();
        limit = parseInt(el.dataset.val);
        document.getElementById('per-page-btn').textContent = limit + ' / page';
        currentPage = 1; fetchPrompts();
    }));

    // ── Pagination (event delegation) ─────────────────────────────────────
    document.getElementById('pagination').addEventListener('click', e => {
        const a = e.target.closest('.pg-link');
        if (!a) return;
        e.preventDefault();
        const p = parseInt(a.dataset.page);
        if (!isNaN(p)) { currentPage = p; fetchPrompts(); }
    });

    // ── Fetch prompts ──────────────────────────────────────────────────────
    function fetchPrompts() {
        const search    = document.getElementById('prompt-search').value;
        const dateRange = document.getElementById('date-range-input').value;
        const tbody     = document.getElementById('prompts-tbody');
        tbody.innerHTML = '<tr><td colspan="8" class="text-center py-5 text-muted"><div class="spinner-border spinner-border-sm text-primary me-2"></div>Loading…</td></tr>';

        const params = new URLSearchParams({ search, date_range: dateRange, page: currentPage, limit });
        fetch(`${apiBase}/api/projects/${projectId}/ai-overview/prompts?${params}`)
            .then(r => r.json())
            .then(renderTable)
            .catch(() => {
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-danger py-4">Error loading prompts.</td></tr>';
            });
    }

    function renderTable(res) {
        const data       = res.data || [];
        const total      = res.total || 0;
        const totalPages = res.total_pages || 1;
        const tbody      = document.getElementById('prompts-tbody');

        if (!data.length) {
            tbody.innerHTML = '<tr><td colspan="8" class="text-center py-5 text-muted">No prompts found.</td></tr>';
        } else {
            tbody.innerHTML = data.map(p => {
                const vis     = parseInt(p.visibility_score) || 0;
                const visColor= vis >= 60 ? '#22c55e' : vis >= 30 ? '#f59e0b' : '#ef4444';
                const compTxt = p.competitors_mentions > 0 ? p.competitors_mentions : '<span class="text-muted">None</span>';
                return `<tr>
                    <td class="ps-3"><input class="form-check-input prompt-chk" type="checkbox" value="${p.id}"></td>
                    <td><div class="status-icon" data-id="${p.id}"><i class="bi bi-circle text-secondary opacity-25"></i></div></td>
                    <td>
                        <a href="${apiBase}/ai-overview/${projectId}/prompt/${p.id}" class="text-decoration-none fw-medium prompt-cell"
                           style="color:#7c3aed;" title="${escHtml(p.prompt_text)}">${escHtml(p.prompt_text)}</a>
                    </td>
                    <td class="text-center tbl-count brand-mentions-${p.id}">${parseInt(p.brand_mentions)||0}</td>
                    <td class="text-center tbl-count domain-citations-${p.id}">${parseInt(p.domain_citations)||0}</td>
                    <td class="text-center tbl-count total-citations-${p.id}">${parseInt(p.total_citations)||0}</td>
                    <td class="text-center">
                        <div class="d-flex align-items-center gap-2 justify-content-center">
                            <div class="vis-bar" style="width:60px;"><div class="vis-bar-fill" style="width:${vis}%;background:${visColor};"></div></div>
                            <span class="tbl-muted">${vis}%</span>
                        </div>
                    </td>
                    <td class="pe-3 text-end tbl-muted">${compTxt}</td>
                </tr>`;
            }).join('');
        }

        // Results count
        const start = (currentPage - 1) * limit + 1;
        const end   = Math.min(currentPage * limit, total);
        document.getElementById('results-count').textContent = total
            ? `Viewing ${start}–${end} of ${total}`
            : 'No results';

        // Pagination
        let pag = '';
        if (totalPages > 1) {
            pag += `<li class="page-item ${currentPage <= 1 ? 'disabled' : ''}"><a class="page-link pg-link" data-page="${currentPage - 1}"><i class="bi bi-chevron-left"></i></a></li>`;
            for (let i = 1; i <= totalPages; i++) {
                if (i === 1 || i === totalPages || (i >= currentPage - 1 && i <= currentPage + 1)) {
                    pag += `<li class="page-item ${i === currentPage ? 'active' : ''}"><a class="page-link pg-link" data-page="${i}">${i}</a></li>`;
                } else if (i === 2 || i === totalPages - 1) {
                    pag += `<li class="page-item disabled"><span class="page-link">…</span></li>`;
                }
            }
            pag += `<li class="page-item ${currentPage >= totalPages ? 'disabled' : ''}"><a class="page-link pg-link" data-page="${currentPage + 1}"><i class="bi bi-chevron-right"></i></a></li>`;
        }
        document.getElementById('pagination').innerHTML = pag;
    }

    // ── Add prompt ─────────────────────────────────────────────────────────
    document.getElementById('save-prompt-btn').addEventListener('click', () => {
        const text = document.getElementById('new-prompt-text').value.trim();
        if (!text) return;
        const btn = document.getElementById('save-prompt-btn');
        btn.disabled = true; btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Saving…';

        fetch(`${apiBase}/api/projects/${projectId}/ai-overview/prompts`, {
            method: 'POST',
            headers: {'Content-Type':'application/json'},
            body: JSON.stringify({prompt_text: text})
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                bootstrap.Modal.getInstance(document.getElementById('addPromptModal'))?.hide();
                document.getElementById('new-prompt-text').value = '';
                fetchPrompts();
            } else {
                alert(data.error || 'Error saving prompt');
            }
        })
        .finally(() => { btn.disabled = false; btn.textContent = 'Save Prompt'; });
    });

    // ── Run selected ───────────────────────────────────────────────────────
    document.getElementById('run-selected-btn').addEventListener('click', async () => {
        const ids = [...document.querySelectorAll('.prompt-chk:checked')].map(c => c.value);
        if (!ids.length)          { Swal.fire('No prompts selected', '', 'warning'); return; }
        if (!selectedModels.length) { Swal.fire('No models selected', 'Choose at least one model from the picker.', 'warning'); return; }

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

        let done = 0;
        const total = ids.length * selectedModels.length;

        // Run prompts in batches of 5, each prompt against all selected models in parallel
        for (let i = 0; i < ids.length; i += 5) {
            const batch = ids.slice(i, i + 5);
            await Promise.all(batch.map(id =>
                Promise.all(selectedModels.map(m =>
                    runSingle(id, m).then(() => {
                        done++;
                        btn.innerHTML = `<span class="spinner-border spinner-border-sm me-1"></span>${done}/${total}`;
                    })
                ))
            ));
        }

        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-play-fill"></i> Run Selected';
        Swal.fire('Done', `Ran ${ids.length} prompt(s) × ${selectedModels.length} model(s).`, 'success');
        fetchPrompts();
    });

    function runSingle(promptId, modelEntry) {
        const icon = document.querySelector(`.status-icon[data-id="${promptId}"]`);
        if (icon) icon.innerHTML = '<div class="spinner-border text-primary" style="width:.8rem;height:.8rem;"></div>';

        return fetch(`${apiBase}/api/ai-overview/prompts/${promptId}/run`, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                platform:             modelEntry.platform,
                model_version:        modelEntry.model,
                web_search_supported: modelEntry.webSearch,
                country_code:         selectedCountry,
            }),
        })
        .then(r => r.json())
        .then(data => {
            if (!icon) return;
            if (data.success) {
                icon.innerHTML = '<i class="bi bi-check-circle-fill text-success"></i>';
                const m = document.querySelector(`.brand-mentions-${promptId}`);
                const c = document.querySelector(`.domain-citations-${promptId}`);
                const t = document.querySelector(`.total-citations-${promptId}`);
                if (m) m.textContent = data.brand_mentions   || 0;
                if (c) c.textContent = data.domain_citations  || 0;
                if (t) t.textContent = (data.links || []).length;
            } else if (data.in_progress) {
                icon.innerHTML = `<i class="bi bi-hourglass-split text-warning" title="Already running in another session"></i>`;
            } else {
                icon.innerHTML = `<i class="bi bi-x-circle-fill text-danger" title="${escHtml(data.error || 'Error')}"></i>`;
            }
        })
        .catch(() => {
            if (icon) icon.innerHTML = '<i class="bi bi-exclamation-circle-fill text-warning"></i>';
        });
    }

    // ── Delete selected ────────────────────────────────────────────────────
    document.getElementById('delete-selected-btn').addEventListener('click', () => {
        const ids = [...document.querySelectorAll('.prompt-chk:checked')].map(c => parseInt(c.value));
        if (!ids.length) { Swal.fire('No prompts selected', '', 'warning'); return; }

        Swal.fire({
            title: 'Delete prompts?',
            text: `This will permanently delete ${ids.length} prompt(s) and all their run history.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            confirmButtonText: 'Delete',
        }).then(result => {
            if (!result.isConfirmed) return;
            fetch(`${apiBase}/api/projects/${projectId}/ai-overview/prompts`, {
                method: 'DELETE',
                headers: {'Content-Type':'application/json'},
                body: JSON.stringify({prompt_ids: ids})
            })
            .then(r => r.json())
            .then(() => { document.getElementById('chk-all').checked = false; fetchPrompts(); });
        });
    });

    // ── Competitors management ─────────────────────────────────────────────
    function loadCompetitors() {
        fetch(`${apiBase}/api/projects/${projectId}/ai-overview/competitors`)
            .then(r => r.json())
            .then(data => {
                const list = document.getElementById('comp-list');
                list.innerHTML = (data.competitors || []).map(c => `
                    <div class="d-flex align-items-center gap-2 border rounded p-2 small" id="comp-${c.id}">
                        <span class="fw-semibold">${escHtml(c.competitor_name)}</span>
                        <span class="text-muted">${escHtml(c.competitor_url)}</span>
                        <button class="btn btn-link btn-sm text-danger ms-auto p-0" onclick="deleteComp(${c.id})">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>`).join('') || '<p class="text-muted small">No competitors added yet.</p>';
            });
    }

    document.getElementById('add-comp-btn').addEventListener('click', () => {
        const name = document.getElementById('comp-name').value.trim();
        const url  = document.getElementById('comp-url').value.trim();
        if (!name || !url) return;
        fetch(`${apiBase}/api/projects/${projectId}/ai-overview/competitors`, {
            method: 'POST', headers: {'Content-Type':'application/json'},
            body: JSON.stringify({competitor_name: name, competitor_url: url})
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                document.getElementById('comp-name').value = '';
                document.getElementById('comp-url').value = '';
                loadCompetitors();
            }
        });
    });

    window.deleteComp = id => {
        fetch(`${apiBase}/api/ai-overview/competitors/${id}`, {method:'DELETE'})
            .then(() => loadCompetitors());
    };

    // ── Variations management ──────────────────────────────────────────────
    function loadVariations() {
        fetch(`${apiBase}/api/projects/${projectId}/ai-overview/variations`)
            .then(r => r.json())
            .then(data => {
                renderVarList('brand-var-list',  data.brand_variations  || [], 'brand');
                renderVarList('domain-var-list', data.domain_variations || [], 'domain');
            });
    }

    function renderVarList(containerId, items, type) {
        const key  = type === 'brand' ? 'variation_name' : 'variation_domain';
        document.getElementById(containerId).innerHTML = items.map(v =>
            `<span class="var-tag">${escHtml(v[key])}<button onclick="deleteVar(${v.id},'${type}')">×</button></span>`
        ).join('');
    }

    function addVar(type) {
        const inputId = type === 'brand' ? 'brand-var-input' : 'domain-var-input';
        const val     = document.getElementById(inputId).value.trim();
        if (!val) return;
        fetch(`${apiBase}/api/projects/${projectId}/ai-overview/variations`, {
            method: 'POST', headers: {'Content-Type':'application/json'},
            body: JSON.stringify({type, value: val})
        })
        .then(r => r.json())
        .then(() => { document.getElementById(inputId).value = ''; loadVariations(); });
    }

    window.deleteVar = (id, type) => {
        fetch(`${apiBase}/api/ai-overview/variations/${id}?type=${type}`, {method:'DELETE'})
            .then(() => loadVariations());
    };

    document.getElementById('add-brand-var-btn').addEventListener('click',  () => addVar('brand'));
    document.getElementById('add-domain-var-btn').addEventListener('click', () => addVar('domain'));

    // Load manage-panel data when modal opens
    document.getElementById('manageSidepanelModal').addEventListener('show.bs.modal', () => {
        loadCompetitors();
        loadVariations();
    });

    // ── Utility ────────────────────────────────────────────────────────────
    function escHtml(str) {
        return String(str ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }

    // ── Initial load ───────────────────────────────────────────────────────
    fetchPrompts();
})();
</script>
