<?php
$sess = session();
$csrfName  = csrf_token();
$csrfValue = csrf_hash();
$apiConfigured = $apiConfigured ?? true;
$hasTrained = ($trainedCount ?? 0) > 0;

$statusLabelMap = [
    'pending'    => ['Pending',    'text-slate-500'],
    'processing' => ['Processing', 'text-amber-600'],
    'trained'    => ['Trained',    'text-emerald-600'],
    'error'      => ['Error',      'text-rose-600'],
];
$normalizeStatus = function($raw) use ($statusLabelMap) {
    $raw = (string) $raw;
    $numericMap = ['0'=>'pending','1'=>'processing','2'=>'trained','3'=>'error'];
    if (isset($numericMap[$raw])) return $numericMap[$raw];
    $clean = strtolower(trim($raw));
    if ($clean === '' || $clean === 'null') return 'pending';
    if ($clean === 'processed' || $clean === 'completed') return 'trained';
    if (!isset($statusLabelMap[$clean])) return 'pending';
    return $clean;
};
?>
<div class="space-y-6 max-w-7xl mx-auto">

    <?php
        $valOk    = isset($apiValidation) && is_array($apiValidation) && !empty($apiValidation['ok']);
        $valFail  = isset($apiValidation) && is_array($apiValidation) && empty($apiValidation['ok']);
        $savedKey = !empty($apiKeySaved);
        $failMsg  = $valFail ? (string) ($apiValidation['message'] ?? '') : '';
    ?>

    <?php if (!$apiConfigured && !$savedKey): ?>
        <div class="glass rounded-2xl border-2 border-amber-200/70 bg-gradient-to-r from-amber-50/80 via-yellow-50/50 to-orange-50/60 p-4 flex items-start gap-3 shadow-sm">
            <div class="w-9 h-9 rounded-lg bg-amber-100 border border-amber-200 flex items-center justify-center flex-shrink-0">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-amber-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"/></svg>
            </div>
            <div class="flex-1 min-w-0">
                <h4 class="text-sm font-bold text-amber-900">OpenAI API key isn't configured yet</h4>
                <p class="text-sm text-amber-800/80 mt-1 leading-relaxed">
                    The assistant can't run because no valid OpenAI key was found. Copy your API key from the
                    <a href="https://platform.openai.com/api-keys" target="_blank" rel="noreferrer noopener" class="underline decoration-amber-500/60 hover:text-amber-900">OpenAI dashboard</a>
                    and paste it into Chatbot Configuration.
                </p>
                <div class="mt-3 flex flex-wrap gap-2">
                    <a href="<?= esc(site_url('/admin/chatbot-config')) ?>" class="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl bg-amber-500 hover:bg-amber-600 text-white text-xs font-semibold shadow-sm transition">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M10.5 6h7.5m-7.5 3h7.5m-7.5 3h7.5m-9.75 4.5h12a2.25 2.25 0 002.25-2.25V6.75A2.25 2.25 0 0020.25 4.5h-12a2.25 2.25 0 00-2.25 2.25v10.5A2.25 2.25 0 008.25 16.5z"/></svg>
                        Go to Chatbot Config
                    </a>
                    <a href="https://platform.openai.com/account/api-keys" target="_blank" rel="noreferrer noopener" class="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl bg-white border border-amber-200 hover:bg-amber-100/60 text-amber-800 text-xs font-semibold transition">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25"/></svg>
                        Open platform.openai.com ↗
                    </a>
                </div>
            </div>
            <button type="button" id="dismissBannerBtn" class="text-amber-400 hover:text-amber-600 transition p-1 rounded-lg hover:bg-amber-100/70">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
            </button>
        </div>
    <?php elseif (!$apiConfigured && $savedKey && $valFail): ?>
        <div class="glass rounded-2xl border-2 border-rose-200/70 bg-gradient-to-r from-rose-50/80 via-pink-50/50 to-red-50/60 p-4 flex items-start gap-3 shadow-sm">
            <div class="w-9 h-9 rounded-lg bg-rose-100 border border-rose-200 flex items-center justify-center flex-shrink-0">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-rose-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"/></svg>
            </div>
            <div class="flex-1 min-w-0">
                <h4 class="text-sm font-bold text-rose-900">Saved OpenAI API key is not working</h4>
                <p class="text-sm text-rose-800/90 mt-1 leading-relaxed whitespace-pre-wrap"><?= esc($failMsg !== '' ? $failMsg : 'OpenAI rejected the stored key with an error. Open Chatbot Config, re-paste the key and use the new Test Connection button to validate it directly from this app.') ?></p>
                <div class="mt-3 flex flex-wrap items-center gap-2">
                    <a href="<?= esc(site_url('/admin/chatbot-config')) ?>" class="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl bg-rose-500 hover:bg-rose-600 text-white text-xs font-semibold shadow-sm transition">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M10.5 6h7.5m-7.5 3h7.5m-7.5 3h7.5m-9.75 4.5h12a2.25 2.25 0 002.25-2.25V6.75A2.25 2.25 0 0020.25 4.5h-12a2.25 2.25 0 00-2.25 2.25v10.5A2.25 2.25 0 008.25 16.5z"/></svg>
                        Fix in Chatbot Config
                    </a>
                    <a href="https://platform.openai.com/settings/billing" target="_blank" rel="noreferrer noopener" class="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl bg-white border border-rose-200 hover:bg-rose-100/60 text-rose-800 text-xs font-semibold transition">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 18.75a60.07 60.07 0 0115.797 2.101c.727.198 1.453-.342 1.453-1.096V18.75M3.75 4.5v.75A.75.75 0 013 6h-.75m0 0v-.375c0-.621.504-1.125 1.125-1.125H20.25M2.25 6v9m18-10.5v.75c0 .414.336.75.75.75h.75m-1.5-1.5h.375c.621 0 1.125.504 1.125 1.125v9.75c0 .621-.504 1.125-1.125 1.125h-.375m1.5-1.5H21a.75.75 0 00-.75.75v.75m0 0H3.75m0 0h-.375a1.125 1.125 0 01-1.125-1.125V15m1.5 1.5v-.75A.75.75 0 003 15h-.75M15 10.5a3 3 0 11-6 0 3 3 0 016 0zm3 0h.008v.008H18V10.5zm-12 0h.008v.008H6V10.5z"/></svg>
                        Check Billing / Credit ↗
                    </a>
                    <a href="https://platform.openai.com/api-keys" target="_blank" rel="noreferrer noopener" class="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl bg-white border border-rose-200 hover:bg-rose-100/60 text-rose-800 text-xs font-semibold transition">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25"/></svg>
                        View / Regenerate API key ↗
                    </a>
                </div>
            </div>
            <button type="button" id="dismissBannerBtn" class="text-rose-400 hover:text-rose-600 transition p-1 rounded-lg hover:bg-rose-100/70">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
            </button>
        </div>
    <?php endif; ?>

    <?php if ($apiConfigured && !$hasTrained): ?>
        <div class="glass rounded-2xl border-2 border-sky-200/60 bg-gradient-to-r from-sky-50/80 via-blue-50/40 to-indigo-50/60 p-4 flex items-start gap-3 shadow-sm">
            <div class="w-9 h-9 rounded-lg bg-sky-100 border border-sky-200 flex items-center justify-center flex-shrink-0">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-sky-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6.042A8.967 8.967 0 006 3.75c-1.052 0-2.062.18-3 .512v14.25A8.987 8.987 0 016 18c2.305 0 4.408.867 6 2.292m0-14.25a8.966 8.966 0 016-2.292c1.052 0 2.062.18 3 .512v14.25A8.987 8.987 0 0018 18a8.967 8.967 0 00-6 2.292m0-14.25v14.25"/></svg>
            </div>
            <div class="flex-1 min-w-0">
                <h4 class="text-sm font-bold text-sky-900">Documents uploaded but not yet trained</h4>
                <p class="text-sm text-sky-800/80 mt-1 leading-relaxed">
                    You have documents in the library, but none are trained. The AI assistant answers from trained document embeddings only.
                    Train documents first in the Documents screen to make them searchable.
                </p>
                <div class="mt-3 flex flex-wrap gap-2">
                    <a href="<?= esc(site_url('/admin/documents')) ?>" class="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl bg-sky-500 hover:bg-sky-600 text-white text-xs font-semibold shadow-sm transition">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M3 7.5L7.5 3m0 0L12 7.5M7.5 3v13.5m13.5 0L16.5 21m0 0L12 16.5m4.5 4.5V7.5"/></svg>
                        Go to Documents & Train
                    </a>
                </div>
            </div>
            <button type="button" id="dismissInfoBtn" class="text-sky-400 hover:text-sky-600 transition p-1 rounded-lg hover:bg-sky-100/70">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
            </button>
        </div>
    <?php endif; ?>

    <div class="flex items-center justify-between gap-4 flex-wrap">
        <div class="flex items-center gap-3">
            <div class="w-9 h-9 rounded-lg bg-gradient-to-br from-fuchsia-500 via-purple-500 to-indigo-600 flex items-center justify-center shadow-sm">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M9.75 3.104v5.714a2.25 2.25 0 01-.659 1.591L5 14.5M9.75 3.104c-.251.023-.501.05-.75.082m.75-.082a24.301 24.301 0 014.5 0m0 0v5.714a2.25 2.25 0 00.659 1.591L19 14.5M14.25 3.104c.251.023.501.05.75.082M14.25 3.104a24.3 0 014.5 0M5 14.5c.758.126 1.53.198 2.307.214a17.403 0 005.386 0c.777-.016 1.549-.088 2.307-.214m-10 0v1.143c0 .351.061.696.178 1.024m-.178-2.167v.05c0 .329.041.651.12.959M19 14.5v.05c0 .308.079.63.12.959M19 14.5c-.758.126-1.53.198-2.307.214a17.403 0 01-5.386 0M5 15.643v1.117c0 .313.036.622.107.923m13.893-2.037v1.117c0 .313-.036.622-.107.923m-13.679 2.037c.207.269.452.518.728.744a20.936 20.936 0 0013.696 0M8 20.5h8" />
                </svg>
            </div>
            <div>
                <h3 class="text-lg font-bold text-slate-800">AI Assistant</h3>
                <p class="text-xs text-slate-500">Ask questions across all trained documents</p>
            </div>
        </div>
        <div class="flex items-center gap-2">
            <span class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-emerald-50 border border-emerald-200 text-xs font-semibold text-emerald-700">
                <span class="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span>
                <?= $trainedCount ?> trained document<?= $trainedCount !== 1 ? 's' : '' ?>
            </span>
            <button id="clearChatBtn" type="button" class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-600 text-xs font-semibold transition">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
                Clear Chat
            </button>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-4 gap-6">
        <div class="lg:col-span-1 space-y-4">
            <div class="glass rounded-2xl p-4 shadow-sm border border-slate-200/60">
                <div class="flex items-center gap-2 mb-3">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-slate-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M3 7.5L7.5 3m0 0L12 7.5M7.5 3v13.5m13.5 0L16.5 21m0 0L12 16.5m4.5 4.5V7.5" />
                    </svg>
                    <h4 class="text-sm font-bold text-slate-800">Scope</h4>
                </div>
                <label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">Search within</label>
                <select id="scopeSelect" class="w-full px-3 py-2.5 rounded-xl bg-white border border-slate-200 text-sm text-slate-700 focus:outline-none focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500 transition">
                    <option value="">All Documents (Cross-search)</option>
                    <?php
                        $trainedDocs = [];
                        $untrainedDocs = [];
                        foreach ($documents as $d) {
                            $s = $normalizeStatus($d['embedding_status'] ?? 'pending');
                            [$lbl, $cls] = $statusLabelMap[$s];
                            $entry = [
                                'id'    => (int) $d['id'],
                                'title' => (string) $d['title'],
                                'status' => $s,
                                'label' => $lbl,
                                'labelClass' => $cls,
                            ];
                            if ($s === 'trained') $trainedDocs[] = $entry;
                            else $untrainedDocs[] = $entry;
                        }
                    ?>
                    <?php if (!empty($trainedDocs)): ?>
                        <optgroup label="✓ Trained — selectable">
                        <?php foreach ($trainedDocs as $td): ?>
                            <option value="<?= $td['id'] ?>">• <?= esc($td['title']) ?></option>
                        <?php endforeach; ?>
                        </optgroup>
                    <?php endif; ?>
                    <?php if (!empty($untrainedDocs)): ?>
                        <optgroup label="⚠ Not trained yet — disabled">
                        <?php foreach ($untrainedDocs as $ud): ?>
                            <option value="" disabled><?= esc($ud['title']) ?> — <?= esc($ud['label']) ?></option>
                        <?php endforeach; ?>
                        </optgroup>
                    <?php endif; ?>
                    <?php if (empty($trainedDocs) && empty($untrainedDocs)): ?>
                        <optgroup label="No documents in library yet">
                            <option value="" disabled>Upload documents first to enable scoped search</option>
                        </optgroup>
                    <?php endif; ?>
                </select>
                <p class="mt-2 text-[11px] text-slate-400 leading-relaxed">
                    Choose a specific <span class="font-semibold text-slate-600">trained</span> document or leave on "All Documents" for cross-search.
                    Untrained items are greyed-out until you run training from the Documents screen.
                </p>
            </div>

            <div id="suggestedWrap" class="glass rounded-2xl p-4 shadow-sm border border-slate-200/60">
                <div class="flex items-center justify-between gap-2 mb-3">
                    <div class="flex items-center gap-2 min-w-0">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-slate-600 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456zM16.894 20.567L16.5 21.75l-.394-1.183a2.25 2.25 0 00-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 001.423-1.423l.394-1.183l.394 1.183a2.25 2.25 0 001.423 1.423l1.183.394-1.183.394a2.25 2.25 0 00-1.423 1.423z" />
                        </svg>
                        <h4 class="suggested-label text-sm font-bold text-slate-800 truncate">Suggested Questions</h4>
                    </div>
                    <div class="flex items-center gap-1.5 flex-shrink-0">
                        <button
                            id="toggleSuggestBtn"
                            type="button"
                            title="Show / hide suggested questions"
                            data-collapse-state="collapsed"
                            class="inline-flex items-center gap-1 px-2 py-1 rounded-lg border border-slate-200 bg-white hover:bg-slate-50 hover:border-slate-300 text-slate-600 shadow-sm transition-all text-[10px] font-medium">
                            <svg id="toggleSuggestIcon" xmlns="http://www.w3.org/2000/svg" class="w-3 h-3 transition-transform -rotate-90" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" />
                            </svg>
                            <span id="toggleSuggestLabel">Show</span>
                        </button>
                        <button
                            id="regenerateSuggestBtn"
                            type="button"
                            title="Generate a new set of questions for the current scope"
                            class="suggest-regen-btn inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border border-slate-200 bg-white hover:bg-indigo-50 hover:border-indigo-200 hover:text-indigo-700 text-slate-600 shadow-sm transition-all text-[11px] font-medium flex-shrink-0 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-white disabled:hover:text-slate-600 disabled:hover:border-slate-200">
                            <svg id="regenerateSuggestIcon" xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99" />
                            </svg>
                            <span class="suggest-regen-label">Regenerate</span>
                        </button>
                    </div>
                </div>
                <div id="suggestedBody" class="hidden">
                    <div id="suggestedPillsContainer" class="suggested-pills space-y-1.5">
                        <?php
                        $defaultSuggestions = [
                            'Summarize all key information from the knowledge base',
                            'What are the most important talking points?',
                            'List any objections and suggested rebuttals',
                            'What are the key pricing details?',
                            'Provide qualifying questions for leads',
                        ];
                        ?>
                        <?php foreach ($defaultSuggestions as $s): ?>
                            <button type="button" class="suggestion-btn w-full text-left inline-flex items-start gap-2 px-2.5 py-1.5 rounded-lg bg-slate-50 hover:bg-purple-50 hover:text-purple-700 text-slate-600 border border-slate-100 hover:border-purple-200 transition leading-snug text-[11px] group">
                                <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3 text-slate-500 group-hover:text-purple-600 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                                <span class="break-words"><?= esc($s) ?></span>
                            </button>
                        <?php endforeach; ?>
                    </div>
                    <div id="suggestStatusCaption" class="mt-2 flex items-start gap-2 text-[10px] text-slate-400 leading-snug min-h-[14px]">
                        <span class="suggest-status-text inline-block">Default suggestions shown — loading AI-generated set…</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="lg:col-span-3">
            <div class="glass rounded-2xl shadow-sm border border-slate-200/60 overflow-hidden flex flex-col" style="height: calc(100vh - 280px); min-height: 520px;">
                <div class="px-6 py-3.5 bg-gradient-to-r from-slate-50/80 to-white border-b border-slate-200/60 flex items-center justify-between">
                    <div class="flex items-center gap-2">
                        <div class="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></div>
                        <span class="text-sm font-semibold text-slate-700">Conversation</span>
                    </div>
                    <span id="statusBadge" class="text-[11px] font-medium text-slate-400">Ready</span>
                </div>

                <div id="chatMessages" class="flex-1 overflow-y-auto px-6 py-6 space-y-5 scrollbar-thin">
                    <div class="flex items-start gap-3 fade-in">
                        <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-fuchsia-500 via-purple-500 to-indigo-600 flex items-center justify-center flex-shrink-0 shadow-md">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 9V5.25A2.25 2.25 0 0110.5 3h6a2.25 2.25 0 012.25 2.25v13.5A2.25 2.25 0 0116.5 21h-6a2.25 2.25 0 01-2.25-2.25V15m-3 0v-3a1.5 1.5 0 013 0v3m-3 0h3" />
                            </svg>
                        </div>
                        <div class="flex-1 max-w-[85%]">
                            <div class="px-4 py-3 rounded-2xl rounded-tl-md bg-white border border-slate-200/70 shadow-sm">
                                <p class="text-sm text-slate-700 leading-relaxed">
                                    Hi there! 👋 I'm your AI assistant, trained on all uploaded documents. Ask me anything about your knowledge base — I can summarize, answer questions, suggest rebuttals, and more.
                                </p>
                            </div>
                            <span class="text-[10px] text-slate-400 mt-1 ml-1 inline-block">Just now</span>
                        </div>
                    </div>
                </div>

                <div class="border-t border-slate-200/60 p-4 bg-white/40 backdrop-blur-sm">
                    <form id="chatForm" class="flex items-end gap-3">
                        <?= csrf_field() ?>
                        <div class="relative flex-1">
                            <textarea
                                id="questionInput"
                                name="question"
                                rows="1"
                                placeholder="Ask anything about your documents..."
                                class="w-full resize-none px-4 py-3 pr-12 rounded-2xl bg-white border border-slate-200 text-sm text-slate-700 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500 transition max-h-32"
                                style="min-height: 48px;"
                            ></textarea>
                        </div>
                        <button
                            id="sendBtn"
                            type="submit"
                            class="inline-flex items-center justify-center w-12 h-12 rounded-2xl bg-gradient-to-br from-fuchsia-600 via-purple-600 to-indigo-600 text-white shadow-md hover:shadow-lg hover:-translate-y-0.5 active:translate-y-0 transition-all disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:translate-y-0"
                        >
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5" />
                            </svg>
                        </button>
                    </form>
                    <p class="mt-2 text-[11px] text-slate-400 text-center">Press <kbd class="px-1.5 py-0.5 rounded bg-slate-100 border border-slate-200 text-slate-500 font-mono">Enter</kbd> to send · <kbd class="px-1.5 py-0.5 rounded bg-slate-100 border border-slate-200 text-slate-500 font-mono">Shift + Enter</kbd> for new line</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    const chatForm = document.getElementById('chatForm');
    const questionInput = document.getElementById('questionInput');
    const chatMessages = document.getElementById('chatMessages');
    const sendBtn = document.getElementById('sendBtn');
    const statusBadge = document.getElementById('statusBadge');
    const clearChatBtn = document.getElementById('clearChatBtn');
    const scopeSelect = document.getElementById('scopeSelect');
    const dismissBannerBtn = document.getElementById('dismissBannerBtn');
    const dismissInfoBtn = document.getElementById('dismissInfoBtn');
    const csrfName = <?= json_encode($csrfName) ?>;
    const csrfValue = <?= json_encode($csrfValue) ?>;

    const suggestUrl = <?= json_encode(site_url('/chat/suggest')) ?>;
    const suggestWrap = document.getElementById('suggestedWrap');
    const suggestPills = document.getElementById('suggestedPillsContainer');
    const suggestBody = document.getElementById('suggestedBody');
    const toggleSuggestBtn = document.getElementById('toggleSuggestBtn');
    const toggleSuggestIcon = document.getElementById('toggleSuggestIcon');
    const toggleSuggestLabel = document.getElementById('toggleSuggestLabel');
    const suggestLabel = suggestWrap ? suggestWrap.querySelector('.suggested-label') : null;
    const suggestRegenBtn = document.getElementById('regenerateSuggestBtn');
    const suggestRegenLabel = suggestRegenBtn ? suggestRegenBtn.querySelector('.suggest-regen-label') : null;
    const suggestRegenIcon = document.getElementById('regenerateSuggestIcon');
    const suggestStatus = document.getElementById('suggestStatusCaption');
    const suggestStatusText = suggestStatus ? suggestStatus.querySelector('.suggest-status-text') : null;
    let suggestBusy = false;

    if (toggleSuggestBtn && suggestBody) {
        try {
            if (localStorage.getItem('admin_suggest_open') !== '1') {
                suggestBody.classList.add('hidden');
                toggleSuggestIcon?.classList.add('-rotate-90');
                if (toggleSuggestLabel) toggleSuggestLabel.textContent = 'Show';
                toggleSuggestBtn.setAttribute('data-collapse-state', 'collapsed');
            } else {
                suggestBody.classList.remove('hidden');
                toggleSuggestIcon?.classList.remove('-rotate-90');
                if (toggleSuggestLabel) toggleSuggestLabel.textContent = 'Hide';
                toggleSuggestBtn.setAttribute('data-collapse-state', 'open');
            }
        } catch (e) {}
        toggleSuggestBtn.addEventListener('click', function () {
            var nowOpen = toggleSuggestBtn.getAttribute('data-collapse-state') !== 'open';
            if (nowOpen) {
                suggestBody.classList.remove('hidden');
                toggleSuggestIcon?.classList.remove('-rotate-90');
                if (toggleSuggestLabel) toggleSuggestLabel.textContent = 'Hide';
                toggleSuggestBtn.setAttribute('data-collapse-state', 'open');
            } else {
                suggestBody.classList.add('hidden');
                toggleSuggestIcon?.classList.add('-rotate-90');
                if (toggleSuggestLabel) toggleSuggestLabel.textContent = 'Show';
                toggleSuggestBtn.setAttribute('data-collapse-state', 'collapsed');
            }
            try { localStorage.setItem('admin_suggest_open', nowOpen ? '1' : '0'); } catch (e) {}
        });
    }

    const FALLBACK_SUGGESTIONS = [
        'Summarize all key information from the knowledge base',
        'What are the most important talking points?',
        'List any objections and suggested rebuttals',
        'What are the key pricing details?',
        'Provide qualifying questions for leads',
    ];

    function setSuggestBusy(isBusy, labelText) {
        suggestBusy = !!isBusy;
        if (suggestRegenBtn) {
            suggestRegenBtn.disabled = suggestBusy;
        }
        if (suggestRegenIcon) {
            if (suggestBusy) {
                suggestRegenIcon.classList.add('animate-spin');
            } else {
                suggestRegenIcon.classList.remove('animate-spin');
            }
        }
        if (suggestRegenLabel) {
            suggestRegenLabel.textContent = suggestBusy
                ? (typeof labelText === 'string' && labelText ? labelText : 'Generating…')
                : 'Regenerate';
        }
        if (suggestStatusText) {
            if (suggestBusy) {
                suggestStatusText.textContent = typeof labelText === 'string' && labelText
                    ? labelText
                    : 'Generating new AI suggestions for current scope…';
                suggestStatus.classList.remove('text-emerald-600', 'text-rose-500', 'text-amber-600');
                suggestStatus.classList.add('text-slate-400');
            }
        }
        if (scopeSelect) {
            scopeSelect.disabled = suggestBusy;
        }
    }

    function renderSuggestions(questions, opts) {
        opts = opts || {};
        const qs = Array.isArray(questions)
            ? questions.filter(q => typeof q === 'string' && q.trim().length >= 3).slice(0, 6)
            : [];
        const list = qs.length > 0 ? qs : (opts.useFallback === false ? [] : FALLBACK_SUGGESTIONS.slice(0, 5));

        if (suggestPills) {
            suggestPills.innerHTML = '';
            list.forEach(function (q) {
                const btn = document.createElement('button');
                btn.type = 'button';
                btn.className = 'suggestion-btn w-full text-left inline-flex items-start gap-2 px-2.5 py-1.5 rounded-lg bg-slate-50 hover:bg-indigo-50 hover:text-indigo-800 text-slate-600 border border-slate-100 hover:border-indigo-200 transition leading-snug text-[11px] group';
                btn.innerHTML =
                    '<svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3 text-slate-500 group-hover:text-indigo-600 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">' +
                    '<path stroke-linecap="round" stroke-linejoin="round" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>' +
                    '<span class="break-words leading-snug">' + escapeHtml(q) + '</span>';
                btn.addEventListener('click', function () { sendQuestion(q); });
                suggestPills.appendChild(btn);
            });
        }

        if (suggestLabel) {
            const title = opts.scopeType === 'single' ? 'Suggested Questions' : 'Suggested Questions';
            suggestLabel.textContent = title;
        }

        if (suggestStatusText) {
            const scope = (opts.docLabelsUsed && opts.docLabelsUsed.length)
                ? (opts.scopeType === 'single'
                    ? 'Scoped to 1 document: ' + opts.docLabelsUsed[0]
                    : 'Scoped to ' + opts.docLabelsUsed.length + ' document(s): ' + opts.docLabelsUsed.slice(0, 2).join('; ') + (opts.docLabelsUsed.length > 2 ? '; +' + (opts.docLabelsUsed.length - 2) : ''))
                : (opts.scopeType === 'single' ? 'Scoped to selected document' : 'Scoped to all trained documents');
            const warn = typeof opts.warn === 'string' && opts.warn.trim().length > 0;
            const charsUsed = typeof opts.contextChars === 'number' ? (' · ' + opts.contextChars.toLocaleString() + ' chars context') : '';
            const seedUsed = typeof opts.seed === 'string' && opts.seed ? (' · seed=' + opts.seed) : '';
            suggestStatusText.textContent = (warn ? '⚠ ' + opts.warn + ' | ' : '✓ ') + scope + charsUsed + seedUsed;
            suggestStatus.classList.remove('text-slate-400', 'text-emerald-600', 'text-rose-500', 'text-amber-600');
            if (warn) suggestStatus.classList.add('text-amber-600');
            else suggestStatus.classList.add('text-emerald-600');
        }
    }

    async function fetchSuggestions(opts) {
        opts = opts || {};
        if (suggestBusy) return;
        const docIdRaw = scopeSelect ? (scopeSelect.value || '') : '';
        const docId = (docIdRaw && String(docIdRaw).match(/^\d+$/)) ? String(docIdRaw) : '';
        const seed = opts.newSeed
            ? String(Math.floor(Math.random() * 900000) + 100000)
            : (typeof opts.seed === 'string' ? opts.seed : '');

        setSuggestBusy(true, opts.newSeed ? 'Re-generating new set…' : 'Generating suggestions for scope…');

        const body = new FormData();
        body.append(csrfName, csrfValue);
        if (docId !== '') body.append('document_id', docId);
        body.append('count', '5');
        if (seed) body.append('seed', seed);

        try {
            const res = await fetch(suggestUrl, { method: 'POST', body: body });
            const ct = res.headers.get('content-type') || '';
            let data = null;
            if (ct.indexOf('application/json') >= 0) data = await res.json();
            if (!data || !data.success) throw new Error((data && data.error) ? data.error : ('HTTP ' + res.status));
            renderSuggestions(data.questions || [], {
                scopeType: data.scope_type || (docId ? 'single' : 'all'),
                docLabelsUsed: data.doc_labels_used || [],
                contextChars: data.context_chars || 0,
                seed: data.seed || seed || '',
                warn: data.warn || '',
                useFallback: true,
            });
        } catch (e) {
            renderSuggestions(FALLBACK_SUGGESTIONS, {
                scopeType: docId ? 'single' : 'all',
                docLabelsUsed: [],
                contextChars: 0,
                seed: seed || '',
                warn: 'Network/AI error: ' + (e && e.message ? e.message : 'Unknown') + '. Showing default starter questions.',
                useFallback: false,
            });
            if (suggestStatusText) {
                suggestStatus.classList.remove('text-slate-400', 'text-emerald-600', 'text-amber-600');
                suggestStatus.classList.add('text-rose-500');
            }
        } finally {
            setSuggestBusy(false);
        }
    }

    if (suggestRegenBtn) {
        suggestRegenBtn.addEventListener('click', function () { fetchSuggestions({ newSeed: true }); });
    }
    if (scopeSelect) {
        scopeSelect.addEventListener('change', function () { fetchSuggestions({ newSeed: true }); });
    }
    setTimeout(function () { fetchSuggestions({ newSeed: true }); }, 200);

    function autoResize(el) {
        el.style.height = 'auto';
        el.style.height = Math.min(el.scrollHeight, 128) + 'px';
    }
    questionInput.addEventListener('input', () => autoResize(questionInput));

    function scrollToBottom() {
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    function nowStr() {
        const d = new Date();
        return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }

    function addUserMessage(text) {
        const wrap = document.createElement('div');
        wrap.className = 'flex items-start gap-3 justify-end fade-in';
        wrap.innerHTML = `
            <div class="flex-1 max-w-[85%] flex flex-col items-end">
                <div class="px-4 py-3 rounded-2xl rounded-tr-md bg-gradient-to-br from-fuchsia-600 via-purple-600 to-indigo-600 text-white shadow-md">
                    <p class="text-sm leading-relaxed whitespace-pre-wrap"></p>
                </div>
                <span class="text-[10px] text-slate-400 mt-1 mr-1 inline-block"></span>
            </div>
            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-emerald-400 to-cyan-500 flex items-center justify-center text-white text-xs font-bold flex-shrink-0 shadow-md">
                <?= strtoupper(substr(esc($sess->get('full_name') ?? 'U'), 0, 1)) ?>
            </div>
        `;
        wrap.querySelector('p.whitespace-pre-wrap').textContent = text;
        wrap.querySelector('span:last-of-type').textContent = nowStr();
        chatMessages.appendChild(wrap);
        scrollToBottom();
    }

    function addAssistantPlaceholder() {
        const wrap = document.createElement('div');
        wrap.className = 'flex items-start gap-3 fade-in';
        wrap.id = 'assistantPlaceholder';
        wrap.innerHTML = `
            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-fuchsia-500 via-purple-500 to-indigo-600 flex items-center justify-center flex-shrink-0 shadow-md">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 9V5.25A2.25 2.25 0 0110.5 3h6a2.25 2.25 0 012.25 2.25v13.5A2.25 2.25 0 0116.5 21h-6a2.25 2.25 0 01-2.25-2.25V15m-3 0v-3a1.5 1.5 0 013 0v3m-3 0h3" />
                </svg>
            </div>
            <div class="flex-1 max-w-[85%]">
                <div class="px-4 py-3 rounded-2xl rounded-tl-md bg-white border border-slate-200/70 shadow-sm">
                    <div class="flex items-center gap-1.5 py-1">
                        <span class="w-2 h-2 rounded-full bg-purple-400 animate-bounce" style="animation-delay: 0s"></span>
                        <span class="w-2 h-2 rounded-full bg-purple-400 animate-bounce" style="animation-delay: 0.15s"></span>
                        <span class="w-2 h-2 rounded-full bg-purple-400 animate-bounce" style="animation-delay: 0.3s"></span>
                    </div>
                </div>
            </div>
        `;
        chatMessages.appendChild(wrap);
        scrollToBottom();
        return wrap;
    }

    function appendFollowUpsToAnswer(flexColEl, followUps) {
        if (!flexColEl || !Array.isArray(followUps) || followUps.length === 0) return;
        const clean = followUps
            .filter(q => typeof q === 'string' && q.trim().length >= 3)
            .slice(0, 4);
        if (clean.length === 0) return;

        const wrap = document.createElement('div');
        wrap.className = 'mt-3 w-full flex flex-col items-start gap-1.5 pl-1';
        const label = document.createElement('div');
        label.className = 'inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-indigo-600/80 px-1.5';
        label.innerHTML =
            '<svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">' +
            '<path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" /></svg> Follow up';
        wrap.appendChild(label);
        const row = document.createElement('div');
        row.className = 'flex flex-wrap gap-1.5 w-full';
        clean.forEach(function (q) {
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'inline-flex items-start gap-1.5 px-3 py-1.5 rounded-2xl text-[12px] font-medium text-left bg-indigo-50 text-indigo-700 border border-indigo-100 hover:bg-indigo-100 hover:text-indigo-800 hover:border-indigo-200 transition-all shadow-sm group max-w-[calc(100%-4px)]';
            btn.innerHTML =
                '<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5 text-indigo-500 group-hover:text-indigo-600 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">' +
                '<path stroke-linecap="round" stroke-linejoin="round" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>' +
                '<span class="break-words leading-snug">' + escapeHtml(q) + '</span>';
            btn.addEventListener('click', function () {
                sendQuestion(q);
            });
            row.appendChild(btn);
        });
        wrap.appendChild(row);
        flexColEl.appendChild(wrap);
    }

    function replacePlaceholder(placeholder, answer, sources, followUps) {
        const answerEl = document.createElement('div');
        answerEl.className = 'flex items-start gap-3 fade-in';
        const sourcesHtml = (sources && sources.length)
            ? `<div class="mt-3 pt-3 border-t border-slate-100 flex flex-wrap gap-1.5">
                <span class="text-[10px] font-semibold text-slate-400 uppercase tracking-wider mr-1 self-center">Sources:</span>
                ${sources.map(s => `<span class="inline-flex items-center px-2 py-0.5 rounded-md bg-purple-50 text-[10px] font-medium text-purple-700 border border-purple-100">${escapeHtml(s)}</span>`).join('')}
            </div>`
            : '';
        answerEl.innerHTML = `
            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-fuchsia-500 via-purple-500 to-indigo-600 flex items-center justify-center flex-shrink-0 shadow-md">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M8.25 9V5.25A2.25 2.25 0 0110.5 3h6a2.25 2.25 0 012.25 2.25v13.5A2.25 2.25 0 0116.5 21h-6a2.25 2.25 0 01-2.25-2.25V15m-3 0v-3a1.5 1.5 0 013 0v3m-3 0h3" />
                </svg>
            </div>
            <div class="flex-1 max-w-[85%] ai-answer-col">
                <div class="px-4 py-3 rounded-2xl rounded-tl-md bg-white border border-slate-200/70 shadow-sm">
                    <div class="text-sm text-slate-700 leading-relaxed whitespace-pre-wrap"></div>
                    ${sourcesHtml}
                </div>
                <span class="text-[10px] text-slate-400 mt-1 ml-1 inline-block"></span>
            </div>
        `;
        answerEl.querySelector('div.whitespace-pre-wrap').textContent = answer;
        answerEl.querySelector('span:last-of-type').textContent = nowStr();
        const answerCol = answerEl.querySelector('.ai-answer-col') || answerEl.lastElementChild;
        if (answerCol && Array.isArray(followUps) && followUps.length > 0) {
            appendFollowUpsToAnswer(answerCol, followUps);
        }
        placeholder.replaceWith(answerEl);
        scrollToBottom();
    }

    function addStructuredError(info, fallback) {
        info = info || null;
        const title = (info && info.title) ? info.title : 'Request failed';
        const body  = (info && info.body)  ? info.body  : (fallback || 'Something went wrong.');
        const action= (info && info.action && info.action.label && info.action.url) ? info.action : null;

        const wrap = document.createElement('div');
        wrap.className = 'flex items-start gap-3 fade-in';
        wrap.innerHTML = `
            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-red-400 to-rose-500 flex items-center justify-center flex-shrink-0 shadow-md">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
            </div>
            <div class="flex-1 max-w-[85%]">
                <div class="px-4 py-3 rounded-2xl rounded-tl-md bg-red-50 border border-red-200/70 shadow-sm">
                    <p class="text-sm font-bold text-red-800 mb-1"></p>
                    <p class="text-sm text-red-700 leading-relaxed whitespace-pre-wrap"></p>
                    ${action ? `<a href="${escapeAttr(action.url)}" class="mt-3 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-red-500 hover:bg-red-600 text-white text-xs font-semibold shadow-sm transition">${escapeHtml(action.label)}
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M10.5 6h7.5M12 14.25l3 3m0 0l3-3m-3 3V6m-9 12H6a2.25 2.25 0 01-2.25-2.25V8.25A2.25 2.25 0 016 6h1.5"/></svg>
                    </a>` : ''}
                </div>
            </div>
        `;
        wrap.querySelectorAll('p')[0].textContent = title;
        wrap.querySelectorAll('p')[1].textContent = body;
        chatMessages.appendChild(wrap);
        scrollToBottom();
    }

    function escapeHtml(str) {
        return String(str).replace(/[&<>"']/g, c => ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#39;'
        }[c]));
    }
    function escapeAttr(str) { return escapeHtml(str); }

    async function sendQuestion(question) {
        if (!question.trim()) return;
        sendBtn.disabled = true;
        statusBadge.textContent = 'Thinking...';
        statusBadge.className = 'text-[11px] font-medium text-purple-600';
        addUserMessage(question.trim());
        const placeholder = addAssistantPlaceholder();

        const body = new FormData();
        body.append(csrfName, csrfValue);
        body.append('question', question.trim());
        const docId = scopeSelect.value;
        if (docId) body.append('document_id', docId);

        try {
            const res = await fetch(<?= json_encode(site_url('/chat/ask')) ?>, {
                method: 'POST',
                body: body,
            });
            const data = await res.json();
            if (data && data.debug) {
                console.log('[RAG] Prompt trace:', data.debug);
            }
            if (data && data.success) {
                const fups = (data.follow_ups && Array.isArray(data.follow_ups)) ? data.follow_ups : [];
                replacePlaceholder(placeholder, data.answer || '(No answer received)', data.sources || [], fups);

                const sugWrap = document.getElementById('suggestedWrap');
                if (sugWrap && fups.length > 0) {
                    const pills = sugWrap.querySelector('.suggested-pills');
                    const label = sugWrap.querySelector('.suggested-label');
                    if (label) label.textContent = 'Suggested follow-ups';
                    if (pills) {
                        pills.innerHTML = '';
                        fups.slice(0, 4).forEach(function (q) {
                            if (typeof q !== 'string' || q.trim().length < 3) return;
                            const btn = document.createElement('button');
                            btn.type = 'button';
                            btn.className = 'suggestion-pill w-full text-left inline-flex items-start gap-2 px-3 py-2.5 rounded-xl text-xs font-medium bg-white text-slate-700 border border-slate-200 hover:bg-indigo-50 hover:text-indigo-800 hover:border-indigo-200 transition-all shadow-sm group';
                            btn.innerHTML =
                                '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-slate-500 group-hover:text-indigo-600 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">' +
                                '<path stroke-linecap="round" stroke-linejoin="round" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>' +
                                '<span class="break-words leading-snug">' + escapeHtml(q) + '</span>';
                            btn.addEventListener('click', function () { sendQuestion(q); });
                            pills.appendChild(btn);
                        });
                    }
                }

                if (data && data.debug && data.debug.chunks > 0) {
                    statusBadge.textContent = 'Used ' + data.debug.chunks + ' passage(s) · ' + data.debug.docs + ' doc(s)';
                    statusBadge.className = 'text-[11px] font-medium text-emerald-600';
                } else if (data && data.debug && data.debug.chunks === 0) {
                    statusBadge.textContent = 'Warning: 0 passages retrieved';
                    statusBadge.className = 'text-[11px] font-medium text-amber-600';
                } else {
                    statusBadge.textContent = 'Ready';
                    statusBadge.className = 'text-[11px] font-medium text-slate-400';
                }
            } else {
                if (data && data.debug) console.warn('[RAG] failed trace:', data.debug);
                replacePlaceholder(placeholder, '', []);
                addStructuredError(data && data.errorInfo ? data.errorInfo : null, data && data.error ? data.error : 'Something went wrong while generating the answer.');
                statusBadge.textContent = 'Error';
                statusBadge.className = 'text-[11px] font-medium text-red-600';
            }
        } catch (err) {
            replacePlaceholder(placeholder, '', []);
            addStructuredError({ title: 'Network error', body: 'Network error: ' + (err.message || String(err)) });
            statusBadge.textContent = 'Error';
            statusBadge.className = 'text-[11px] font-medium text-red-600';
        } finally {
            sendBtn.disabled = false;
            questionInput.value = '';
            autoResize(questionInput);
            questionInput.focus();
        }
    }

    chatForm.addEventListener('submit', function (e) {
        e.preventDefault();
        sendQuestion(questionInput.value);
    });

    questionInput.addEventListener('keydown', function (e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendQuestion(questionInput.value);
        }
    });

    document.querySelectorAll('.suggestion-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            sendQuestion(btn.textContent.trim());
        });
    });

    clearChatBtn.addEventListener('click', function () {
        if (!confirm('Clear the conversation?')) return;
        const welcome = chatMessages.firstElementChild;
        chatMessages.innerHTML = '';
        if (welcome) chatMessages.appendChild(welcome);
    });

    if (dismissBannerBtn) {
        dismissBannerBtn.addEventListener('click', function () {
            const banner = dismissBannerBtn.closest('.glass');
            if (banner) banner.style.display = 'none';
        });
    }
    if (dismissInfoBtn) {
        dismissInfoBtn.addEventListener('click', function () {
            const banner = dismissInfoBtn.closest('.glass');
            if (banner) banner.style.display = 'none';
        });
    }
})();
</script>
