<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mengerjakan Ujian: {{ $ujian->judul }} - SIPENA</title>
    <!-- Custom CSS from Teacher Role -->
    <link rel="stylesheet" href="{{ asset('css/guru.css') }}">
    <!-- FontAwesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            background-color: var(--bg-color);
            font-family: 'Inter', sans-serif;
            color: var(--text-dark);
            margin: 0;
            padding: 0 0 86px;
        }
        .exam-layout {
            display: grid;
            grid-template-columns: minmax(0, 1fr) minmax(280px, 320px);
            gap: 24px;
            max-width: 1200px;
            margin: 24px auto;
            padding: 0 16px;
        }
        @media (max-width: 900px) {
            .exam-layout {
                grid-template-columns: 1fr;
            }
            .navigation-card {
                position: static;
            }
        }
        .exam-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-hover) 100%);
            color: white;
            padding: 20px 24px;
            border-radius: var(--border-radius);
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: var(--shadow-md);
            margin-bottom: 24px;
        }
        .exam-header > div:first-child {
            min-width: 0;
        }
        .exam-header h1,
        .exam-header p,
        #question-text,
        #options-container {
            overflow-wrap: anywhere;
            word-break: break-word;
        }
        .timer-box {
            background: rgba(255, 255, 255, 0.15);
            padding: 10px 20px;
            border-radius: 8px;
            font-weight: 800;
            font-size: 1.15rem;
            display: flex;
            align-items: center;
            gap: 8px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            backdrop-filter: blur(4px);
        }
        .question-card {
            background: white;
            border-radius: var(--border-radius);
            padding: 28px;
            box-shadow: var(--shadow-sm);
            border: 1px solid #e2e8f0;
            min-height: 400px;
            display: flex;
            flex-direction: column;
            min-width: 0;
        }
        .option-card {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 14px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 12px;
            cursor: pointer;
            transition: var(--transition);
            min-width: 0;
        }
        .option-card:hover {
            border-color: #cbd5e1;
            background-color: var(--bg-color);
        }
        .option-card.selected {
            border-color: var(--primary-color);
            background-color: var(--primary-light);
        }
        .option-letter {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: #f1f5f9;
            color: #475569;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 800;
            font-size: 0.95rem;
            flex: 0 0 32px;
        }
        .option-card.selected .option-letter {
            background: var(--primary-color);
            color: white;
        }
        .navigation-card {
            background: white;
            border-radius: var(--border-radius);
            padding: 24px;
            box-shadow: var(--shadow-sm);
            border: 1px solid #e2e8f0;
            position: sticky;
            top: 24px;
            min-width: 0;
        }
        .grid-nav {
            display: grid;
            grid-template-columns: repeat(5, minmax(0, 1fr));
            gap: 8px;
            margin-top: 16px;
            margin-bottom: 24px;
            align-content: start;
        }
        .btn-nav-num {
            aspect-ratio: 1;
            border: 2px solid #dbe3ef;
            border-radius: 8px;
            font-weight: 700;
            font-size: 0.95rem;
            background: #ffffff;
            color: #111827;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: var(--transition);
        }
        .btn-nav-num.answered {
            background: #dcfce7;
            border-color: #16a34a;
            color: #14532d;
        }
        .btn-nav-num.current {
            background: #eff6ff;
            border-color: #2563eb;
            color: #1d4ed8;
            box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.2);
        }
        .btn-nav-num.current.answered {
            background: #dcfce7;
            border-color: #2563eb;
            color: #14532d;
        }
        .btn-footer-nav {
            display: flex;
            justify-content: space-between;
            margin-top: auto;
            padding-top: 20px;
            border-top: 1px solid #f1f5f9;
            gap: 12px;
            flex-wrap: wrap;
        }
        .btn-footer-nav .btn-submit-exam {
            background-color: #2563eb;
            border-color: #2563eb;
            color: #ffffff;
            margin-left: auto;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        .sidebar-submit {
            background: #fff;
            bottom: 0;
            padding-top: 12px;
            position: sticky;
        }
        .answer-progress {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            color: var(--text-gray);
            font-size: 0.85rem;
            font-weight: 700;
            margin-bottom: 14px;
            padding: 10px 12px;
        }
        .exam-sticky-submit {
            align-items: center;
            background: rgba(255, 255, 255, 0.96);
            border-top: 1px solid #e2e8f0;
            bottom: 0;
            box-shadow: 0 -10px 30px rgba(15, 23, 42, 0.08);
            display: flex;
            gap: 14px;
            justify-content: center;
            left: 0;
            padding: 12px 16px;
            position: fixed;
            right: 0;
            z-index: 999;
        }
        .exam-sticky-submit .answer-progress {
            margin: 0;
            min-width: 180px;
        }
        .exam-sticky-submit .btn {
            min-height: 44px;
            background-color: #2563eb;
            border: 1px solid #2563eb;
            border-radius: 10px;
            color: #ffffff;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            font-weight: 800;
            padding: 0 18px;
            text-decoration: none;
            white-space: nowrap;
        }
        .option-text {
            color: var(--text-dark);
            flex: 1;
            font-size: 1rem;
            line-height: 1.5;
            min-width: 0;
            overflow-wrap: anywhere;
            word-break: break-word;
        }
        #question-image {
            max-width: 100%;
            height: auto;
            box-sizing: border-box;
        }
        @media (max-width: 640px) {
            .exam-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 12px;
            }

            .timer-box {
                width: 100%;
                justify-content: center;
            }

            .question-card,
            .navigation-card {
                padding: 18px;
            }

            .option-card {
                align-items: flex-start;
                word-break: break-word;
            }

            .btn-footer-nav {
                flex-direction: column;
                gap: 10px;
            }

            .btn-footer-nav .btn {
                width: 100%;
                justify-content: center;
            }

            .btn-footer-nav .btn-submit-exam {
                margin-left: 0;
            }

            .exam-sticky-submit {
                align-items: stretch;
                flex-direction: column;
            }

            .exam-sticky-submit .answer-progress,
            .exam-sticky-submit .btn {
                width: 100%;
            }
        }
    </style>
</head>
<body>

    <div style="max-width: 1200px; margin: 24px auto; padding: 0 16px;">
        <!-- Header -->
        <header class="exam-header">
            <div>
                <h1 style="font-size: 1.3rem; margin: 0; font-weight: 700; color: white;">{{ $ujian->judul }}</h1>
                <p style="margin: 4px 0 0 0; opacity: 0.85; font-size: 0.9rem;">Mapel: {{ $ujian->mataPelajaran->nama_mapel }} | Kelas: {{ $kelas }}</p>
            </div>
            
            <div class="timer-box">
                <i class="fa-regular fa-clock"></i> <span id="timer-display">--:--</span>
            </div>
        </header>

        <!-- Main Layout -->
        <div class="exam-layout">
            <!-- Kiri: Question Card -->
            <div class="question-card" id="question-card-container">
                <!-- Header Soal -->
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding-bottom: 12px; border-bottom: 1px solid #f1f5f9;">
                    <span id="question-number-badge" style="font-weight: 800; font-size: 1rem; color: var(--primary-color); background: var(--primary-light); padding: 4px 12px; border-radius: 6px;">Soal --</span>
                    <span style="font-size: 0.85rem; color: var(--text-gray);" id="question-weight">Bobot: --</span>
                </div>

                <!-- Soal Image -->
                <div id="question-image-box" style="margin-bottom: 16px; display: none;">
                    <img id="question-image" src="" alt="Gambar Soal" style="max-height: 200px; border-radius: 8px; border: 1px solid #cbd5e1; background: white; padding: 4px;">
                </div>

                <!-- Pertanyaan -->
                <div id="question-text" style="font-size: 1.15rem; font-weight: 700; color: var(--text-dark); line-height: 1.6; margin-bottom: 24px;">
                    Loading pertanyaan...
                </div>

                <!-- Pilihan Jawaban -->
                <div id="options-container" style="display: flex; flex-direction: column;">
                    <!-- Rendered by JS -->
                </div>

                <!-- Footer Nav Buttons -->
                <div class="btn-footer-nav">
                    <button id="btn-prev-question" onclick="prevQuestion()" class="btn btn-outline"><i class="fa-solid fa-chevron-left"></i> Sebelumnya</button>
                    <button id="btn-next-question" onclick="nextQuestion()" class="btn btn-primary">Berikutnya <i class="fa-solid fa-chevron-right"></i></button>
                    <button type="button" onclick="confirmSubmit()" class="btn btn-submit-exam"><i class="fa-solid fa-check-double"></i> Selesai / Kirim Ujian</button>
                </div>
            </div>

            <!-- Kanan: Sidebar Navigation Grid -->
            <div>
                <div class="navigation-card">
                    <h3 style="font-size: 1.05rem; margin-top: 0; color: var(--text-dark); font-weight: 700;"><i class="fa-solid fa-grip" style="color: var(--primary-color); margin-right: 6px;"></i> Navigasi Soal</h3>
                    <p style="font-size: 0.8rem; color: var(--text-gray); margin-top: 4px;">Warna hijau menunjukkan soal telah dijawab.</p>

                    <div class="grid-nav" id="grid-navigation-container">
                        <!-- Rendered by JS -->
                    </div>

                    <div class="sidebar-submit">
                        <div class="answer-progress js-answer-progress">0 dari 0 soal terjawab</div>
                        <button onclick="confirmSubmit()" class="btn btn-primary" style="width: 100%; min-height: 46px; font-size: 0.95rem; background-color: #2563eb; border-color: #2563eb; color: #ffffff; display: flex; align-items: center; justify-content: center; gap: 8px; font-weight: 800;"><i class="fa-solid fa-check-double"></i> Selesai & Kumpulkan</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="exam-sticky-submit">
        <div class="answer-progress js-answer-progress">0 dari 0 soal terjawab</div>
        <button type="button" onclick="confirmSubmit()" class="btn">
            <i class="fa-solid fa-check-double"></i> Selesai / Kirim Ujian
        </button>
    </div>

    <!-- Hidden Submission Form -->
    <form id="exam-submit-form" action="{{ route('siswa.ujian.submit', $ujian->id) }}" method="POST" style="display: none;">
        @csrf
    </form>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        // Load data from Laravel backend
        let rawQuestions = @json($soals);
        const acakSoal = {{ $ujian->acak_soal ? 'true' : 'false' }};
        const acakJawaban = {{ $ujian->acak_jawaban ? 'true' : 'false' }};
        const examDurationMinutes = {{ $ujian->durasi }};
        const serverRemainingSeconds = {{ $remainingSeconds ?? ($ujian->durasi * 60) }};
        
        let questions = [];
        let currentIndex = 0;
        let answers = {}; // Maps: question_id -> original_option_key (A, B, C, D)

        // --- FISHER-YATES SHUFFLE ALGORITHM ---
        function fisherYatesShuffle(array) {
            let currentIndex = array.length, randomIndex;
            while (currentIndex !== 0) {
                randomIndex = Math.floor(Math.random() * currentIndex);
                currentIndex--;
                [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
            }
            return array;
        }

        const examId = {{ $ujian->id }};
        const studentId = {{ auth()->id() }};
        const storageKey = `ujian_answers_${examId}_${studentId}`;
        const legacyStorageKey = `sipena_exam_${examId}_answers`;
        const validOptionKeys = ['A', 'B', 'C', 'D'];
        const debugUjian = new URLSearchParams(window.location.search).has('debug_ujian') || localStorage.getItem('debugUjian') === '1';
        let isSubmitting = false;

        function getQuestionSignature() {
            return rawQuestions.map(q => q.id).join('|');
        }

        function getValidQuestionIds() {
            return new Set(rawQuestions.map(q => String(q.id)));
        }

        function normalizeSavedAnswers(savedAnswers) {
            const validQuestionIds = getValidQuestionIds();
            const normalized = {};

            Object.entries(savedAnswers || {}).forEach(([questionId, optionKey]) => {
                if (validQuestionIds.has(String(questionId)) && validOptionKeys.includes(optionKey)) {
                    normalized[questionId] = optionKey;
                }
            });

            return normalized;
        }

        function loadSavedAnswers() {
            try {
                sessionStorage.removeItem(legacyStorageKey);
                const saved = sessionStorage.getItem(storageKey);
                if (!saved) {
                    answers = {};
                    return;
                }

                const parsed = JSON.parse(saved);
                if (!parsed || parsed.signature !== getQuestionSignature() || typeof parsed.answers !== 'object') {
                    sessionStorage.removeItem(storageKey);
                    answers = {};
                    return;
                }

                answers = normalizeSavedAnswers(parsed.answers);
            } catch (error) {
                sessionStorage.removeItem(storageKey);
                answers = {};
            }
        }

        function persistAnswers() {
            sessionStorage.setItem(storageKey, JSON.stringify({
                signature: getQuestionSignature(),
                answers: normalizeSavedAnswers(answers)
            }));
        }

        function createTextNodeElement(tagName, className, text) {
            const element = document.createElement(tagName);
            if (className) {
                element.className = className;
            }
            element.textContent = text ?? '';
            return element;
        }

        function getAnsweredCount() {
            return Object.values(answers).filter(Boolean).length;
        }

        function updateProgress() {
            document.querySelectorAll('.js-answer-progress').forEach((progress) => {
                progress.textContent = `${getAnsweredCount()} dari ${questions.length} soal terjawab`;
            });
        }

        function debugExamState(source) {
            if (!debugUjian) {
                return;
            }

            console.debug('[SIPENA ujian]', {
                source,
                storageKey,
                totalQuestions: questions.length,
                renderedNavButtons: document.querySelectorAll('.btn-nav-num').length,
                currentQuestionIndex: currentIndex,
                answeredCount: getAnsweredCount(),
                questionIds: questions.map(q => q.id),
                answers
            });
        }

        // Initialize and shuffle questions & answers
        function initQuestions() {
            // Map each question to include its options with original keys
            questions = rawQuestions.map(rawQuestion => {
                const q = {
                    id: rawQuestion.id,
                    pertanyaan: rawQuestion.pertanyaan || '',
                    gambar: rawQuestion.gambar || '',
                    bobot: rawQuestion.bobot ?? 1,
                    opsi_a: rawQuestion.opsi_a || '',
                    opsi_b: rawQuestion.opsi_b || '',
                    opsi_c: rawQuestion.opsi_c || '',
                    opsi_d: rawQuestion.opsi_d || ''
                };
                let options = [
                    { key: 'A', val: q.opsi_a },
                    { key: 'B', val: q.opsi_b },
                    { key: 'C', val: q.opsi_c },
                    { key: 'D', val: q.opsi_d }
                ];
                if (acakJawaban) {
                    options = fisherYatesShuffle(options);
                }
                q.shuffledOptions = options;
                return q;
            });

            if (acakSoal) {
                questions = fisherYatesShuffle(questions);
            }

            currentIndex = 0;
        }

        // Render current question
        function renderQuestion() {
            if (questions.length === 0) return;
            const q = questions[currentIndex];
            if (!q) return;

            // Update badge & weight
            document.getElementById('question-number-badge').innerText = `Soal ${currentIndex + 1} dari ${questions.length}`;
            document.getElementById('question-weight').innerText = `Bobot: ${q.bobot}`;

            // Show image if available
            const imgBox = document.getElementById('question-image-box');
            const imgEl = document.getElementById('question-image');
            if (q.gambar) {
                imgEl.src = "{{ asset('storage') }}/" + q.gambar;
                imgEl.alt = `Gambar soal ${currentIndex + 1}`;
                imgBox.style.display = 'block';
            } else {
                imgEl.removeAttribute('src');
                imgBox.style.display = 'none';
            }

            // Question Text
            document.getElementById('question-text').innerText = q.pertanyaan;

            // Options list
            const optionsContainer = document.getElementById('options-container');
            optionsContainer.innerHTML = '';

            const letters = ['A', 'B', 'C', 'D'];
            q.shuffledOptions.forEach((opt, idx) => {
                const isSelected = answers[q.id] === opt.key;
                
                const card = document.createElement('div');
                card.className = `option-card ${isSelected ? 'selected' : ''}`;
                card.onclick = () => selectOption(q.id, opt.key);
                card.setAttribute('role', 'button');
                card.setAttribute('tabindex', '0');
                card.setAttribute('aria-pressed', isSelected ? 'true' : 'false');
                card.onkeydown = (event) => {
                    if (event.key === 'Enter' || event.key === ' ') {
                        event.preventDefault();
                        selectOption(q.id, opt.key);
                    }
                };

                card.appendChild(createTextNodeElement('div', 'option-letter', letters[idx]));
                card.appendChild(createTextNodeElement('div', 'option-text', opt.val));
                optionsContainer.appendChild(card);
            });

            // Adjust navigation buttons
            const btnPrev = document.getElementById('btn-prev-question');
            const btnNext = document.getElementById('btn-next-question');

            if (currentIndex === 0) {
                btnPrev.style.visibility = 'hidden';
            } else {
                btnPrev.style.visibility = 'visible';
            }

            if (currentIndex === questions.length - 1) {
                btnNext.innerText = 'Tinjau Jawaban';
                btnNext.onclick = () => {
                    Swal.fire({
                        title: 'Soal Terakhir',
                        text: 'Ini adalah soal terakhir. Silakan periksa kembali navigasi soal jika ada yang belum dijawab.',
                        icon: 'info',
                        confirmButtonColor: 'var(--primary-color)'
                    });
                };
            } else {
                btnNext.innerHTML = 'Berikutnya <i class="fa-solid fa-chevron-right"></i>';
                btnNext.onclick = nextQuestion;
            }

            // Render Nav Sidebar
            renderNavigation();
            updateProgress();
            debugExamState('renderQuestion');
        }

        // Selection answer
        function selectOption(questionId, originalOptionKey) {
            answers[questionId] = originalOptionKey;
            persistAnswers();
            renderQuestion();
        }

        // Navigate questions
        function prevQuestion() {
            if (currentIndex > 0) {
                currentIndex--;
                renderQuestion();
            }
        }

        document.addEventListener('keydown', function(event) {
            if (event.key === 'ArrowLeft') {
                prevQuestion();
            } else if (event.key === 'ArrowRight') {
                if (currentIndex < questions.length - 1) {
                    nextQuestion();
                }
            }
        });

        function nextQuestion() {
            if (currentIndex < questions.length - 1) {
                currentIndex++;
                renderQuestion();
            }
        }

        function jumpToQuestion(index) {
            currentIndex = index;
            renderQuestion();
        }

        // Render Sidebar Navigation Grid
        function renderNavigation() {
            const container = document.getElementById('grid-navigation-container');
            container.innerHTML = '';

            questions.forEach((q, idx) => {
                const isAnswered = Boolean(answers[q.id]);
                const isCurrent = idx === currentIndex;

                const btn = document.createElement('button');
                btn.className = `btn-nav-num ${isAnswered ? 'answered' : ''} ${isCurrent ? 'current' : ''}`;
                btn.innerText = idx + 1;
                btn.onclick = () => jumpToQuestion(idx);

                container.appendChild(btn);
            });

            updateProgress();
            debugExamState('renderNavigation');
        }

        // Timer Implementation
        let timeRemainingSeconds = serverRemainingSeconds;
        function startTimer() {
            const display = document.getElementById('timer-display');
            
            const interval = setInterval(() => {
                if (timeRemainingSeconds <= 0) {
                    clearInterval(interval);
                    Swal.fire({
                        title: 'Waktu Habis!',
                        text: 'Waktu ujian telah berakhir. Jawaban Anda akan otomatis dikirimkan.',
                        icon: 'warning',
                        allowOutsideClick: false,
                        confirmButtonColor: '#2563eb',
                        confirmButtonText: 'Kumpulkan Sekarang'
                    }).then(() => {
                        submitUjian();
                    });
                    // Auto-submit after 3 seconds if modal isn't clicked
                    setTimeout(submitUjian, 3000);
                    return;
                }

                timeRemainingSeconds--;
                const minutes = Math.floor(timeRemainingSeconds / 60);
                const seconds = timeRemainingSeconds % 60;
                
                display.innerText = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;

                // Warning colors when 5 minutes remaining
                if (timeRemainingSeconds <= 300) {
                    display.parentElement.style.background = '#fee2e2';
                    display.parentElement.style.color = '#ef4444';
                    display.parentElement.style.borderColor = '#fca5a5';
                }
            }, 1000);
        }

        // Confirm submit
        function confirmSubmit() {
            const totalQuestions = questions.length;
            const answeredCount = Object.keys(answers).length;
            const unansweredCount = totalQuestions - answeredCount;

            let htmlMsg = `Anda telah menjawab <strong>${answeredCount}</strong> dari ${totalQuestions} soal.`;
            if (unansweredCount > 0) {
                htmlMsg += `<br><span style="color: red; font-weight: bold;">Peringatan: Masih ada ${unansweredCount} soal yang belum Anda jawab!</span>`;
            }

            Swal.fire({
                title: 'Apakah Anda sudah selesai?',
                html: htmlMsg,
                icon: unansweredCount > 0 ? 'warning' : 'question',
                showCancelButton: true,
                confirmButtonColor: '#2563eb',
                cancelButtonColor: '#cbd5e1',
                confirmButtonText: 'Ya, Kumpulkan Jawaban',
                cancelButtonText: 'Periksa Kembali'
            }).then((result) => {
                if (result.isConfirmed) {
                    submitUjian();
                }
            });
        }

        // Submit form handler
        function submitUjian() {
            if (isSubmitting) {
                return;
            }
            isSubmitting = true;

            // Disable page exit alert
            window.onbeforeunload = null;

            const form = document.getElementById('exam-submit-form');
            form.innerHTML = ''; // Reset

            // Add CSRF
            const csrf = document.createElement('input');
            csrf.type = 'hidden';
            csrf.name = '_token';
            csrf.value = "{{ csrf_token() }}";
            form.appendChild(csrf);

            // Add answers mapping
            for (const [soalId, optionKey] of Object.entries(answers)) {
                if (!optionKey) {
                    continue;
                }
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = `answers[${soalId}]`;
                input.value = optionKey;
                form.appendChild(input);
            }

            sessionStorage.removeItem(storageKey);
            sessionStorage.removeItem(legacyStorageKey);
            form.submit();
        }

        // Prevent leaving page warning
        window.onbeforeunload = function() {
            return "Apakah Anda yakin ingin meninggalkan ujian? Jawaban Anda yang belum disubmit akan hilang.";
        };

        // Initialize page
        document.addEventListener('DOMContentLoaded', () => {
            loadSavedAnswers();
            initQuestions();
            renderQuestion();
            startTimer();
            debugExamState('DOMContentLoaded');
        });
    </script>
</body>
</html>
