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

<?php
$total = $total ?? 0;
$attemptId = (int)($attempt['id'] ?? 0);
$quizTitle = (string)($setting['title'] ?? 'Quiz');
$passingPct = (float)($setting['passing_score_pct'] ?? 70);
?>

<?= $this->section('title') ?><?= esc($quizTitle) ?> · Take Quiz<?= $this->endSection() ?>
<?= $this->section('pageTitle') ?><?= esc($quizTitle) ?><?= $this->endSection() ?>

<?= $this->section('content') ?>
<div class="space-y-5">
    <div class="glass rounded-2xl border border-slate-200/60 p-5 flex flex-wrap items-center justify-between gap-4">
        <div class="flex flex-wrap items-center gap-4">
            <div class="px-3 py-1.5 rounded-xl bg-violet-50 text-violet-700 text-[12px] font-semibold">
                Question <span id="qIndexHuman" class="font-bold">1</span>/<?= $total ?>
            </div>
            <div class="w-56 h-2 rounded-full bg-slate-200 overflow-hidden">
                <div id="progressBar" class="h-full bg-gradient-to-r from-violet-500 to-fuchsia-500 transition-all" style="width: <?= $total > 0 ? number_format(100 / $total, 2) : 0 ?>%"></div>
            </div>
            <div class="px-3 py-1.5 rounded-xl bg-slate-100 text-slate-700 text-[12px] font-semibold">
                Passing: <span class="font-bold"><?= number_format($passingPct, 0) ?>%</span>
            </div>
        </div>
        <div class="flex items-center gap-3">
            <div id="timerPanel" class="flex items-center gap-2 px-4 py-2 rounded-xl border-2 border-slate-300 bg-white">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-slate-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                <span id="timerText" class="text-lg font-bold text-slate-800 tabular-nums">00:00</span>
            </div>
            <button id="btnNext" class="px-4 py-2 rounded-xl bg-gradient-to-r from-violet-600 to-fuchsia-600 text-white text-sm font-semibold shadow-md shadow-violet-500/20 hover:shadow-lg transition disabled:opacity-50 disabled:cursor-not-allowed">
                Next →
            </button>
        </div>
    </div>

    <div id="questionArea" class="glass rounded-2xl border border-slate-200/60 p-6 md:p-8 min-h-[360px]">
        <?php if ($total === 0): ?>
            <div class="text-center py-12 text-sm text-slate-500">No questions available.</div>
        <?php else: ?>
            <?php foreach ($questions as $idx => $q): ?>
                <div class="question-card hidden fade-in" data-idx="<?= (int)$idx ?>" data-id="<?= (int)$q['id'] ?>" data-type="<?= esc($q['type']) ?>" data-timer="<?= (int)$q['timer_seconds'] ?>">
                    <div class="flex flex-wrap items-start justify-between gap-3 mb-5">
                        <div>
                            <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-semibold <?= $q['type'] === 'fill_up' ? 'bg-sky-100 text-sky-700' : 'bg-indigo-100 text-indigo-700' ?>">
                                <?= $q['type'] === 'fill_up' ? 'Fill in the Blank' : 'Multiple Choice' ?>
                            </span>
                        </div>
                    </div>
                    <p class="text-lg md:text-xl font-semibold text-slate-800 leading-relaxed mb-6"><?= esc($q['text']) ?></p>

                    <?php if ($q['type'] === 'multiple_choice' && !empty($q['options'])): ?>
                        <div class="space-y-2.5" id="options_<?= (int)$idx ?>">
                            <?php foreach ($q['options'] as $o):
                                $letter = strtoupper(trim((string)($o['letter'] ?? '')));
                                $text = trim((string)($o['text'] ?? ''));
                            ?>
                                <label class="mc-option block items-start gap-3 px-4 py-3.5 rounded-xl border-2 border-slate-200 bg-white hover:border-violet-300 hover:bg-violet-50/40 cursor-pointer transition select-none">
                                    <div class="flex items-start gap-3">
                                        <span class="inline-flex items-center justify-center w-7 h-7 rounded-lg text-[12px] font-bold bg-slate-100 text-slate-700 border border-slate-200 flex-shrink-0 mc-letter"><?= $letter ?></span>
                                        <span class="flex-1 text-sm text-slate-700 leading-relaxed pt-1 mc-text"><?= esc($text) ?></span>
                                        <input type="radio" name="ans_<?= (int)$idx ?>" value="<?= esc($letter) ?>" class="hidden mc-radio">
                                    </div>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="mb-2">
                            <label class="block text-xs font-semibold text-slate-600 mb-1.5">Your Answer</label>
                            <textarea id="fillAns_<?= (int)$idx ?>" rows="3" class="w-full rounded-xl border-2 border-slate-300 bg-white px-4 py-3 text-sm focus:ring-2 focus:ring-violet-500/30 focus:border-violet-500 outline-none transition" placeholder="Type a concise answer here..."></textarea>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<script>
(function () {
    const attemptId = <?= json_encode($attemptId) ?>;
    const total = <?= (int)$total ?>;
    const btnNext = document.getElementById('btnNext');
    const timerText = document.getElementById('timerText');
    const timerPanel = document.getElementById('timerPanel');
    const indexHuman = document.getElementById('qIndexHuman');
    const progress = document.getElementById('progressBar');
    const cards = Array.from(document.querySelectorAll('.question-card'));
    if (cards.length === 0 || total === 0) return;

    let idx = 0;
    let questionStartTs = 0;
    let timerInterval = null;
    let remaining = 0;
    let submitting = false;

    function showCurrent() {
        cards.forEach((c, i) => c.classList.toggle('hidden', i !== idx));
        indexHuman.textContent = String(idx + 1);
        progress.style.width = (((idx + 1) / total) * 100).toFixed(2) + '%';
        const card = cards[idx];
        const timer = parseInt(card.dataset.timer || '60', 10);
        remaining = timer;
        questionStartTs = Math.floor(Date.now() / 1000);
        updateTimerText();
        if (timerInterval) clearInterval(timerInterval);
        timerInterval = setInterval(tick, 1000);
        btnNext.textContent = (idx === total - 1) ? 'Finish Quiz ✓' : 'Next →';
        // reset selected UI styling
        cards[idx].querySelectorAll('.mc-option').forEach(el => {
            el.classList.remove('border-violet-500', 'bg-violet-100/60');
            el.classList.add('border-slate-200', 'bg-white');
            const letterEl = el.querySelector('.mc-letter');
            if (letterEl) {
                letterEl.classList.remove('bg-violet-600', 'text-white');
                letterEl.classList.add('bg-slate-100', 'text-slate-700');
            }
        });
    }

    function updateTimerText() {
        const r = Math.max(0, remaining);
        const mm = String(Math.floor(r / 60)).padStart(2, '0');
        const ss = String(r % 60).padStart(2, '0');
        timerText.textContent = mm + ':' + ss;
        if (r <= 10) {
            timerPanel.classList.remove('border-slate-300', 'border-rose-400', 'border-amber-400');
            timerPanel.classList.add('border-rose-400');
            timerPanel.classList.add('animate-pulse');
        } else if (r <= 25) {
            timerPanel.classList.remove('border-slate-300', 'border-rose-400', 'border-amber-400');
            timerPanel.classList.add('border-amber-400');
            timerPanel.classList.remove('animate-pulse');
        } else {
            timerPanel.classList.remove('border-rose-400', 'border-amber-400', 'animate-pulse');
            timerPanel.classList.add('border-slate-300');
        }
    }

    function tick() {
        remaining--;
        if (remaining <= 0) {
            if (timerInterval) clearInterval(timerInterval);
            autoNextOnTimeout();
        } else {
            updateTimerText();
        }
    }

    function getAnswerFromUI() {
        const card = cards[idx];
        const type = card.dataset.type;
        if (type === 'multiple_choice') {
            const checked = card.querySelector('.mc-radio:checked');
            return checked ? (checked.value || '') : '';
        } else {
            const ta = card.querySelector('textarea[id^="fillAns_"]');
            return ta ? (ta.value || '') : '';
        }
    }

    function submitCurrentAnswer(forceTimedOut) {
        if (submitting) return Promise.resolve();
        submitting = true;
        const card = cards[idx];
        const qid = parseInt(card.dataset.id, 10);
        const answer = getAnswerFromUI();
        const timedOut = !!forceTimedOut;
        const spent = Math.min(parseInt(card.dataset.timer || '60', 10), Math.floor(Date.now() / 1000) - questionStartTs);
        const fd = new FormData();
        fd.append('question_id', String(qid));
        fd.append('answer', answer);
        fd.append('time_spent', String(Math.max(0, spent)));
        fd.append('timed_out', timedOut ? '1' : '0');
        return fetch('<?= site_url('/agent/quizzes/answer') ?>', {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: fd,
        }).then(r => r.json()).finally(() => { submitting = false; });
    }

    function autoNextOnTimeout() {
        submitCurrentAnswer(true).finally(() => {
            if (idx + 1 < total) { idx++; showCurrent(); }
            else finishQuiz();
        });
    }

    async function onNextClick() {
        if (submitting) return;
        btnNext.disabled = true;
        try { await submitCurrentAnswer(false); } catch (e) {}
        if (idx + 1 < total) { idx++; showCurrent(); }
        else { finishQuiz(); }
        btnNext.disabled = false;
    }

    function finishQuiz() {
        if (timerInterval) clearInterval(timerInterval);
        btnNext.disabled = true;
        btnNext.textContent = 'Saving...';
        const fd = new FormData();
        fd.append('attempt_id', String(attemptId));
        fetch('<?= site_url('/agent/quizzes/finish') ?>', {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: fd,
        }).then(r => r.json()).then(res => {
            if (res && res.redirect) { window.location.href = res.redirect; }
            else btnNext.textContent = 'Done ✓';
        }).catch(() => { btnNext.textContent = 'Retry finish'; btnNext.disabled = false; });
    }

    // bind radio styling + selection
    cards.forEach((c, i) => {
        c.querySelectorAll('.mc-option').forEach(labelEl => {
            labelEl.addEventListener('click', function (e) {
                const radio = labelEl.querySelector('.mc-radio');
                if (!radio) return;
                c.querySelectorAll('.mc-option').forEach(x => {
                    x.classList.remove('border-violet-500', 'bg-violet-100/60');
                    x.classList.add('border-slate-200', 'bg-white');
                    const ltr = x.querySelector('.mc-letter');
                    if (ltr) {
                        ltr.classList.remove('bg-violet-600', 'text-white');
                        ltr.classList.add('bg-slate-100', 'text-slate-700');
                    }
                });
                radio.checked = true;
                labelEl.classList.remove('border-slate-200', 'bg-white');
                labelEl.classList.add('border-violet-500', 'bg-violet-100/60');
                const ltr = labelEl.querySelector('.mc-letter');
                if (ltr) {
                    ltr.classList.remove('bg-slate-100', 'text-slate-700');
                    ltr.classList.add('bg-violet-600', 'text-white');
                }
            });
        });
    });

    btnNext.addEventListener('click', onNextClick);

    // Prevent accidental leave
    window.addEventListener('beforeunload', function (e) {
        if (submitting) return;
        e.preventDefault();
        e.returnValue = '';
    });

    showCurrent();
})();
</script>
<?= $this->endSection() ?>
