@php
    $hideNavbar = true;
@endphp

@extends('siswa.layout')

@section('content')

{{-- =================================================
     🔒 FULLSCREEN OVERLAY
================================================== --}}
<div
    id="fullscreen-overlay"
    class="fixed inset-0 z-50 bg-slate-900 text-white
           flex flex-col items-center justify-center space-y-6"
>
    <i data-lucide="monitor" class="w-16 h-16"></i>
    <h2 class="text-2xl font-bold">Quiz wajib fullscreen</h2>
    <p class="text-slate-300 text-center max-w-md">
        Klik tombol di bawah untuk memulai quiz dalam mode fullscreen.
        Jika keluar fullscreen atau berpindah aplikasi,
        quiz otomatis berakhir dan nilai menjadi <strong>0</strong>.
    </p>
    <button
        id="enter-fullscreen-btn"
        class="bg-teal-600 px-8 py-3 rounded-lg font-semibold hover:bg-teal-500 transition"
    >
        Masuk Fullscreen & Mulai Quiz
    </button>
</div>

{{-- =================================================
     ⏱️ TIMEOUT MODAL
================================================== --}}
<div id="timeoutModal" class="fixed inset-0 z-[9999] hidden items-center justify-center p-4"
     style="background: rgba(2,6,23,0.85); backdrop-filter: blur(8px);">
    <div class="timeout-card relative overflow-hidden rounded-3xl w-full max-w-md mx-auto text-center shadow-2xl">
        <div class="timeout-glow"></div>
        <div class="relative z-10 p-8 pb-6">
            <div class="timeout-icon-wrap mx-auto mb-5">
                <svg viewBox="0 0 64 64" class="timeout-svg" fill="none">
                    <circle cx="32" cy="32" r="28" stroke="rgba(239,68,68,0.3)" stroke-width="3"/>
                    <circle cx="32" cy="32" r="28" stroke="#ef4444" stroke-width="3"
                            stroke-dasharray="176" stroke-dashoffset="176"
                            class="timeout-ring" stroke-linecap="round"/>
                    <text x="32" y="38" text-anchor="middle" font-size="22" font-weight="800"
                          fill="#fff" font-family="system-ui">⏱</text>
                </svg>
            </div>
            <h2 class="timeout-title">Waktu Habis!</h2>
            <p class="timeout-sub">Jawaban kamu sedang diproses dan dikirim secara otomatis.</p>
            <div class="timeout-bar-wrap mt-6 mb-4">
                <div class="timeout-bar-track">
                    <div class="timeout-bar-fill" id="timeoutBarFill"></div>
                </div>
                <p class="timeout-bar-label">
                    Mengalihkan dalam <span id="timeoutCountdown">3</span> detik...
                </p>
            </div>
        </div>
    </div>
</div>

{{-- =================================================
     QUIZ WRAPPER
================================================== --}}
<div class="min-h-screen bg-gradient-to-br from-slate-50 to-blue-50 p-4">
    <div class="max-w-7xl mx-auto">

        {{-- HEADER --}}
        <div class="lg:col-span-12 mb-6 md:mb-8">
            <div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-6 md:p-8 space-y-5">
                <div>
                    <h1 class="text-2xl md:text-3xl font-bold text-slate-900 mb-2">
                        {{ $quiz->title }}
                    </h1>
                    <div class="flex flex-wrap items-center gap-3 text-sm text-slate-600">
                        <span class="inline-flex items-center gap-2 bg-blue-50 text-blue-700 px-3 py-1.5 rounded-full">
                            <i data-lucide="list-checks" class="w-4 h-4"></i>
                            {{ $questions->count() }} Soal
                        </span>
                        @if($duration)
                        <span class="inline-flex items-center gap-2 bg-red-50 text-red-700 px-3 py-1.5 rounded-full"
                              id="timer-badge">
                            <i data-lucide="clock" class="w-4 h-4"></i>
                            <span id="quiz-timer">00:00</span>
                        </span>
                        @endif
                        <span class="inline-flex items-center gap-2 bg-emerald-50 text-emerald-700 px-3 py-1.5 rounded-full">
                            <i data-lucide="target" class="w-4 h-4"></i>
                            Passing: {{ $quiz->passing_score }}%
                        </span>
                    </div>
                </div>
                <div>
                    <div class="flex justify-between items-center mb-2">
                        <span class="text-sm font-medium text-slate-700">Progress</span>
                        <span id="progress-percentage" class="text-sm font-bold text-blue-600">0%</span>
                    </div>
                    <div class="h-2.5 bg-slate-200 rounded-full overflow-hidden">
                        <div id="progress-bar" class="h-full bg-gradient-to-r from-blue-500 to-indigo-600 transition-all duration-500 rounded-full" style="width:0%"></div>
                    </div>
                    <div class="flex justify-between mt-1 text-xs text-slate-500">
                        <span><span id="answered-count">0</span>/{{ $questions->count() }} terjawab</span>
                        <span id="flagged-count" class="text-amber-500 font-medium">0 ditandai</span>
                    </div>
                </div>
            </div>
        </div>

        {{-- MAIN CONTENT --}}
        <div class="flex flex-col lg:flex-row gap-6">

            {{-- SIDEBAR KIRI --}}
            <div class="lg:w-1/4">
                <div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-5 h-full sticky top-6">
                    <div class="flex items-center justify-between mb-5 pb-4 border-b border-slate-100">
                        <h3 class="font-bold text-slate-800 flex items-center gap-2">
                            <i data-lucide="navigation" class="w-5 h-5 text-blue-600"></i>
                            Navigasi Soal
                        </h3>
                        <span class="text-xs font-medium bg-slate-100 text-slate-700 px-2.5 py-1 rounded-full">
                            <span id="sidebar-answered">0</span>/{{ $questions->count() }}
                        </span>
                    </div>

                    <div class="grid grid-cols-5 gap-3 mb-6" id="questionNav">
                        @foreach($questions as $i => $q)
                            <button type="button" data-index="{{ $i }}"
                                class="question-nav-btn w-12 h-12 rounded-xl border-2 border-slate-200 text-sm font-semibold
                                       transition-all duration-200 hover:scale-105 hover:shadow-sm
                                       relative group flex items-center justify-center nav-button-default">
                                {{ $i + 1 }}
                                <div class="absolute -top-8 left-1/2 -translate-x-1/2
                                            bg-slate-900 text-white text-xs px-2 py-1 rounded
                                            opacity-0 group-hover:opacity-100 transition-opacity
                                            whitespace-nowrap pointer-events-none z-10 shadow-lg">
                                    Soal {{ $i + 1 }}
                                </div>
                            </button>
                        @endforeach
                    </div>

                    <div class="mb-6 p-4 bg-slate-50 rounded-xl border border-slate-100">
                        <h4 class="text-sm font-semibold text-slate-700 mb-3 flex items-center gap-2">
                            <i data-lucide="info" class="w-4 h-4 text-slate-500"></i>
                            Keterangan Status
                        </h4>
                        <div class="space-y-2.5">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-2">
                                    <div class="w-3.5 h-3.5 rounded-full bg-blue-600 border-2 border-blue-600"></div>
                                    <span class="text-xs text-slate-600">Aktif</span>
                                </div>
                                <span class="text-xs font-medium text-slate-700" id="active-count">1</span>
                            </div>
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-2">
                                    <div class="w-3.5 h-3.5 rounded-full bg-emerald-500 border-2 border-emerald-500"></div>
                                    <span class="text-xs text-slate-600">Terjawab</span>
                                </div>
                                <span class="text-xs font-medium text-emerald-600" id="answered-status">0</span>
                            </div>
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-2">
                                    <div class="w-3.5 h-3.5 rounded-full bg-amber-400 border-2 border-amber-400"></div>
                                    <span class="text-xs text-slate-600">Ragu-ragu</span>
                                </div>
                                <span class="text-xs font-medium text-amber-600" id="flagged-status">0</span>
                            </div>
                        </div>
                    </div>

                    <div class="p-4 bg-amber-50 rounded-xl border border-amber-200">
                        <h4 class="text-sm font-semibold text-amber-800 mb-2 flex items-center gap-2">
                            <i data-lucide="flag" class="w-4 h-4"></i>
                            Ditandai Ragu
                        </h4>
                        <div id="flagged-list" class="min-h-[40px]">
                            <p class="text-xs text-amber-600 text-center py-2">Belum ada yang ditandai</p>
                        </div>
                    </div>

                    <button type="button" id="submitAllBtn"
                        class="w-full mt-6 px-4 py-3 rounded-xl
                               bg-gradient-to-r from-emerald-500 to-green-600
                               text-white font-bold hover:from-emerald-600 hover:to-green-700
                               hover:shadow-lg transition-all duration-200
                               flex items-center justify-center gap-2"
                        style="display: none;">
                        <i data-lucide="check-circle" class="w-5 h-5"></i>
                        <span>Semua Sudah Terjawab - Siap Kirim</span>
                    </button>
                </div>
            </div>

            {{-- KONTEN KANAN --}}
            <div class="lg:w-3/4 min-w-0">
                <div class="bg-white rounded-2xl shadow-lg border border-slate-200 overflow-hidden h-full">
                    <div class="border-b border-slate-100 p-6 bg-gradient-to-r from-slate-50 to-white">
                        <div class="flex justify-between items-center">
                            <div>
                                <span class="inline-flex items-center gap-2 px-4 py-2.5 rounded-full
                                             text-sm font-semibold bg-blue-100 text-blue-800 mb-2">
                                    <i data-lucide="help-circle" class="w-4 h-4"></i>
                                    Soal <span id="current-question">1</span> dari {{ $questions->count() }}
                                </span>
                                <p class="text-xs text-slate-500 mt-1">
                                    Pilih satu jawaban yang paling tepat dengan mengklik pilihan
                                </p>
                            </div>
                            <button type="button" id="flagBtn"
                                class="px-4 py-2.5 rounded-xl font-semibold transition-all duration-200
                                       flex items-center gap-2 border-2 border-amber-400
                                       text-amber-700 bg-amber-50 hover:bg-amber-100
                                       hover:border-amber-500 hover:shadow-sm flag-button">
                                <i data-lucide="flag" class="w-4 h-4"></i>
                                <span>Tandai Ragu</span>
                            </button>
                        </div>
                    </div>

                    {{-- FORM --}}
                    <form id="quiz-form" method="POST"
                          action="{{ route('siswa.quiz.submit', $quiz->id) }}"
                          autocomplete="off" class="p-6 md:p-8">
                        @csrf

                        <input type="hidden" name="fullscreen_violation"
                               id="fullscreen_violation" value="0">

                        {{-- Dummy answers agar selalu array meskipun tidak menjawab --}}
                        @foreach($questions as $question)
                            <input type="hidden"
                                   name="answers[{{ $question->id }}]"
                                   value=""
                                   class="dummy-answer-{{ $question->id }}">
                        @endforeach

                        {{-- SOAL --}}
                        @foreach($questions as $index => $question)
                            <div class="question {{ $index === 0 ? '' : 'hidden' }}"
                                 data-index="{{ $index }}"
                                 data-question-id="{{ $question->id }}">

                                <div class="mb-8">
                                    <h2 class="text-lg md:text-xl font-semibold text-slate-800
                                               mb-6 leading-relaxed break-words max-w-3xl">
                                        {{ $question->question }}
                                    </h2>

                                    @if(!empty($question->question_image))
                                        <div class="mb-8 max-w-3xl mx-auto">
                                            <div class="relative rounded-xl border-2 border-slate-200
                                                        overflow-hidden group cursor-zoom-in">
                                                <img src="{{ $question->question_image }}"
                                                     alt="Gambar Soal"
                                                     class="w-full max-w-2xl h-auto object-contain
                                                            max-h-[380px] mx-auto">
                                                <div class="absolute inset-0 bg-black/50 opacity-0
                                                            group-hover:opacity-100 transition-opacity
                                                            flex items-center justify-center">
                                                    <span class="text-white bg-white/20 backdrop-blur-sm
                                                                 px-4 py-2 rounded-lg flex items-center
                                                                 gap-2 text-sm">
                                                        <i data-lucide="zoom-in" class="w-4 h-4"></i>
                                                        Klik untuk memperbesar
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    @endif
                                </div>

                                <div class="space-y-3 max-w-3xl">
                                    @foreach($question->available_options as $opt)
                                        <div class="option-container">
                                            <input type="radio"
                                                   name="answers[{{ $question->id }}]"
                                                   value="{{ $opt['key'] }}"
                                                   id="q{{ $question->id }}_{{ $opt['key'] }}"
                                                   class="hidden option-input">
                                            <label for="q{{ $question->id }}_{{ $opt['key'] }}"
                                                class="flex items-center gap-4 p-4 md:p-5 border-2
                                                       border-slate-200 rounded-xl cursor-pointer
                                                       transition-all duration-200 hover:border-blue-400
                                                       hover:bg-blue-50 option-label">
                                                <div class="flex-shrink-0">
                                                    <div class="w-6 h-6 md:w-7 md:h-7 rounded-full
                                                                border-2 border-slate-300 flex items-center
                                                                justify-center transition-all duration-200
                                                                option-circle">
                                                        <div class="w-2.5 h-2.5 md:w-3 md:h-3 rounded-full
                                                                    bg-blue-600 opacity-0 transition-opacity
                                                                    duration-200 option-dot"></div>
                                                    </div>
                                                </div>
                                                <div class="flex-1">
                                                    <div class="flex items-start md:items-center gap-3 md:gap-4">
                                                        <span class="font-bold text-lg text-blue-600 min-w-[24px]">
                                                            {{ $opt['label'] }}.
                                                        </span>
                                                        <span class="text-slate-700 text-base leading-relaxed">
                                                            {{ $opt['value'] }}
                                                        </span>
                                                    </div>
                                                </div>
                                            </label>
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        @endforeach

                        {{-- NAVIGATION FOOTER --}}
                        <div class="mt-10 pt-6 border-t border-slate-200">
                            <div class="flex justify-between items-center">
                                <button type="button" id="prevBtn"
                                    class="px-5 py-2.5 md:px-6 md:py-3 rounded-xl border-2
                                           border-slate-300 text-slate-700 font-medium hover:bg-slate-50
                                           disabled:opacity-50 disabled:cursor-not-allowed
                                           transition-all duration-200 flex items-center gap-2 prev-button"
                                    disabled>
                                    <i data-lucide="chevron-left" class="w-4 h-4 md:w-5 md:h-5"></i>
                                    <span class="hidden md:inline">Sebelumnya</span>
                                </button>

                                <div class="flex items-center gap-3 md:gap-4">
                                    <button type="button" id="submitBtn"
                                        class="px-5 py-2.5 md:px-8 md:py-3 rounded-xl
                                               bg-gradient-to-r from-emerald-500 to-green-600
                                               text-black font-semibold shadow-md shadow-emerald-200
                                               hover:shadow-lg hover:shadow-emerald-300
                                               transition-all duration-200 hover:scale-105
                                               hidden flex items-center gap-2 submit-main-button">
                                        <i data-lucide="send" class="w-4 h-4 md:w-5 md:h-5"></i>
                                        <span>Kirim Jawaban</span>
                                    </button>

                                    <button type="button" id="nextBtn"
                                        class="px-5 py-2.5 md:px-8 md:py-3 rounded-xl
                                               bg-gradient-to-r from-blue-500 to-indigo-600
                                               text-black font-semibold hover:shadow-lg hover:shadow-blue-200
                                               transition-all duration-200 hover:scale-105
                                               flex items-center gap-2 next-button">
                                        <span>Selanjutnya</span>
                                        <i data-lucide="chevron-right" class="w-4 h-4 md:w-5 md:h-5"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

{{-- =================================================
     CSS
================================================== --}}
<style>
.nav-button-default  { background-color:white !important; border-color:#e2e8f0 !important; color:#334155 !important; }
.nav-button-active   { background-color:#2563eb !important; border-color:#2563eb !important; color:white !important; }
.nav-button-answered { background-color:#10b981 !important; border-color:#10b981 !important; color:white !important; }
.nav-button-flagged  { background-color:#fbbf24 !important; border-color:#fbbf24 !important; color:#78350f !important; }
.submit-main-button,.prev-button,.next-button,.flag-button { opacity:1 !important; visibility:visible !important; }
.option-container.selected .option-label   { border-color:#2563eb; background-color:#eff6ff; box-shadow:0 4px 12px rgba(37,99,235,.1); }
.option-container.selected .option-circle  { border-color:#2563eb !important; background-color:#dbeafe !important; }
.option-container.selected .option-dot     { opacity:1 !important; }
.question { animation:slideIn .3s ease-out; }
@keyframes slideIn { from{opacity:0; transform:translateX(20px)} to{opacity:1; transform:translateX(0)} }
#progress-bar { background:linear-gradient(90deg,#ef4444 0%,#f97316 25%,#22c55e 50%,#16a34a 75%,#15803d 100%); background-size:200% 100%; animation:bloodFlow 2s linear infinite; }
@keyframes bloodFlow { 0%{background-position:200% 0} 100%{background-position:-200% 0} }

.timeout-card{background:linear-gradient(145deg,#0f172a,#1e293b,#0f2744);border:1px solid rgba(239,68,68,.25);box-shadow:0 0 0 1px rgba(239,68,68,.1),0 30px 80px rgba(0,0,0,.6);}
.timeout-glow{position:absolute;width:260px;height:260px;border-radius:50%;background:radial-gradient(circle,rgba(239,68,68,.18) 0%,transparent 70%);top:-100px;left:50%;transform:translateX(-50%);animation:glowPulse 2s ease-in-out infinite;}
@keyframes glowPulse{0%,100%{opacity:.6;transform:translateX(-50%) scale(1)}50%{opacity:1;transform:translateX(-50%) scale(1.15)}}
.timeout-icon-wrap{width:80px;height:80px;position:relative;}
.timeout-svg{width:100%;height:100%;transform:rotate(-90deg);filter:drop-shadow(0 0 12px rgba(239,68,68,.5));}
.timeout-ring{animation:ringFill .8s ease-out .3s forwards;}
@keyframes ringFill{to{stroke-dashoffset:0}}
.timeout-title{font-family:'Syne','DM Sans',system-ui,sans-serif;font-size:1.75rem;font-weight:800;color:#fff;margin-bottom:.5rem;animation:fadeSlideUp .5s ease both .2s;}
.timeout-sub{font-size:.85rem;color:rgba(148,163,184,.9);line-height:1.6;animation:fadeSlideUp .5s ease both .35s;}
@keyframes fadeSlideUp{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}
.timeout-bar-wrap{animation:fadeSlideUp .5s ease both .5s;}
.timeout-bar-track{width:100%;height:6px;background:rgba(255,255,255,.08);border-radius:100px;overflow:hidden;margin-bottom:10px;}
.timeout-bar-fill{height:100%;width:100%;background:linear-gradient(90deg,#ef4444,#f97316);border-radius:100px;animation:drainBar 3s linear forwards;}
@keyframes drainBar{from{width:100%}to{width:0%}}
.timeout-bar-label{font-size:.78rem;color:rgba(148,163,184,.7);}
#timeoutCountdown{color:#f87171;font-weight:700;}
</style>

{{-- =================================================
     🔑 SAFE SUBMIT HELPER
================================================== --}}
<script>
// Guard global untuk mencegah double submit
window._quizSubmitted = false;

function safeSubmitForm(isViolation) {
    if (window._quizSubmitted) {
        console.log('Quiz sudah disubmit, skip...');
        return;
    }
    
    console.log('Submitting quiz...', isViolation ? 'violation' : 'normal');
    window._quizSubmitted = true;
    window.quizActive = false;
    window.submitted = true;
    window.isSubmitting = true;

    if (isViolation) {
        document.getElementById('fullscreen_violation').value = '1';
    }

    // Submit form, server akan redirect ke halaman result
    document.getElementById('quiz-form').submit();
}
</script>

{{-- =================================================
     🔒 LOCKDOWN SCRIPT
================================================== --}}
<script>
document.addEventListener('DOMContentLoaded', () => {

    const overlay = document.getElementById('fullscreen-overlay');
    const btn     = document.getElementById('enter-fullscreen-btn');
    const form    = document.getElementById('quiz-form');

    window.quizActive     = false;
    window.submitted      = false;
    window.isSubmitting   = false;
    window.violationCount = 0;

    // Modal pelanggaran pertama (warning)
    function showViolationWarning(reason, onContinue) {
        if (document.getElementById('viol-modal-1')) return;
        
        const modal = document.createElement('div');
        modal.id = 'viol-modal-1';
        modal.style.cssText = 'position:fixed;inset:0;z-index:99999;background:rgba(2,6,23,.9);backdrop-filter:blur(8px);display:flex;align-items:center;justify-content:center;padding:1rem;';
        modal.innerHTML = `
            <div style="background:linear-gradient(145deg,#1e293b,#0f172a);border:1px solid rgba(251,191,36,.3);border-radius:24px;padding:2rem;max-width:380px;width:100%;text-align:center;box-shadow:0 30px 80px rgba(0,0,0,.6);">
                <div style="width:64px;height:64px;margin:0 auto 1.25rem;background:rgba(251,191,36,.12);border:2px solid rgba(251,191,36,.35);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.8rem;">⚠️</div>
                <h3 style="font-size:1.25rem;font-weight:800;color:#fff;margin-bottom:.5rem;font-family:system-ui">Pelanggaran Pertama!</h3>
                <p style="font-size:.83rem;color:rgba(148,163,184,.9);line-height:1.6;margin-bottom:.35rem;">${reason}</p>
                <p style="font-size:.8rem;color:#fbbf24;font-weight:600;margin-bottom:1.5rem;">⚠️ Pelanggaran berikutnya: nilai otomatis <strong>0</strong>.</p>
                <button id="viol1Btn" style="width:100%;padding:.85rem;border-radius:12px;background:linear-gradient(135deg,#f59e0b,#d97706);color:#fff;font-weight:700;font-size:.95rem;border:none;cursor:pointer;font-family:system-ui;">Masuk Fullscreen Kembali</button>
            </div>
        `;
        document.body.appendChild(modal);
        
        document.getElementById('viol1Btn').addEventListener('click', async () => {
            try {
                await document.documentElement.requestFullscreen();
                modal.remove();
                window.quizActive = true;
                if (onContinue) onContinue();
            } catch {
                alert('Gagal masuk fullscreen. Silakan coba lagi.');
            }
        });
    }

    // Modal pelanggaran kedua (final, submit dengan nilai 0)
    function showFinalViolationAndSubmit(reason) {
        if (window._quizSubmitted) return;
        
        const modal = document.createElement('div');
        modal.style.cssText = 'position:fixed;inset:0;z-index:99999;background:rgba(2,6,23,.95);backdrop-filter:blur(8px);display:flex;align-items:center;justify-content:center;padding:1rem;';
        modal.innerHTML = `
            <div style="background:linear-gradient(145deg,#1e293b,#0f172a);border:1px solid rgba(239,68,68,.3);border-radius:24px;padding:2rem;max-width:380px;width:100%;text-align:center;box-shadow:0 30px 80px rgba(0,0,0,.6);">
                <div style="width:64px;height:64px;margin:0 auto 1.25rem;background:rgba(239,68,68,.12);border:2px solid rgba(239,68,68,.35);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.8rem;">🚫</div>
                <h3 style="font-size:1.25rem;font-weight:800;color:#fff;margin-bottom:.5rem;font-family:system-ui">Quiz Dihentikan!</h3>
                <p style="font-size:.83rem;color:rgba(148,163,184,.9);line-height:1.6;margin-bottom:.35rem;">${reason}</p>
                <p style="font-size:.85rem;color:#f87171;font-weight:700;margin-bottom:1.5rem;">Nilai kamu: <span style="font-size:1.5rem;">0</span></p>
                <div style="display:flex;align-items:center;justify-content:center;gap:8px;background:rgba(239,68,68,.08);border-radius:12px;padding:.75rem;font-size:.8rem;color:rgba(148,163,184,.8);">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                    Menyimpan jawaban...
                </div>
            </div>
        `;
        document.body.appendChild(modal);
        
        // Submit setelah 2 detik (biar modal sempat terbaca)
        setTimeout(() => safeSubmitForm(true), 2000);
    }

    function handleViolation(reason) {
        if (!window.quizActive || window._quizSubmitted || window.isSubmitting) return;

        window.violationCount++;

        if (window.violationCount === 1) {
            window.quizActive = false;
            showViolationWarning(reason, () => lucide.createIcons());
        } else {
            window.quizActive = false;
            showFinalViolationAndSubmit(reason);
        }
    }

    // Tombol mulai quiz
    btn.addEventListener('click', async () => {
        try {
            await document.documentElement.requestFullscreen();
            overlay.remove();
            window.quizActive = true;
            lucide.createIcons();
        } catch {
            alert('Fullscreen wajib diizinkan untuk memulai quiz.');
        }
    });

    // Event lockdown
    document.addEventListener('fullscreenchange', () => {
        if (!document.fullscreenElement && window.quizActive && !window._quizSubmitted) {
            handleViolation('Kamu keluar dari mode fullscreen.');
        }
    });

    document.addEventListener('visibilitychange', () => {
        if (document.hidden && window.quizActive && !window._quizSubmitted) {
            handleViolation('Kamu berpindah tab atau aplikasi.');
        }
    });

    window.addEventListener('blur', () => {
        if (window.quizActive && !window._quizSubmitted) {
            handleViolation('Kamu berpindah aplikasi.');
        }
    });

    window.addEventListener('beforeunload', (e) => {
        if (window.quizActive && !window._quizSubmitted) {
            e.preventDefault();
            e.returnValue = '';
            return '';
        }
    });

    form.addEventListener('submit', () => {
        window._quizSubmitted = true;
        window.quizActive = false;
        window.submitted = true;
        window.isSubmitting = true;
    });

    // Disable right click dan shortcuts
    document.addEventListener('contextmenu', e => e.preventDefault());
    document.addEventListener('keydown', (e) => {
        if (e.key === 'F12') e.preventDefault();
        if (e.ctrlKey && e.shiftKey && ['I','J'].includes(e.key)) e.preventDefault();
        if (e.ctrlKey && ['u','s'].includes(e.key)) e.preventDefault();
    });
});
</script>

{{-- =================================================
     ⏱️ TIMER - FIXED VERSION
     Auto submit meskipun tidak menjawab soal
================================================== --}}
@if($quiz->duration)
<script>
document.addEventListener('DOMContentLoaded', () => {
    // Waktu mulai dari database attempt
    const STARTED_AT = new Date("{{ $attempt->started_at ? \Carbon\Carbon::parse($attempt->started_at)->toIso8601String() : now()->toIso8601String() }}").getTime();
    const DURATION_SECONDS = {{ (int)$quiz->duration }} * 60;
    
    const timerEl = document.getElementById('quiz-timer');
    const timerBadge = document.getElementById('timer-badge');
    const timeoutModal = document.getElementById('timeoutModal');
    const timeoutCountdown = document.getElementById('timeoutCountdown');
    
    let timerDone = false;
    let timerInterval = null;

    function getRemainingSeconds() {
        const elapsedSeconds = Math.floor((Date.now() - STARTED_AT) / 1000);
        return Math.max(0, DURATION_SECONDS - elapsedSeconds);
    }

    function submitQuizTimeout() {
        if (timerDone || window._quizSubmitted) {
            console.log('Timer sudah selesai atau quiz sudah disubmit');
            return;
        }
        
        console.log('⏰ WAKTU HABIS - Auto submit quiz');
        timerDone = true;
        
        // Hentikan interval timer
        if (timerInterval) {
            clearInterval(timerInterval);
        }

        // Tampilkan modal timeout
        timeoutModal.classList.remove('hidden');
        timeoutModal.classList.add('flex');

        // Countdown 3,2,1
        let count = 3;
        const countdownInterval = setInterval(() => {
            count--;
            if (timeoutCountdown) {
                timeoutCountdown.textContent = count;
            }
            if (count <= 0) {
                clearInterval(countdownInterval);
            }
        }, 1000);

        // Submit form setelah 3 detik (biar modal sempat dilihat)
        setTimeout(() => {
            console.log('⏰ Mengirim jawaban ke server...');
            safeSubmitForm(false); // false = bukan violation
        }, 3200);
    }

    function updateTimer() {
        if (timerDone || window._quizSubmitted) return;

        const remaining = getRemainingSeconds();
        
        // Format menit:detik
        const minutes = Math.floor(remaining / 60);
        const seconds = remaining % 60;
        timerEl.textContent = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;

        // Visual warning
        if (remaining <= 300 && remaining > 60) { // 5 menit tersisa
            timerBadge?.classList.add('animate-pulse');
        } else if (remaining <= 60 && remaining > 0) { // 1 menit tersisa
            timerBadge?.classList.remove('bg-red-50', 'text-red-700');
            timerBadge?.classList.add('bg-red-600', 'text-white', 'animate-pulse');
        } else if (remaining <= 0) {
            // WAKTU HABIS!
            submitQuizTimeout();
        }
    }

    // Jalankan timer
    updateTimer(); // Langsung update
    timerInterval = setInterval(updateTimer, 1000);

    // Cleanup interval jika halaman di-unload
    window.addEventListener('beforeunload', () => {
        if (timerInterval) {
            clearInterval(timerInterval);
        }
    });
});
</script>
@endif

{{-- =================================================
     QUIZ NAVIGATION LOGIC
================================================== --}}
<script>
document.addEventListener('DOMContentLoaded', () => {

    const questions    = document.querySelectorAll('.question');
    const navBtns      = document.querySelectorAll('.question-nav-btn');
    const prevBtn      = document.getElementById('prevBtn');
    const nextBtn      = document.getElementById('nextBtn');
    const submitBtn    = document.getElementById('submitBtn');
    const submitAllBtn = document.getElementById('submitAllBtn');
    const flagBtn      = document.getElementById('flagBtn');

    const elProgressBar        = document.getElementById('progress-bar');
    const elProgressPercentage = document.getElementById('progress-percentage');
    const elAnsweredCount      = document.getElementById('answered-count');
    const elSidebarAnswered    = document.getElementById('sidebar-answered');
    const elFlaggedCount       = document.getElementById('flagged-count');
    const elCurrentQuestion    = document.getElementById('current-question');
    const elFlaggedList        = document.getElementById('flagged-list');
    const elAnsweredStatus     = document.getElementById('answered-status');
    const elFlaggedStatus      = document.getElementById('flagged-status');
    const elActiveCount        = document.getElementById('active-count');

    let current = 0;
    const total = questions.length;
    const flagged = Array(total).fill(false);
    const answered = Array(total).fill(false);

    function checkAllAnswered() {
        let answeredTotal = 0;
        let flaggedTotal = 0;
        
        questions.forEach((q, idx) => {
            const radios = q.querySelectorAll('input[type="radio"].option-input');
            const isAnswered = [...radios].some(r => r.checked);
            answered[idx] = isAnswered;
            if (isAnswered) answeredTotal++;
            if (flagged[idx]) flaggedTotal++;
        });

        const percentage = total > 0 ? Math.round((answeredTotal / total) * 100) : 0;
        if (elProgressBar) elProgressBar.style.width = `${percentage}%`;
        if (elProgressPercentage) elProgressPercentage.textContent = `${percentage}%`;
        if (elAnsweredCount) elAnsweredCount.textContent = answeredTotal;
        if (elSidebarAnswered) elSidebarAnswered.textContent = answeredTotal;
        if (elFlaggedCount) elFlaggedCount.textContent = `${flaggedTotal} ditandai`;
        if (elAnsweredStatus) elAnsweredStatus.textContent = answeredTotal;
        if (elFlaggedStatus) elFlaggedStatus.textContent = flaggedTotal;
        if (elActiveCount) elActiveCount.textContent = current + 1;

        const allAnswered = answeredTotal === total;
        const hasFlagged = flaggedTotal > 0;
        const isLast = current === total - 1;

        if (allAnswered && submitAllBtn) {
            submitAllBtn.style.display = 'flex';
            if (hasFlagged) {
                submitAllBtn.innerHTML = `<i data-lucide="alert-circle" class="w-5 h-5"></i><span>Masih ada ${flaggedTotal} ragu</span>`;
                submitAllBtn.disabled = true;
                submitAllBtn.style.opacity = '0.6';
            } else {
                submitAllBtn.innerHTML = `<i data-lucide="check-circle" class="w-5 h-5"></i><span>Semua Terjawab - Kirim</span>`;
                submitAllBtn.disabled = false;
                submitAllBtn.style.opacity = '1';
            }
        } else if (submitAllBtn) {
            submitAllBtn.style.display = 'none';
        }

        if (isLast && allAnswered && !hasFlagged) {
            if (submitBtn) submitBtn.style.display = 'flex';
            if (nextBtn) nextBtn.style.display = 'none';
        } else {
            if (submitBtn) submitBtn.style.display = 'none';
            if (nextBtn) {
                nextBtn.style.display = isLast ? 'none' : 'flex';
            }
        }

        if (typeof lucide !== 'undefined' && lucide.createIcons) {
            lucide.createIcons();
        }
        
        return { allAnswered, hasFlagged, answeredTotal, flaggedTotal };
    }

    function updateFlaggedList() {
        if (!elFlaggedList) return;
        
        const nums = flagged.map((f, i) => f ? i + 1 : null).filter(Boolean);
        if (nums.length > 0) {
            elFlaggedList.innerHTML = `
                <div class="flex flex-wrap gap-2">
                    ${nums.map(n => `
                        <button type="button" data-index="${n-1}"
                            class="flagged-btn px-3 py-1.5 bg-amber-100 text-amber-700
                                   rounded-full text-sm font-medium hover:bg-amber-200
                                   transition-colors flex items-center gap-1 shadow-sm">
                            <i data-lucide="flag" class="w-3 h-3"></i>${n}
                        </button>
                    `).join('')}
                </div>`;
            elFlaggedList.querySelectorAll('.flagged-btn').forEach(b =>
                b.addEventListener('click', () => show(parseInt(b.dataset.index)))
            );
        } else {
            elFlaggedList.innerHTML = '<p class="text-xs text-amber-600 text-center py-2">Belum ada yang ditandai</p>';
        }
        
        if (typeof lucide !== 'undefined' && lucide.createIcons) {
            lucide.createIcons();
        }
    }

    function updateNavButtons() {
        navBtns.forEach((b, i) => {
            b.classList.remove('nav-button-active', 'nav-button-answered', 'nav-button-flagged', 'nav-button-default');
            if (flagged[i]) {
                b.classList.add('nav-button-flagged');
            } else if (i === current) {
                b.classList.add('nav-button-active');
            } else if (answered[i]) {
                b.classList.add('nav-button-answered');
            } else {
                b.classList.add('nav-button-default');
            }
        });

        if (flagBtn) {
            flagBtn.innerHTML = flagged[current]
                ? `<i data-lucide="x" class="w-4 h-4"></i><span>Batal Tandai</span>`
                : `<i data-lucide="flag" class="w-4 h-4"></i><span>Tandai Ragu</span>`;
            flagBtn.style.backgroundColor = '#fef3c7';
            flagBtn.style.borderColor = flagged[current] ? '#f59e0b' : '#fbbf24';
            flagBtn.style.color = '#92400e';
        }

        if (elCurrentQuestion) elCurrentQuestion.textContent = current + 1;
        
        checkAllAnswered();
        updateFlaggedList();
        
        if (typeof lucide !== 'undefined' && lucide.createIcons) {
            lucide.createIcons();
        }
    }

    function show(index) {
        questions.forEach(q => {
            q.classList.add('hidden');
            q.style.opacity = '0';
            q.style.transform = 'translateX(20px)';
        });
        
        const q = questions[index];
        q.classList.remove('hidden');
        
        setTimeout(() => {
            q.style.transition = 'all .3s ease-out';
            q.style.opacity = '1';
            q.style.transform = 'translateX(0)';
        }, 50);
        
        if (prevBtn) prevBtn.disabled = index === 0;
        current = index;
        
        if (index === total - 1) {
            if (nextBtn) nextBtn.style.display = 'none';
        } else {
            if (nextBtn) nextBtn.style.display = 'flex';
            if (submitBtn) submitBtn.style.display = 'none';
        }
        
        updateNavButtons();
    }

    function setupOptionSelection() {
        document.querySelectorAll('.option-input').forEach(input => {
            input.addEventListener('click', function () {
                const qWrapper = this.closest('.question');
                const container = this.closest('.option-container');

                // Toggle off
                if (this.dataset.checked === 'true') {
                    this.checked = false;
                    this.dataset.checked = 'false';
                    container.classList.remove('selected');
                    const circle = container.querySelector('.option-circle');
                    const dot = container.querySelector('.option-dot');
                    if (circle) circle.classList.remove('border-blue-600', 'bg-blue-50');
                    if (dot) dot.classList.remove('opacity-100');
                    updateNavButtons();
                    return;
                }

                // Deselect semua di soal ini
                qWrapper.querySelectorAll('.option-input').forEach(r => {
                    r.dataset.checked = 'false';
                });
                qWrapper.querySelectorAll('.option-container').forEach(c => {
                    c.classList.remove('selected');
                    const circle = c.querySelector('.option-circle');
                    const dot = c.querySelector('.option-dot');
                    if (circle) circle.classList.remove('border-blue-600', 'bg-blue-50');
                    if (dot) dot.classList.remove('opacity-100');
                });

                // Pilih ini
                this.checked = true;
                this.dataset.checked = 'true';
                container.classList.add('selected');
                const circle = container.querySelector('.option-circle');
                const dot = container.querySelector('.option-dot');
                if (circle) circle.classList.add('border-blue-600', 'bg-blue-50');
                if (dot) dot.classList.add('opacity-100');

                updateNavButtons();
                const progress = checkAllAnswered();
                if (!progress.allAnswered && current < total - 1) {
                    setTimeout(() => show(current + 1), 300);
                }
            });
        });
    }

    if (nextBtn) {
        nextBtn.addEventListener('click', () => show(current + 1));
    }
    if (prevBtn) {
        prevBtn.addEventListener('click', () => show(current - 1));
    }
    navBtns.forEach(b => {
        b.addEventListener('click', () => show(parseInt(b.dataset.index)));
    });
    
    if (flagBtn) {
        flagBtn.addEventListener('click', () => {
            flagged[current] = !flagged[current];
            flagBtn.style.transform = 'scale(.95)';
            setTimeout(() => {
                flagBtn.style.transform = 'scale(1)';
            }, 150);
            updateNavButtons();
        });
    }
    
    if (submitAllBtn) {
        submitAllBtn.addEventListener('click', () => {
            const p = checkAllAnswered();
            if (!p.allAnswered) {
                alert(`Masih ada ${total - p.answeredTotal} soal yang belum dijawab.`);
                return;
            }
            if (p.hasFlagged) {
                alert(`Masih ada ${p.flaggedTotal} soal yang ditandai ragu-ragu. Hapus tanda ragu sebelum mengirim.`);
                return;
            }
            if (current !== total - 1) {
                show(total - 1);
            }
            setTimeout(() => {
                if (submitBtn) {
                    submitBtn.style.display = 'flex';
                    if (nextBtn) nextBtn.style.display = 'none';
                    submitBtn.click();
                }
            }, 300);
        });
    }

    show(0);
    setupOptionSelection();
    
    if (typeof lucide !== 'undefined' && lucide.createIcons) {
        lucide.createIcons();
    }

    // Zoom gambar
    document.querySelectorAll('.question .group').forEach(c => {
        c.addEventListener('click', function () {
            const img = this.querySelector('img');
            if (!img) return;
            const clone = img.cloneNode(true);
            clone.style.cssText = 'max-height:90vh;max-width:90vw;cursor:zoom-out;';
            const ov = document.createElement('div');
            ov.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.8);display:flex;align-items:center;justify-content:center;z-index:9999;cursor:zoom-out;';
            ov.appendChild(clone);
            document.body.appendChild(ov);
            ov.addEventListener('click', () => ov.remove());
        });
    });
});
</script>

{{-- =================================================
     SUBMIT CONFIRMATION MODAL
================================================== --}}
<div id="submitModal"
     class="fixed inset-0 z-[999] bg-black/60 backdrop-blur-sm hidden items-center justify-center p-4">
    <div class="bg-white rounded-2xl p-6 w-full max-w-md text-center space-y-4 shadow-2xl">
        <div class="w-16 h-16 mx-auto rounded-full bg-gradient-to-r from-emerald-100 to-green-100 flex items-center justify-center">
            <i data-lucide="send" class="w-8 h-8 text-emerald-600"></i>
        </div>
        <div>
            <h3 class="text-xl font-bold text-slate-900 mb-1">Kirim Jawaban?</h3>
            <p class="text-sm text-slate-600">Pastikan semua jawaban sudah diperiksa.</p>
        </div>
        <div class="bg-slate-50 rounded-lg p-4">
            <div class="grid grid-cols-2 gap-3">
                <div class="bg-white p-3 rounded-lg">
                    <div class="text-lg font-bold text-blue-600" id="modal-total">{{ $questions->count() }}</div>
                    <div class="text-xs text-slate-500">Total Soal</div>
                </div>
                <div class="bg-white p-3 rounded-lg">
                    <div class="text-lg font-bold text-emerald-600" id="modal-answered">0</div>
                    <div class="text-xs text-slate-500">Terjawab</div>
                </div>
                <div class="bg-white p-3 rounded-lg">
                    <div class="text-lg font-bold text-amber-600" id="modal-flagged">0</div>
                    <div class="text-xs text-slate-500">Ragu-ragu</div>
                </div>
                <div class="bg-white p-3 rounded-lg">
                    <div class="text-lg font-bold text-red-600" id="modal-unanswered">0</div>
                    <div class="text-xs text-slate-500">Belum</div>
                </div>
            </div>
        </div>
        <div class="flex gap-3 pt-2">
            <button id="cancelSubmit"
                class="flex-1 px-4 py-2.5 rounded-lg text-slate-700 font-medium border border-slate-200
                       hover:bg-slate-50 transition-all duration-200 flex items-center justify-center gap-2">
                <i data-lucide="arrow-left" class="w-4 h-4"></i>
                Periksa Lagi
            </button>
            <button id="confirmSubmit"
                class="flex-1 px-4 py-2.5 rounded-lg
                       bg-gradient-to-r from-emerald-500 to-green-600
                       text-black font-bold hover:shadow-lg
                       transition-all duration-200 flex items-center justify-center gap-2">
                <i data-lucide="send" class="w-4 h-4"></i>
                Kirim Sekarang
            </button>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const submitBtn  = document.getElementById('submitBtn');
    const modal      = document.getElementById('submitModal');
    const cancelBtn  = document.getElementById('cancelSubmit');
    const confirmBtn = document.getElementById('confirmSubmit');

    if (submitBtn) {
        submitBtn.addEventListener('click', () => {
            const qs = document.querySelectorAll('.question');
            let answered = 0;
            qs.forEach(q => {
                if ([...q.querySelectorAll('input[type="radio"].option-input')].some(r => r.checked)) {
                    answered++;
                }
            });
            const fl = document.querySelectorAll('.nav-button-flagged').length;

            document.getElementById('modal-answered').textContent = answered;
            document.getElementById('modal-flagged').textContent = fl;
            document.getElementById('modal-total').textContent = qs.length;
            document.getElementById('modal-unanswered').textContent = qs.length - answered;

            modal.classList.remove('hidden');
            modal.classList.add('flex');
        });
    }

    if (cancelBtn) {
        cancelBtn.addEventListener('click', () => {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        });
    }

    if (confirmBtn) {
        confirmBtn.addEventListener('click', () => {
            confirmBtn.innerHTML = '<i data-lucide="loader" class="w-4 h-4 animate-spin"></i> Mengirim...';
            confirmBtn.disabled = true;
            if (cancelBtn) cancelBtn.disabled = true;
            setTimeout(() => safeSubmitForm(false), 800);
        });
    }

    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && modal && !modal.classList.contains('hidden')) {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        }
    });
});
</script>

@endsection