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

<?php
$callId = (int)($call['id'] ?? 0);
$score = $call['score_pct'] !== null ? (float)$call['score_pct'] : null;
$threshold = $call['pass_threshold_pct'] !== null ? (float)$call['pass_threshold_pct'] : ($binding ? (float)($binding['pass_threshold_pct'] ?? 70) : 70);
$passed = $score !== null && $score >= $threshold;
$scored = $score !== null;
$durationSec = (int)($call['duration_seconds'] ?? 0);
$durStr = '';
if ($durationSec > 0) {
    $m = (int)($durationSec / 60);
    $s = $durationSec % 60;
    $durStr = $m . 'm ' . $s . 's';
}
$direction = ucfirst(strtolower(trim((string)($call['direction'] ?? 'outbound'))));
$phone = (string)($call['phone_number'] ?? '');
$transcript = (string)($call['transcript'] ?? '');
if (is_array(json_decode($transcript, true))) {
    $arr = json_decode($transcript, true);
    $parts = [];
    if (is_array($arr)) {
        foreach ($arr as $m) {
            if (is_array($m)) {
                $role = (string)($m['role'] ?? ($m['speaker'] ?? ''));
                $text = (string)($m['content'] ?? ($m['text'] ?? ($m['message'] ?? '')));
                if ($text !== '') {
                    $parts[] = ($role !== '' ? strtoupper($role) . ': ' : '') . $text;
                }
            }
        }
    }
    $transcriptText = implode("\n", $parts);
} else {
    $transcriptText = $transcript;
}
$summary = (string)($call['call_summary'] ?? '');
$recordingUrl = (string)($call['recording_url'] ?? '');
$bindingName = $binding ? (string)($binding['name'] ?? 'Unknown Assistant') : 'Unknown';
$vapiName = $binding ? (string)($binding['vapi_name'] ?? '') : '';
$startedStr = !empty($call['started_at']) ? date('F j, Y H:i', strtotime($call['started_at'])) : '';
?>

<?= $this->section('title') ?>Call Review · <?= esc($bindingName) ?><?= $this->endSection() ?>
<?= $this->section('pageTitle') ?>Mock Call Review<?= $this->endSection() ?>

<?= $this->section('content') ?>
<div class="space-y-6">
    <div class="glass rounded-2xl border border-slate-200/60 overflow-hidden">
        <?php if ($scored): ?>
            <div class="px-6 py-5 bg-gradient-to-r <?= $passed ? 'from-emerald-50 to-teal-50 border-b border-emerald-100' : 'from-rose-50 to-amber-50 border-b border-rose-100' ?>">
        <?php else: ?>
            <div class="px-6 py-5 bg-gradient-to-r from-slate-50 to-slate-100 border-b border-slate-200">
        <?php endif; ?>
            <div class="flex flex-wrap items-start justify-between gap-5">
                <div>
                    <p class="text-[11px] font-semibold uppercase tracking-wider text-slate-500"><?= esc($bindingName) ?><?= $vapiName !== '' ? ' · ' . esc($vapiName) : '' ?></p>
                    <h2 class="text-2xl md:text-3xl font-extrabold mt-1 <?= $scored ? ($passed ? 'text-emerald-700' : 'text-rose-700') : 'text-slate-700' ?>">
                        <?php if (!$scored): ?>
                            ⏳ Scoring In Progress
                        <?php elseif ($passed): ?>
                            🎉 You Passed!
                        <?php else: ?>
                            Keep Practicing — Below Passing Score
                        <?php endif; ?>
                    </h2>
                    <p class="text-sm text-slate-600 mt-1">
                        <?= $startedStr !== '' ? $startedStr . ' · ' : '' ?><?= $direction ?><?= $phone !== '' ? ' · ' . esc($phone) : '' ?><?= $durStr !== '' ? ' · ' . $durStr : '' ?>
                    </p>
                    <?php if (!empty($docNames)): ?>
                        <p class="text-[11px] text-slate-500 mt-1.5" title="<?= esc(implode(', ', $docNames)) ?>">
                            <span class="font-semibold text-slate-600">Basis Docs:</span> <?= esc(implode(', ', array_slice(array_values($docNames), 0, 3))) ?><?= count($docNames) > 3 ? ' (+' . (count($docNames) - 3) . ' more)' : '' ?>
                        </p>
                    <?php endif; ?>
                </div>
                <div class="text-right">
                    <?php if ($scored): ?>
                        <div class="text-5xl md:text-6xl font-extrabold tabular-nums <?= $score >= 70 ? 'text-emerald-600' : ($score >= 50 ? 'text-amber-600' : 'text-rose-600') ?>"><?= number_format($score, 0) ?><span class="text-2xl align-top text-slate-400">%</span></div>
                        <div class="flex flex-wrap justify-end gap-2 mt-2">
                            <div class="px-3 py-1 rounded-lg bg-slate-100 text-slate-700 text-[11px] font-semibold">Passing <?= number_format($threshold, 0) ?>%</div>
                            <?php if ($recordingUrl !== ''): ?>
                                <a href="<?= esc($recordingUrl) ?>" target="_blank" rel="noopener" class="px-3 py-1 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 text-[11px] font-semibold inline-flex items-center gap-1 transition">
                                    🎧 Recording
                                </a>
                            <?php endif; ?>
                        </div>
                    <?php else: ?>
                        <div class="text-5xl md:text-6xl font-extrabold tabular-nums text-slate-400">—<span class="text-2xl align-top text-slate-400">%</span></div>
                        <div class="mt-2 text-[11px] text-slate-500">Score pending…</div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <?php if ($scored && !empty($call['ai_feedback'])): ?>
            <div class="p-5 md:p-6 border-b border-slate-200/70 bg-gradient-to-br from-violet-50/70 to-fuchsia-50/60">
                <div class="flex items-start gap-3">
                    <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-violet-500 to-fuchsia-500 text-white flex items-center justify-center shadow-md shadow-violet-500/20 flex-shrink-0">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-[20px] h-[20px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" /></svg>
                    </div>
                    <div class="flex-1 min-w-0">
                        <p class="text-xs font-semibold text-violet-700 uppercase tracking-wider mb-2">AI Coach · Your Personalized Feedback</p>
                        <div class="text-[13.5px] text-slate-700 whitespace-pre-line leading-relaxed"><?= nl2br(esc((string)$call['ai_feedback'])) ?></div>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="p-5 md:p-6 flex flex-wrap items-center gap-3">
            <a href="<?= site_url('/agent/mock-calls') ?>" 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">
                ← Back to Mock Calls
            </a>
            <?php if ($bindingId = (int)($binding['id'] ?? 0)): ?>
                <a href="<?= site_url('/agent/mock-call-logs/' . $bindingId) ?>" 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">
                    View All Call Logs
                </a>
            <?php endif; ?>
            <button type="button" onclick="rescoreCall(<?= $callId ?>)" class="inline-flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-violet-600 to-fuchsia-600 text-white text-sm font-semibold rounded-xl shadow-md shadow-violet-500/20 hover:shadow-lg hover:-translate-y-0.5 active:translate-y-0 transition-all">
                <span id="rescore-spinner" class="hidden inline-block w-4 h-4 border-2 border-violet-200 border-t-white rounded-full animate-spin"></span>
                <span id="rescore-text">Re-score (AI)</span>
            </button>
        </div>
    </div>

    <?php if ($scored && !empty($breakdown)): ?>
        <div>
            <h3 class="text-sm font-semibold text-slate-700 uppercase tracking-wider mb-3">10-Category Score Breakdown · 100 Points</h3>
            <div class="glass rounded-2xl border border-slate-200/60 overflow-hidden">
                <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-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider w-1/3">Category</th>
                                <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Performance</th>
                                <th class="px-6 py-3.5 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider w-24">Points</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100">
                            <?php
                            $totalAwarded = 0;
                            $totalMax = 0;
                            foreach ($breakdown as $row):
                                $name = (string)($row['category'] ?? '');
                                $awarded = (float)($row['points_awarded'] ?? 0);
                                $max = (float)($row['points_max'] ?? 0);
                                $rationale = (string)($row['rationale'] ?? '');
                                $totalAwarded += $awarded;
                                $totalMax += $max;
                                $pct = $max > 0 ? (int)round(($awarded / $max) * 100) : 0;
                                $barClass = $pct >= 70 ? 'bg-emerald-500' : ($pct >= 50 ? 'bg-amber-500' : 'bg-rose-500');
                            ?>
                                <tr class="hover:bg-slate-50/50 transition align-top">
                                    <td class="px-6 py-4">
                                        <div class="flex flex-col gap-2">
                                            <div>
                                                <p class="text-sm font-semibold text-slate-800"><?= esc($name) ?></p>
                                                <?php if ($rationale !== ''): ?>
                                                    <p class="text-[11.5px] text-slate-500 mt-1 leading-relaxed"><?= esc($rationale) ?></p>
                                                <?php endif; ?>
                                            </div>
                                            <?php
                                            $quote      = trim((string)($row['transcript_quote'] ?? ''));
                                            $bestAnswer = trim((string)($row['best_answer_from_docs'] ?? ''));
                                            ?>
                                            <?php if ($quote !== '' || $bestAnswer !== ''): ?>
                                            <div class="flex flex-col gap-2 mt-1">
                                                <?php if ($quote !== ''): ?>
                                                    <details class="group rounded-xl border border-slate-200/80 bg-slate-50/60 overflow-hidden">
                                                        <summary class="cursor-pointer list-none px-3 py-2 flex items-center gap-2 hover:bg-slate-100/60 transition">
                                                            <div class="w-6 h-6 rounded-md bg-sky-100 text-sky-700 flex items-center justify-center flex-shrink-0">
                                                                <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="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z" /></svg>
                                                            </div>
                                                            <span class="text-[11px] font-bold uppercase tracking-wider text-slate-600 flex-1">Exact Transcript Evidence</span>
                                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5 text-slate-500 group-open:rotate-180 transition" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" /></svg>
                                                        </summary>
                                                        <div class="px-3 pb-3 pt-1 border-t border-slate-200/80 bg-white/60">
                                                            <blockquote class="text-[12px] font-mono leading-relaxed text-slate-700 whitespace-pre-wrap border-l-2 border-sky-400 pl-3 italic"><?= esc($quote) ?></blockquote>
                                                        </div>
                                                    </details>
                                                <?php endif; ?>
                                                <?php if ($bestAnswer !== ''): ?>
                                                    <details class="group rounded-xl border border-emerald-200/70 bg-gradient-to-br from-emerald-50/80 to-teal-50/40 overflow-hidden" open>
                                                        <summary class="cursor-pointer list-none px-3 py-2 flex items-center gap-2 hover:bg-emerald-50 transition">
                                                            <div class="w-6 h-6 rounded-md bg-emerald-100 text-emerald-700 flex items-center justify-center flex-shrink-0">
                                                                <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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                                                            </div>
                                                            <span class="text-[11px] font-bold uppercase tracking-wider text-emerald-700 flex-1">Best Answer · Trained Docs</span>
                                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5 text-emerald-600 group-open:rotate-180 transition" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" /></svg>
                                                        </summary>
                                                        <div class="px-3 pb-3 pt-1 border-t border-emerald-200/60 bg-white/80">
                                                            <div class="text-[12.5px] text-slate-700 leading-relaxed whitespace-pre-line"><?= nl2br(esc($bestAnswer)) ?></div>
                                                        </div>
                                                    </details>
                                                <?php endif; ?>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="w-full">
                                            <div class="w-full bg-slate-100 rounded-full h-2.5 overflow-hidden">
                                                <div class="h-2.5 rounded-full <?= $barClass ?> transition-all" style="width: <?= $pct ?>%"></div>
                                            </div>
                                            <div class="mt-1.5 text-[10px] text-slate-500 font-semibold"><?= $pct ?>% of max</div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 text-right">
                                        <span class="text-sm font-bold tabular-nums <?= $pct >= 70 ? 'text-emerald-600' : ($pct >= 50 ? 'text-amber-600' : 'text-rose-600') ?>"><?= number_format($awarded, 1) ?></span>
                                        <span class="text-xs text-slate-400 tabular-nums">/<?= number_format($max, 1) ?></span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            <tr class="bg-slate-50/80 font-semibold">
                                <td class="px-6 py-4 text-sm text-slate-800">TOTAL</td>
                                <td class="px-6 py-4">
                                    <?php $totalPct = $totalMax > 0 ? (int)round(($totalAwarded / $totalMax) * 100) : 0; ?>
                                    <div class="w-full">
                                        <div class="w-full bg-slate-200 rounded-full h-2.5 overflow-hidden">
                                            <div class="h-2.5 rounded-full bg-gradient-to-r from-violet-500 to-fuchsia-500" style="width: <?= $totalPct ?>%"></div>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-right">
                                    <span class="text-base font-extrabold tabular-nums text-slate-800"><?= number_format($totalAwarded, 1) ?></span>
                                    <span class="text-sm text-slate-500 tabular-nums">/<?= number_format($totalMax, 1) ?></span>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <div>
        <h3 class="text-sm font-semibold text-slate-700 uppercase tracking-wider mb-3">Call Transcript</h3>
        <div class="glass rounded-2xl border border-slate-200/60 p-5">
            <?php if ($summary !== ''): ?>
                <div class="mb-4 pb-4 border-b border-slate-200/70">
                    <p class="text-[11px] font-semibold uppercase tracking-wide text-slate-500 mb-1.5">AI Summary</p>
                    <p class="text-sm text-slate-700 leading-relaxed"><?= nl2br(esc($summary)) ?></p>
                </div>
            <?php endif; ?>
            <?php if ($transcriptText !== ''): ?>
                <div class="max-h-96 overflow-y-auto scrollbar-thin pr-2">
                    <pre class="text-[12.5px] text-slate-700 whitespace-pre-wrap leading-relaxed font-mono bg-slate-50/60 rounded-xl p-4 border border-slate-200/50"><?= esc($transcriptText) ?></pre>
                </div>
            <?php else: ?>
                <div class="text-center py-8">
                    <div class="mx-auto w-12 h-12 rounded-xl bg-slate-100 flex items-center justify-center mb-3">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M8 10h.01M12 10h.01M16 10h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" /></svg>
                    </div>
                    <p class="text-sm text-slate-500">No transcript available for this call.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
async function rescoreCall(callId) {
    const spinner = document.getElementById('rescore-spinner');
    const textEl = document.getElementById('rescore-text');
    spinner.classList.remove('hidden');
    textEl.textContent = 'Re-scoring...';

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

    try {
        const resp = await fetch('<?= site_url('/agent/mock-call-score/') ?>' + callId, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: fd
        });
        const data = await resp.json();
        if (data.ok || data.already_scored) {
            window.location.reload();
        } else {
            textEl.textContent = 'Failed — retry';
        }
    } catch (e) {
        textEl.textContent = 'Network error';
    } finally {
        spinner.classList.add('hidden');
    }
}
</script>
<?= $this->endSection() ?>
