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

<?php
$questions = $attempt['questions'] ?? [];
$total = (int)($attempt['total_questions'] ?? 0);
$correct = (int)($attempt['correct_count'] ?? 0);
$answered = (int)($attempt['answered_count'] ?? 0);
$score = (float)($attempt['score_pct'] ?? 0);
$passed = !empty($attempt['passed']);
$timerS = (int)($setting['question_timer_seconds'] ?? 0);
$passing = (float)($setting['passing_score_pct'] ?? 70);
$startTs = !empty($attempt['started_at']) ? strtotime($attempt['started_at']) : 0;
$endTs = !empty($attempt['completed_at']) ? strtotime($attempt['completed_at']) : 0;
$durStr = ($startTs && $endTs) ? (int)(($endTs - $startTs) / 60) . 'm ' . (($endTs - $startTs) % 60) . 's' : '—';
$attemptNo = (int)($attempt['attempt_no'] ?? 1);
?>

<?= $this->section('title') ?>Result · <?= esc($setting['title'] ?? 'Quiz') ?><?= $this->endSection() ?>
<?= $this->section('pageTitle') ?>Quiz Result<?= $this->endSection() ?>

<?= $this->section('content') ?>
<div class="space-y-6">
    <div class="glass rounded-2xl border border-slate-200/60 overflow-hidden">
        <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' ?>">
            <div class="flex flex-wrap items-start justify-between gap-5">
                <div>
                    <p class="text-[11px] font-semibold uppercase tracking-wider text-slate-500">Attempt #<?= $attemptNo ?> · <?= esc($setting['title'] ?? 'Quiz') ?></p>
                    <h2 class="text-2xl md:text-3xl font-extrabold mt-1 <?= $passed ? 'text-emerald-700' : 'text-rose-700' ?>">
                        <?= $passed ? '🎉 You Passed!' : 'Keep Practicing — Below Passing Score' ?>
                    </h2>
                    <p class="text-sm text-slate-600 mt-1">Completed in <?= $durStr ?> · <?= !empty($attempt['completed_at']) ? date('F j, Y H:i', $endTs) : '' ?></p>
                </div>
                <div class="text-right">
                    <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, 1) ?><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"><?= $correct ?>/<?= $total ?> correct</div>
                        <div class="px-3 py-1 rounded-lg bg-slate-100 text-slate-700 text-[11px] font-semibold"><?= $answered ?> answered</div>
                        <div class="px-3 py-1 rounded-lg bg-slate-100 text-slate-700 text-[11px] font-semibold"><?= $timerS ?>s timer/q</div>
                        <div class="px-3 py-1 rounded-lg bg-slate-100 text-slate-700 text-[11px] font-semibold">Passing <?= number_format($passing, 0) ?>%</div>
                    </div>
                </div>
            </div>
        </div>

        <?php if (!empty($attempt['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($attempt['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/quizzes/start/' . (int)($attempt['quiz_setting_id'] ?? 0)) ?>"
               data-quiz-start-btn
               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">
                <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="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="quiz-start-label">Try Again (New Questions)</span>
            </a>
            <a href="<?= site_url('/agent/quizzes') ?>" 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">
                ← All Quizzes
            </a>
            <div class="ml-auto text-[11px] text-slate-500">Every retry pulls fresh unique AI-generated questions from the trained documents.</div>
        </div>
    </div>

    <div>
        <h3 class="text-sm font-semibold text-slate-700 uppercase tracking-wider mb-3">Answer Breakdown</h3>
        <div class="space-y-4">
            <?php foreach ($questions as $i => $q):
                $type = ($q['question_type'] ?? '') === 'fill_up' ? 'Fill-Up' : 'Multiple Choice';
                $typeClass = ($q['question_type'] ?? '') === 'fill_up' ? 'bg-sky-100 text-sky-700' : 'bg-indigo-100 text-indigo-700';
                $opts = $q['options_arr'] ?? [];
                $userAns = trim((string)($q['user_answer'] ?? ''));
                $correctAns = trim((string)($q['correct_answer'] ?? ''));
                $isCorrect = !empty($q['is_correct']);
                $answered = !empty($q['answered']);
                $timedOut = !empty($q['timed_out']);
                $spent = (int)($q['time_spent_seconds'] ?? 0);
            ?>
                <div class="glass rounded-2xl border border-slate-200/60 p-5">
                    <div class="flex flex-wrap items-start justify-between gap-3 mb-3">
                        <div class="flex items-center gap-2 flex-wrap">
                            <span class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-slate-900 text-white text-xs font-bold"><?= $i + 1 ?></span>
                            <span class="inline-flex px-2 py-0.5 rounded-lg text-[10px] font-semibold <?= $typeClass ?>"><?= $type ?></span>
                            <?php if ($spent > 0): ?>
                                <span class="inline-flex px-2 py-0.5 rounded-lg text-[10px] font-semibold bg-slate-100 text-slate-600">⏱ <?= $spent ?>s</span>
                            <?php endif; ?>
                            <?php if ($timedOut): ?>
                                <span class="inline-flex px-2 py-0.5 rounded-lg text-[10px] font-semibold bg-amber-100 text-amber-700">⏰ Timed out</span>
                            <?php elseif (!$answered): ?>
                                <span class="inline-flex px-2 py-0.5 rounded-lg text-[10px] font-semibold bg-slate-100 text-slate-600">Skipped</span>
                            <?php endif; ?>
                        </div>
                        <div>
                            <?php if ($answered || $timedOut): ?>
                                <?php if ($isCorrect): ?>
                                    <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-emerald-100 text-emerald-700">
                                        <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.5"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" /></svg>
                                        Correct
                                    </span>
                                <?php else: ?>
                                    <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-rose-100 text-rose-700">
                                        <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.5"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" /></svg>
                                        Incorrect
                                    </span>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                    <p class="text-sm font-semibold text-slate-800 leading-relaxed mb-3"><?= esc($q['question_text']) ?></p>

                    <?php if ($type === 'Multiple Choice' && !empty($opts)): ?>
                        <div class="space-y-1.5 mb-3">
                            <?php foreach ($opts as $o):
                                $letter = strtoupper(trim((string)($o['letter'] ?? '')));
                                $text = trim((string)($o['text'] ?? ''));
                                $correctLetter = strtoupper($correctAns);
                                $userLetter = strtoupper($userAns);
                                $isCorrectOpt = ($letter === $correctLetter);
                                $userPicked = ($answered && $letter === $userLetter);
                                $rowClass = 'px-3 py-2 rounded-xl border text-sm ';
                                if ($userPicked && $isCorrectOpt) $rowClass .= 'border-emerald-300 bg-emerald-50';
                                elseif ($userPicked) $rowClass .= 'border-rose-300 bg-rose-50';
                                elseif ($isCorrectOpt) $rowClass .= 'border-violet-300 bg-violet-50';
                                else $rowClass .= 'border-slate-200 bg-slate-50/40';
                            ?>
                                <div class="<?= $rowClass ?> flex items-start gap-2">
                                    <span class="inline-flex items-center justify-center w-6 h-6 rounded-lg text-[11px] font-bold <?= $isCorrectOpt ? 'bg-violet-500 text-white' : 'bg-white text-slate-700 border border-slate-200' ?> flex-shrink-0 mt-0.5"><?= $letter ?></span>
                                    <span class="flex-1 text-slate-700"><?= esc($text) ?></span>
                                    <?php if ($userPicked && !$isCorrectOpt): ?>
                                        <span class="text-[10px] font-semibold text-rose-600 mt-1">your pick</span>
                                    <?php elseif ($isCorrectOpt): ?>
                                        <span class="text-[10px] font-semibold text-violet-600 mt-1">answer</span>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3 mb-3">
                            <div class="px-3 py-2.5 rounded-xl border border-violet-200 bg-violet-50/60">
                                <p class="text-[10px] font-semibold text-violet-700 uppercase tracking-wide mb-1">✔ Correct Answer</p>
                                <p class="text-sm text-slate-800 font-semibold"><?= esc($correctAns) ?></p>
                            </div>
                            <div class="px-3 py-2.5 rounded-xl border <?= $isCorrect ? 'border-emerald-200 bg-emerald-50/60' : 'border-rose-200 bg-rose-50/60' ?>">
                                <p class="text-[10px] font-semibold uppercase tracking-wide mb-1 <?= $isCorrect ? 'text-emerald-700' : 'text-rose-700' ?>">🗣 Your Answer</p>
                                <p class="text-sm text-slate-800 font-semibold"><?= $userAns !== '' ? esc($userAns) : '<span class="italic text-slate-400 font-normal">(no answer)</span>' ?></p>
                            </div>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($q['ai_rationale'])): ?>
                        <div class="px-3 py-2 rounded-xl bg-slate-50 border border-slate-200 text-[11.5px] text-slate-600 leading-relaxed">
                            <span class="font-semibold text-slate-700">Why: </span><?= esc($q['ai_rationale']) ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>
<script>
(function () {
  const SPINNER = '<svg class="w-4 h-4 animate-spin" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-85" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path></svg>';
  document.querySelectorAll('a[data-quiz-start-btn]').forEach(function (btn) {
    btn.addEventListener('click', function (e) {
      if (btn.dataset.loading === '1') { e.preventDefault(); return; }
      btn.dataset.loading = '1';
      e.preventDefault();
      const href = btn.getAttribute('href') || '#';
      const label = btn.querySelector('.quiz-start-label');
      btn.classList.add('opacity-80', 'cursor-wait', 'pointer-events-none');
      btn.style.transform = 'none';
      btn.style.boxShadow = 'none';
      btn.innerHTML = SPINNER + ' <span class="quiz-start-label inline-flex">' + (label ? 'Generating questions…' : 'Generating…') + '</span>';
      setTimeout(function () { window.location.href = href; }, 30);
    });
  });
})();
</script>
<?= $this->endSection() ?>
