<?= $this->extend('layout/app') ?>

<?= $this->section('title') ?>Mock Vapi Calls<?= $this->endSection() ?>
<?= $this->section('pageTitle') ?>Mock Vapi Calls<?= $this->endSection() ?>

<?= $this->section('content') ?>
<div class="space-y-6">
    <div class="flex flex-wrap items-center justify-between gap-3">
        <p class="text-sm text-slate-500">Practice with Vapi AI-powered mock calls. Click the call link to start a conversation with the AI assistant, then sync the calls and review your performance.</p>
        <a href="<?= site_url('/agent/mock-call-logs') ?>" 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="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" /></svg>
            All Call Logs
        </a>
    </div>

    <?php if (empty($bindings)): ?>
        <div class="glass rounded-2xl border border-slate-200/60 p-16 text-center">
            <div class="mx-auto w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center mb-4">
                <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="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" /></svg>
            </div>
            <?php if (!empty($user['role']) && $user['role'] === 'admin'): ?>
                <p class="text-sm font-medium text-slate-600">No Vapi assistants are configured yet. Create and assign assistants in <a href="<?= esc(site_url('/admin/vapi-settings')) ?>" class="text-violet-600 font-semibold underline">Vapi Settings</a>.</p>
            <?php else: ?>
                <p class="text-sm font-medium text-slate-600">No Vapi assistants are assigned to you yet. Ask your admin to configure one in AI Assistant settings.</p>
            <?php endif; ?>
        </div>
    <?php else: ?>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
            <?php foreach ($bindings as $item):
                $binding = $item['binding'];
                $id = (int)$item['id'];
                $totalCalls = (int)($item['total_calls'] ?? 0);
                $avgScore = $item['avg_score'];
                $threshold = (int)($binding['pass_threshold_pct'] ?? 70);
                $docCount = count($item['selected_doc_ids'] ?? []);
                $url = (string)($binding['url'] ?? '');
                $vapiName = (string)($binding['vapi_name'] ?? '');
            ?>
                <div class="glass rounded-2xl border border-slate-200/60 shadow-sm overflow-hidden hover:shadow-md transition-all">
                    <div class="p-5">
                        <div class="flex flex-wrap items-start justify-between gap-3 mb-4">
                            <div class="flex flex-col">
                                <span class="inline-flex items-center gap-2 mb-1">
                                    <h3 class="text-lg font-bold text-slate-800"><?= esc($binding['name'] ?? 'Unnamed Assistant') ?></h3>
                                </span>
                                <?php if ($vapiName !== ''): ?>
                                    <p class="text-xs text-slate-500 mb-1"><?= esc($vapiName) ?></p>
                                <?php endif; ?>
                                <?php if ($url !== ''): ?>
                                    <a href="<?= esc($url) ?>" target="_blank" rel="noopener" class="text-xs text-blue-600 hover:text-blue-700 font-medium inline-flex items-center gap-1 break-all">
                                        <?= esc($url) ?>
                                        <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" /></svg>
                                    </a>
                                <?php endif; ?>
                                <?php if (!empty($item['is_admin_view'])): ?>
                                    <?php
                                        $aNames = !empty($item['assigned_agent_names']) ? array_values($item['assigned_agent_names']) : [];
                                    ?>
                                    <?php if (!empty($aNames)): ?>
                                        <div class="mt-2 flex flex-wrap gap-1">
                                            <?php foreach ($aNames as $aname): ?>
                                                <span class="inline-flex items-center px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-100 text-sky-700 border border-sky-200">👤 <?= esc($aname) ?></span>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php else: ?>
                                        <span class="mt-2 inline-flex items-center px-2 py-0.5 rounded-md text-[10px] font-semibold bg-amber-100 text-amber-700 border border-amber-200">⚠ No agents assigned</span>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="mb-4">
                            <a href="<?= esc($url) ?>" target="_blank" rel="noopener" class="inline-flex items-center gap-2 w-full justify-center px-4 py-2.5 bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-sm font-semibold rounded-xl shadow-md shadow-blue-500/20 hover:shadow-lg hover:-translate-y-0.5 active:translate-y-0 transition-all">
                                <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="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" /></svg>
                                Open Call Link
                            </a>
                        </div>

                        <div class="grid grid-cols-4 gap-3 mb-4">
                            <div class="bg-slate-50 rounded-xl p-2.5 text-center">
                                <p class="text-[10px] font-semibold text-slate-500 uppercase tracking-wide">Threshold</p>
                                <p class="text-sm font-bold text-slate-800 mt-0.5"><?= $threshold ?>%</p>
                            </div>
                            <div class="bg-slate-50 rounded-xl p-2.5 text-center">
                                <p class="text-[10px] font-semibold text-slate-500 uppercase tracking-wide">Docs</p>
                                <p class="text-sm font-bold text-slate-800 mt-0.5"><?= $docCount ?></p>
                            </div>
                            <div class="bg-slate-50 rounded-xl p-2.5 text-center">
                                <p class="text-[10px] font-semibold text-slate-500 uppercase tracking-wide">Calls</p>
                                <p class="text-sm font-bold text-slate-800 mt-0.5"><?= $totalCalls ?></p>
                            </div>
                            <div class="bg-slate-50 rounded-xl p-2.5 text-center">
                                <p class="text-[10px] font-semibold text-slate-500 uppercase tracking-wide">Avg Score</p>
                                <p class="text-sm font-bold mt-0.5 <?= $avgScore !== null ? ((float)$avgScore >= $threshold ? 'text-emerald-600' : 'text-rose-600') : 'text-slate-400' ?>"><?= $avgScore !== null ? number_format((float)$avgScore, 1) . '%' : '—' ?></p>
                            </div>
                        </div>

                        <?php if (!empty($item['doc_names'])): ?>
                            <p class="text-[11px] text-slate-500 mb-4" title="<?= esc(implode(', ', $item['doc_names'])) ?>">
                                <span class="font-semibold text-slate-600">Basis Docs:</span> <?= esc(implode(', ', array_slice($item['doc_names'], 0, 3))) ?><?= count($item['doc_names']) > 3 ? ' (+' . (count($item['doc_names']) - 3) . ' more)' : '' ?>
                            </p>
                        <?php endif; ?>

                        <div class="flex flex-wrap items-center gap-2">
                            <a href="<?= site_url('/agent/mock-call-logs/' . $id) ?>" class="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-sm font-semibold bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 transition">
                                View Call Logs →
                            </a>
                            <button type="button" id="sync-<?= $id ?>" onclick="syncCalls(<?= $id ?>)" class="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-sm font-semibold bg-violet-50 text-violet-700 hover:bg-violet-100 border border-violet-200 transition">
                                <span id="sync-<?= $id ?>-spinner" class="hidden inline-block w-3.5 h-3.5 border-2 border-violet-300 border-t-violet-600 rounded-full animate-spin"></span>
                                <span id="sync-<?= $id ?>-icon">
                                    <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="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>
                                <span id="sync-<?= $id ?>-text">Sync Calls</span>
                            </button>
                        </div>
                        <div id="sync-<?= $id ?>-result" class="mt-2 text-xs"></div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<script>
async function syncCalls(bindingId) {
    const btn = document.getElementById('sync-' + bindingId);
    const spinner = document.getElementById('sync-' + bindingId + '-spinner');
    const iconEl = document.getElementById('sync-' + bindingId + '-icon');
    const textEl = document.getElementById('sync-' + bindingId + '-text');
    const resultEl = document.getElementById('sync-' + bindingId + '-result');

    btn.disabled = true;
    spinner.classList.remove('hidden');
    iconEl.classList.add('hidden');
    textEl.textContent = 'Syncing...';
    resultEl.textContent = '';
    resultEl.className = 'mt-2 text-xs text-slate-500';

    const fd = new FormData();
    fd.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');

    try {
        const resp = await fetch('<?= site_url('/agent/mock-calls/sync/') ?>' + bindingId, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: fd
        });
        const data = await resp.json();
        if (data.ok) {
            resultEl.innerHTML = '<span class="text-emerald-600 font-semibold">✓ ' + (data.msg || 'Sync complete.') + '</span>';
            setTimeout(() => window.location.reload(), 1200);
        } else {
            resultEl.innerHTML = '<span class="text-rose-600 font-semibold">✗ ' + (data.error || data.msg || 'Sync failed.') + '</span>';
        }
    } catch (e) {
        resultEl.innerHTML = '<span class="text-rose-600 font-semibold">✗ Network error.</span>';
    } finally {
        btn.disabled = false;
        spinner.classList.add('hidden');
        iconEl.classList.remove('hidden');
        textEl.textContent = 'Sync Calls';
    }
}
</script>
<?= $this->endSection() ?>
