<div class="space-y-6">
    <div class="flex flex-wrap items-center justify-between gap-3">
        <div>
            <p class="text-sm text-slate-500">Configure Vapi API credentials, assistant bindings, and scoring thresholds.</p>
        </div>
        <div class="flex flex-wrap gap-2">
            <a href="<?= site_url('/admin/vapi/score-history') ?>" class="inline-flex items-center gap-2 px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm font-semibold rounded-xl shadow-sm border border-slate-200 transition">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" /></svg>
                Call Score History
            </a>
        </div>
    </div>

    <div class="glass rounded-2xl shadow-sm border border-slate-200/60 p-6">
        <div class="flex items-start gap-3 mb-4">
            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-sky-500 to-indigo-500 text-white flex items-center justify-center shadow-md shadow-sky-500/20 flex-shrink-0">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" /></svg>
            </div>
            <div class="flex-1">
                <h3 class="text-base font-semibold text-slate-800">Vapi API Key</h3>
                <p class="text-[11px] text-slate-500 mt-0.5">Paste your Vapi API key. Get one from <a href="https://dashboard.vapi.ai/settings/api-keys" target="_blank" class="underline text-indigo-600">dashboard.vapi.ai</a>.</p>
            </div>
        </div>
        <form method="post" action="<?= site_url('/admin/vapi-settings') ?>" class="flex flex-wrap items-stretch gap-3">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="save_key">
            <div class="flex-1 min-w-[260px]">
                <label class="block text-xs font-semibold text-slate-600 mb-1.5">Vapi API Key</label>
                <input type="text" id="vapiKeyInput" name="api_key" value="<?= esc($apiKey) ?>" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-mono focus:ring-2 focus:ring-sky-500/30 focus:border-sky-500 outline-none transition" placeholder="vapi_...">
            </div>
            <div class="flex flex-col justify-end gap-1.5">
                <label class="block text-xs font-semibold text-slate-600 mb-1.5">&nbsp;</label>
                <div class="flex items-center gap-2">
                    <button type="submit" class="px-5 py-2.5 rounded-xl text-sm font-semibold text-white bg-gradient-to-r from-sky-600 to-indigo-600 shadow-md hover:shadow-lg transition">
                        Save Key
                    </button>
                    <button type="button" id="btnTestVapi" class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-semibold bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 transition">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" /></svg>
                        Test Connection
                    </button>
                </div>
            </div>
        </form>
        <div id="vapiTestResult" class="mt-3 hidden">
            <span class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-[11px] font-semibold" id="vapiTestBadge"></span>
            <span class="text-[11px] text-slate-600 ml-2" id="vapiTestMsg"></span>
        </div>
    </div>

    <div class="glass rounded-2xl shadow-sm border border-slate-200/60 p-6">
        <form method="post" action="<?= site_url('/admin/vapi-settings') ?>" class="mb-5">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="refresh_assistants">
            <button type="submit" class="w-full inline-flex items-center justify-center gap-3 px-6 py-4 bg-gradient-to-r from-violet-600 via-indigo-600 to-sky-600 text-white text-sm font-bold rounded-2xl shadow-xl shadow-indigo-500/25 hover:shadow-2xl hover:-translate-y-0.5 active:translate-y-0 transition-all">
                <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="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" /></svg>
                Pull Latest Assistants from Vapi
            </button>
        </form>

        <?php if (empty($bindings)): ?>
            <div class="text-center py-12">
                <div class="w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center mx-auto mb-3">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" /></svg>
                </div>
                <p class="text-sm font-medium text-slate-600">No assistants loaded yet.</p>
                <p class="text-[11px] text-slate-500 mt-1">Click the button above to pull assistants from Vapi.</p>
            </div>
        <?php else: ?>
            <form method="post" action="<?= site_url('/admin/vapi-settings') ?>">
                <?= csrf_field() ?>
                <input type="hidden" name="action" value="save_bindings">
                <div class="space-y-4">
                    <?php foreach ($bindings as $b):
                        $bid = (int)$b['id'];
                        $selDocIds = !empty($b['selected_doc_ids']) ? (array)json_decode($b['selected_doc_ids'], true) : [];
                        if (!is_array($selDocIds)) $selDocIds = [];
                        $selDocIds = array_values(array_filter(array_map('intval', $selDocIds)));
                        $selAgentIds = !empty($b['assigned_agent_ids']) ? (array)json_decode($b['assigned_agent_ids'], true) : [];
                        if (!is_array($selAgentIds)) $selAgentIds = [];
                        $selAgentIds = array_values(array_filter(array_map('intval', $selAgentIds)));
                    ?>
                        <input type="hidden" name="binding_ids[]" value="<?= $bid ?>">
                        <div class="border border-slate-200/80 rounded-2xl bg-gradient-to-br from-white/80 to-slate-50/60 overflow-hidden">
                            <div class="flex flex-wrap items-center gap-3 px-5 py-3.5 border-b border-slate-200/80 bg-slate-50/50">
                                <span class="inline-flex items-center px-2.5 py-1 rounded-lg bg-slate-900 text-white text-[11px] font-mono font-semibold">
                                    <?= esc($b['vapi_assistant_id']) ?>
                                </span>
                                <span class="text-[11px] text-slate-500 italic"><?= esc($b['vapi_name'] ?? '') ?></span>
                                <div class="ml-auto flex items-center gap-2">
                                    <label class="inline-flex items-center gap-2 cursor-pointer">
                                        <input type="checkbox" name="active_<?= $bid ?>" value="1" <?= !empty($b['is_active']) ? 'checked' : '' ?> class="w-4 h-4 text-emerald-600 rounded">
                                        <span class="text-xs font-semibold text-slate-700">Active</span>
                                    </label>
                                    <a href="<?= site_url('/admin/vapi/delete-binding/' . $bid) ?>" onclick="return confirm('Delete this binding?');" class="p-1.5 rounded-lg text-red-500 hover:bg-red-50 transition" title="Delete binding">
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><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>
                                    </a>
                                </div>
                            </div>

                            <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4 p-5">
                                <div>
                                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Nickname</label>
                                    <input type="text" name="name_<?= $bid ?>" value="<?= esc($b['name'] ?? '') ?>" class="w-full rounded-xl border border-slate-300 bg-white px-3.5 py-2.5 text-sm focus:ring-2 focus:ring-violet-500/30 focus:border-violet-500 outline-none transition" placeholder="Display name...">
                                </div>
                                <div>
                                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Vapi Assistant URL (optional)</label>
                                    <input type="text" name="url_<?= $bid ?>" value="<?= esc($b['url'] ?? '') ?>" class="w-full rounded-xl border border-slate-300 bg-white px-3.5 py-2.5 text-sm focus:ring-2 focus:ring-violet-500/30 focus:border-violet-500 outline-none transition" placeholder="https://...">
                                </div>
                                <div>
                                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Pass Threshold %</label>
                                    <input type="number" name="pass_<?= $bid ?>" min="0" max="100" value="<?= (int)($b['pass_threshold_pct'] ?? 70) ?>" class="w-full rounded-xl border border-slate-300 bg-white px-3.5 py-2.5 text-sm focus:ring-2 focus:ring-violet-500/30 focus:border-violet-500 outline-none transition">
                                </div>
                                <div>
                                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Stats</label>
                                    <div class="flex flex-wrap gap-2 pt-2.5">
                                        <span class="inline-flex items-center px-2.5 py-1 rounded-lg bg-slate-100 text-slate-700 text-[11px] font-semibold">
                                            <?= (int)($b['call_count'] ?? 0) ?> calls
                                        </span>
                                        <span class="inline-flex items-center px-2.5 py-1 rounded-lg bg-indigo-50 text-indigo-700 text-[11px] font-semibold">
                                            <?= (int)($b['assigned_agent_count'] ?? 0) ?> agents
                                        </span>
                                    </div>
                                </div>
                            </div>

                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 px-5 pb-5">
                                <div>
                                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">
                                        Trained Documents
                                        <span class="text-[10px] text-slate-400 font-normal ml-1">(<?= count($selDocIds) ?> selected)</span>
                                    </label>
                                    <div class="rounded-xl border border-slate-300 bg-white max-h-56 overflow-y-auto scrollbar-thin">
                                        <?php if (empty($trainedDocs)): ?>
                                            <div class="p-4 text-center text-[11px] text-slate-500">No trained documents.</div>
                                        <?php else: ?>
                                            <?php foreach ($trainedDocs as $d):
                                                $did = (int)$d['id'];
                                                $checked = in_array($did, $selDocIds, true);
                                            ?>
                                                <label class="flex items-start gap-2.5 px-3 py-2 border-b border-slate-100 last:border-b-0 hover:bg-slate-50 transition cursor-pointer">
                                                    <input type="checkbox" name="docs_<?= $bid ?>[]" value="<?= $did ?>" <?= $checked ? 'checked' : '' ?> class="mt-0.5 w-4 h-4 text-violet-600 rounded">
                                                    <div class="flex-1 min-w-0">
                                                        <span class="text-[12px] font-medium text-slate-800 truncate block"><?= esc($d['title']) ?></span>
                                                        <?php if (!empty($d['category_name'])): ?>
                                                            <span class="text-[10px] text-slate-500"><?= esc($d['category_name']) ?> · <?= (int)($d['chunk_count'] ?? 0) ?> chunks</span>
                                                        <?php endif; ?>
                                                    </div>
                                                </label>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div>
                                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">
                                        Assigned Agents
                                        <span class="text-[10px] text-slate-400 font-normal ml-1">(<?= count($selAgentIds) ?> selected)</span>
                                    </label>
                                    <div class="rounded-xl border border-slate-300 bg-white max-h-56 overflow-y-auto scrollbar-thin">
                                        <?php if (empty($agentUsers)): ?>
                                            <div class="p-4 text-center text-[11px] text-slate-500">No agents defined.</div>
                                        <?php else: ?>
                                            <?php foreach ($agentUsers as $u):
                                                $uid = (int)$u['id'];
                                                $checked = in_array($uid, $selAgentIds, true);
                                            ?>
                                                <label class="flex items-start gap-2.5 px-3 py-2 border-b border-slate-100 last:border-b-0 hover:bg-slate-50 transition cursor-pointer">
                                                    <input type="checkbox" name="agents_<?= $bid ?>[]" value="<?= $uid ?>" <?= $checked ? 'checked' : '' ?> class="mt-0.5 w-4 h-4 text-violet-600 rounded">
                                                    <div class="flex-1 min-w-0">
                                                        <span class="text-[12px] font-medium text-slate-800 truncate block"><?= esc($u['name'] ?? $u['username'] ?? 'User') ?></span>
                                                        <span class="text-[10px] text-slate-500"><?= esc($u['email'] ?? '') ?></span>
                                                    </div>
                                                </label>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="mt-5 flex justify-end">
                    <button type="submit" class="px-6 py-2.5 rounded-xl text-sm font-semibold text-white bg-gradient-to-r from-violet-600 to-fuchsia-600 shadow-md hover:shadow-lg transition">
                        Save Bindings
                    </button>
                </div>
            </form>
        <?php endif; ?>
    </div>

    <div class="glass rounded-2xl shadow-sm border border-slate-200/60 p-6">
        <div class="flex items-start gap-3 mb-4">
            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-emerald-500 to-teal-500 text-white flex items-center justify-center shadow-md shadow-emerald-500/20 flex-shrink-0">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z" /></svg>
            </div>
            <div class="flex-1">
                <h3 class="text-base font-semibold text-slate-800">100-Point Call Scorecard</h3>
                <p class="text-[11px] text-slate-500 mt-0.5">Each Vapi call is scored against the following 10 categories against the selected training documents.</p>
            </div>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="bg-slate-50/70 border-b border-slate-200/60">
                        <th class="px-4 py-2.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">#</th>
                        <th class="px-4 py-2.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Category</th>
                        <th class="px-4 py-2.5 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider">Points</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php
                    $scorecard = [
                        ['Research relevance', 15],
                        ['Identity and opener', 10],
                        ['Observation accuracy', 15],
                        ['Homeowner-to-business bridge', 10],
                        ['Diagnostic question', 10],
                        ['Listening and control', 10],
                        ['Positioning', 10],
                        ['Objection handling', 10],
                        ['Booking', 10],
                        ['Compliance and CRM', 5],
                    ];
                    foreach ($scorecard as $idx => [$cat, $pts]):
                    ?>
                        <tr class="hover:bg-slate-50/50 transition">
                            <td class="px-4 py-2.5 text-[11px] text-slate-500 font-semibold w-10"><?= $idx + 1 ?></td>
                            <td class="px-4 py-2.5 text-sm text-slate-800 font-medium"><?= esc($cat) ?></td>
                            <td class="px-4 py-2.5 text-right text-sm font-bold text-emerald-700 w-24"><?= $pts ?></td>
                        </tr>
                    <?php endforeach; ?>
                    <tr class="bg-slate-50/80">
                        <td class="px-4 py-3 text-xs font-bold text-slate-700 uppercase tracking-wider" colspan="2">Total</td>
                        <td class="px-4 py-3 text-right text-base font-extrabold text-slate-900">100</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
(function () {
    const btn = document.getElementById('btnTestVapi');
    const keyInput = document.getElementById('vapiKeyInput');
    const resultWrap = document.getElementById('vapiTestResult');
    const badge = document.getElementById('vapiTestBadge');
    const msg = document.getElementById('vapiTestMsg');

    function setResult(ok, text, countText) {
        resultWrap.classList.remove('hidden');
        badge.className = 'inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-[11px] font-semibold ' +
            (ok ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700');
        badge.textContent = ok ? '✓ Connected' : '✗ Failed';
        let msgText = text;
        if (ok && countText !== '' && countText !== null && countText !== undefined) {
            msgText += ' — ' + countText;
        }
        msg.textContent = msgText;
    }

    btn?.addEventListener('click', async () => {
        const key = (keyInput?.value || '').trim();
        const body = new FormData();
        body.append('api_key', key);
        body.append('use_saved', key === '' ? '1' : '0');
        const csrfName = '<?= csrf_token() ?>';
        const csrfHash = '<?= csrf_hash() ?>';
        body.append(csrfName, csrfHash);

        btn.disabled = true;
        btn.classList.add('opacity-60', 'cursor-not-allowed');
        resultWrap.classList.add('hidden');
        try {
            const resp = await fetch('<?= site_url('/admin/vapi/test-connection') ?>', {
                method: 'POST',
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
                body: body,
                credentials: 'same-origin',
            });
            let data;
            try { data = await resp.json(); } catch (e) { data = { ok: false, msg: 'Bad response from server.' }; }
            const ok = !!data.ok;
            const c = data.count;
            const countStr = (c !== null && c !== undefined) ? c + ' assistant(s) found' : '';
            setResult(ok, (data.msg || (ok ? 'Success.' : 'Unknown error.')), countStr);
        } catch (e) {
            setResult(false, 'Network error: ' + e.message, null);
        } finally {
            btn.disabled = false;
            btn.classList.remove('opacity-60', 'cursor-not-allowed');
        }
    });
})();
</script>
