

<?php $__env->startSection('title', 'Kuis Interaktif Level 1-5 - PilahPintar'); ?>

<?php $__env->startSection('styles'); ?>
<style>
    .game-bucket {
        border-radius: 1.5rem;
        border: 4px solid #cbd5e1;
        background: white;
        padding: 1.5rem 1rem;
        cursor: pointer;
        transition: all 0.2s ease;
        box-shadow: 0 8px 15px rgba(0,0,0,0.05);
    }
    .game-bucket:hover {
        transform: translateY(-8px);
    }
    .bucket-organik { border-color: var(--organik-color) !important; color: var(--organik-color); }
    .bucket-anorganik { border-color: var(--anorganik-color) !important; color: var(--anorganik-color); }
    .bucket-b3 { border-color: var(--b3-color) !important; color: var(--b3-color); }

    .bucket-organik:hover { background: #e8f5e9; }
    .bucket-anorganik:hover { background: #fffde7; }
    .bucket-b3:hover { background: #ffebee; }

    .game-item-display {
        width: 130px;
        height: 130px;
        background: white;
        border: 4px solid #334155;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 1.5rem;
        box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        cursor: pointer;
    }

    .shake-animation {
        animation: shake 0.5s;
    }
    .success-pulse {
        animation: successPulse 0.5s;
    }

    @keyframes shake {
        0%, 100% { transform: translateX(0); }
        10%, 30%, 50%, 70%, 90% { transform: translateX(-10px); }
        20%, 40%, 60%, 80% { transform: translateX(10px); }
    }
    @keyframes successPulse {
        0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }
        70% { transform: scale(1.1); box-shadow: 0 0 0 15px rgba(16, 185, 129, 0); }
        100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
    }

    .emoji-item {
        font-size: 4.5rem;
    }
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div class="container">

    <!-- HEADER -->
    <div class="text-center mb-4">
        <span class="badge bg-warning text-dark font-heading px-3 py-2 rounded-pill mb-2">
            <i class="fa-solid fa-gamepad me-1"></i> Gamifikasi Pembelajaran
        </span>
        <h2 class="fw-bold font-heading text-success">Kuis & Game Edukasi Sampah 🎮</h2>
        <p class="text-muted col-lg-8 mx-auto mb-2">Yuk selesaikan 5 level seru untuk mendapatkan Sertifikat Pahlawan Lingkungan!</p>
    </div>

    <!-- REGISTRATION FORM (BEFORE PLAYING) -->
    <div id="registrationScreen" class="row justify-content-center">
        <div class="col-md-6 col-lg-5">
            <div class="card card-eco p-4 p-md-5 text-center">
                <span class="fs-1 mb-2">🧒🏫</span>
                <h4 class="fw-bold font-heading text-dark">Petualang Baru!</h4>
                <p class="text-muted small mb-4">Masukkan nama dan kelasmu sebelum mulai petualangan belajar memilah sampah!</p>
                
                <form id="registrationForm" onsubmit="saveRegistration(event)">
                    <div class="mb-3 text-start">
                        <label class="form-label fw-bold small">Nama Lengkapmu:</label>
                        <input type="text" id="regName" class="form-control form-control-lg rounded-pill border-2" placeholder="Contoh: Budi Santoso" required>
                    </div>
                    <div class="mb-4 text-start">
                        <label class="form-label fw-bold small">Pilih Kelas:</label>
                        <select id="regClass" class="form-select form-select-lg rounded-pill border-2" required>
                            <option value="">-- Pilih Kelas --</option>
                            <option value="Kelas 1 SD">Kelas 1 SD 🎒</option>
                            <option value="Kelas 2 SD">Kelas 2 SD 🎒</option>
                            <option value="Kelas 3 SD">Kelas 3 SD 🎒</option>
                            <option value="Kelas 4 SD">Kelas 4 SD 🎒</option>
                            <option value="Kelas 5 SD">Kelas 5 SD 🎒</option>
                            <option value="Kelas 6 SD">Kelas 6 SD 🎒</option>
                            <option value="Umum / Masyarakat">Umum / Masyarakat 🧑‍🌾</option>
                        </select>
                    </div>

                    <button type="submit" class="btn btn-success btn-lg w-100 rounded-pill fw-bold text-white shadow">
                        Mulai Petualangan 🚀
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- MAIN GAME AREA (HIDDEN UNTIL REGISTERED) -->
    <div id="mainGameArea" style="display: none;">
        
        <!-- STUDENT PROFILE DASHBOARD HEADER -->
        <div class="card bg-white p-3 rounded-4 border-2 border-success shadow-sm mb-4">
            <div class="d-flex flex-column flex-md-row justify-content-between align-items-center gap-3">
                <div class="d-flex align-items-center gap-3">
                    <span class="fs-2">🧒🏫</span>
                    <div>
                        <h6 class="fw-bold text-success font-heading mb-0" id="dashName">Nama Siswa</h6>
                        <small class="text-muted" id="dashClass">Kelas SD</small>
                    </div>
                </div>
                <div class="d-flex align-items-center gap-2 flex-wrap justify-content-center justify-content-md-start">
                    <span class="badge bg-success text-white font-heading px-3 py-2 rounded-pill">
                        ⭐ Nilai Tertinggi: <span id="dashHighScore">0</span> / 500
                    </span>
                    <span class="badge bg-warning text-dark font-heading px-3 py-2 rounded-pill">
                        🏆 Level Terbuka: <span id="dashLevel">1</span>
                    </span>
                    <button class="btn btn-outline-danger btn-sm rounded-pill" onclick="logoutStudent()">
                        Ganti Akun <i class="fa-solid fa-right-from-bracket ms-1"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- LEVEL SELECTION SCREEN -->
        <div id="levelSelectionScreen">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h4 class="fw-bold font-heading text-dark mb-0">🏆 Pilih Level Permainan</h4>
                <button class="btn btn-outline-secondary btn-sm rounded-pill" onclick="resetProgress()">
                    <i class="fa-solid fa-rotate-left me-1"></i> Reset Progress
                </button>
            </div>

            <div class="row gy-4 mb-5">
                <?php
                    $levelTitles = [
                        1 => ['title' => 'Detektif Sampah', 'icon' => '🔍', 'desc' => 'Tebak Jenis Sampah (5 Soal Kuis Visual)'],
                        2 => ['title' => 'Pilahan Ajaib 1', 'icon' => '🟢', 'desc' => 'Game Memilah Sampah Organik & Anorganik'],
                        3 => ['title' => 'Pejuang 3R', 'icon' => '🔄', 'desc' => 'Edukasi Kurangi & Daur Ulang (5 Soal Kuis Visual)'],
                        4 => ['title' => 'Pilahan Ajaib 2', 'icon' => '🔴', 'desc' => 'Game Memilah Sampah Organik, Anorganik & B3'],
                        5 => ['title' => 'Pahlawan Bumi', 'icon' => '👑', 'desc' => 'Aksi Lingkungan & Zero Waste (5 Soal Kuis Visual)'],
                    ];
                ?>

                <?php for($lvl = 1; $lvl <= 5; $lvl++): ?>
                <div class="col-md-6 col-lg-4">
                    <div class="level-card p-4 h-100 locked" id="levelCard-<?php echo e($lvl); ?>" onclick="startLevel(<?php echo e($lvl); ?>)">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <span class="badge badge-level bg-secondary text-white" id="levelBadge-<?php echo e($lvl); ?>">🔒 Terkunci</span>
                            <span class="fs-2"><?php echo e($levelTitles[$lvl]['icon']); ?></span>
                        </div>
                        <h5 class="fw-bold font-heading text-dark mb-1"><?php echo e($levelTitles[$lvl]['title']); ?></h5>
                        <p class="text-muted small mb-3"><?php echo e($levelTitles[$lvl]['desc']); ?></p>
                        
                        <div class="d-flex align-items-center justify-content-between pt-2 border-top">
                            <small class="fw-bold text-success" id="levelStatus-<?php echo e($lvl); ?>">Luluskan Level <?php echo e($lvl-1); ?> Dulu</small>
                            <button class="btn btn-sm btn-success rounded-pill px-3 fw-bold" id="playBtn-<?php echo e($lvl); ?>" disabled>
                                Main <i class="fa-solid fa-play ms-1"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <?php endfor; ?>
            </div>

            <!-- CERTIFICATE CLAIM BANNER -->
            <div class="card card-eco p-4 bg-white border-2 border-warning text-center shadow-sm" id="certClaimBanner" style="display: none;">
                <span class="fs-1 mb-2">🎓🏆</span>
                <h4 class="fw-bold font-heading text-dark">Selamat! Kamu Telah Menjadi Pahlawan Lingkungan!</h4>
                <p class="text-muted col-md-8 mx-auto">Nama dan kelasmu akan otomatis dicantumkan ke dalam Sertifikat Kelulusan.</p>
                <button class="btn btn-warning btn-lg rounded-pill fw-bold text-dark px-5 shadow mx-auto" onclick="openCertificateModal()">
                    <i class="fa-solid fa-certificate me-2"></i> Cetak Sertifikat Pahlawan Lingkungan 📜
                </button>
            </div>
        </div>

        <!-- PLAYING MULTIPLE CHOICE QUIZ SCREEN (LEVEL 1, 3, 5) -->
        <div id="gameplayScreen" style="display: none;">
            <div class="row justify-content-center">
                <div class="col-lg-8">
                    
                    <div class="card card-eco p-4 p-md-5">
                        <div class="d-flex justify-content-between align-items-center mb-4 pb-3 border-bottom">
                            <div>
                                <span class="badge bg-success font-heading px-3 py-2 rounded-pill fs-6" id="activeLevelTitle">Level 1</span>
                            </div>
                            <button class="btn btn-outline-secondary btn-sm rounded-pill" onclick="quitQuiz()">
                                <i class="fa-solid fa-xmark me-1"></i> Keluar
                            </button>
                        </div>

                        <!-- PROGRESS BAR -->
                        <div class="progress mb-4" style="height: 10px; border-radius: 999px;">
                            <div class="progress-bar bg-success progress-bar-striped progress-bar-animated" id="quizProgressBar" style="width: 0%;"></div>
                        </div>

                        <!-- QUESTION BOX -->
                        <div id="questionContainer">
                            <small class="text-muted fw-bold d-block mb-2">Soal Ke-<span id="questionNum">1</span> dari 5</small>
                            
                            <!-- EMOJI / ILLUSTRATION BOX FOR KIDS -->
                            <div class="text-center bg-light p-4 rounded-4 mb-4 border">
                                <span id="questionVisual" class="display-1 animate-float d-block">❓</span>
                            </div>

                            <h5 class="fw-bold font-heading text-dark mb-4 text-center" id="questionText">Teks Pertanyaan...</h5>

                            <!-- OPTIONS -->
                            <div class="d-grid gap-3 mb-4" id="optionsContainer">
                                <!-- Rendered options -->
                            </div>

                            <!-- EXPLANATION -->
                            <div class="p-3 rounded-3 mb-4" id="explanationBox" style="display: none;">
                                <strong id="feedbackTitle" class="d-block mb-1"></strong>
                                <span id="explanationText" class="small"></span>
                            </div>

                            <button class="btn btn-success btn-lg w-100 rounded-pill fw-bold" id="nextQuestionBtn" onclick="nextQuestion()" style="display: none;">
                                Pertanyaan Selanjutnya &rarr;
                            </button>
                        </div>
                    </div>

                </div>
            </div>
        </div>

        <!-- PLAYING INTERACTIVE MINI GAME SCREEN (LEVEL 2 & 4) -->
        <div id="miniGameScreen" style="display: none;">
            <div class="row justify-content-center">
                <div class="col-lg-8">
                    <div class="card card-eco p-4 p-md-5 text-center">
                        <div class="d-flex justify-content-between align-items-center mb-4 pb-3 border-bottom">
                            <div>
                                <span class="badge bg-warning text-dark font-heading px-3 py-2 rounded-pill fs-6" id="gameLevelTitle">Game Memilah</span>
                            </div>
                            <button class="btn btn-outline-secondary btn-sm rounded-pill" onclick="quitQuiz()">
                                <i class="fa-solid fa-xmark me-1"></i> Keluar
                            </button>
                        </div>

                        <p class="text-muted fw-bold mb-1">Pilahlah Item ini dengan Menekan Bak yang Benar!</p>
                        <small class="text-muted d-block mb-4">Sisa item yang harus dipilah: <span class="badge bg-primary" id="gameItemsLeft">5</span></small>

                        <!-- ITEM TO SORT DISPLAY -->
                        <div class="game-item-display" id="gameItemDisplay">
                            <span class="emoji-item animate-float" id="gameEmojiDisplay">🍎</span>
                        </div>
                        <h4 class="fw-bold font-heading text-dark mb-5" id="gameItemName">Apel</h4>

                        <!-- BUCKETS BINS -->
                        <div class="row g-3 justify-content-center" id="bucketsContainer">
                            <div class="col-4">
                                <div class="game-bucket bucket-organik" onclick="throwItem('Organik')">
                                    <span class="fs-1 d-block mb-1">🟢</span>
                                    <strong class="font-heading">ORGANIK</strong>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="game-bucket bucket-anorganik" onclick="throwItem('Anorganik')">
                                    <span class="fs-1 d-block mb-1">🟡</span>
                                    <strong class="font-heading">ANORGANIK</strong>
                                </div>
                            </div>
                            <div class="col-4" id="b3BucketCol" style="display: none;">
                                <div class="game-bucket bucket-b3" onclick="throwItem('B3')">
                                    <span class="fs-1 d-block mb-1">🔴</span>
                                    <strong class="font-heading">B3</strong>
                                </div>
                            </div>
                        </div>

                        <!-- EXPLANATION GAME FEEDBACK -->
                        <div class="p-3 rounded-3 mt-4" id="gameExplanationBox" style="display: none;">
                            <strong id="gameFeedbackTitle" class="d-block mb-1"></strong>
                            <span id="gameExplanationText" class="small"></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- RESULT SCREEN -->
        <div id="resultScreen" style="display: none;">
            <div class="row justify-content-center">
                <div class="col-lg-6 text-center">
                    <div class="card card-eco p-5">
                        <span class="fs-1 mb-2" id="resultEmoji">🎉</span>
                        <h3 class="fw-bold font-heading text-dark mb-1" id="resultTitle">Level Selesai!</h3>
                        <p class="text-muted">Hasil evaluasi belajar kamu</p>
                        
                        <div class="p-4 bg-light rounded-4 my-4 border">
                            <small class="text-muted fw-bold d-block">SKOR AKHIR</small>
                            <h1 class="display-3 fw-extrabold text-success mb-0" id="resultScore">100</h1>
                            <span class="badge bg-success px-3 py-2 rounded-pill mt-2" id="resultStatusBadge">LULUS</span>
                        </div>

                        <div class="d-grid gap-2">
                            <button class="btn btn-success btn-lg rounded-pill fw-bold" id="resultNextBtn" onclick="backToLevels()">
                                <i class="fa-solid fa-list-check me-1"></i> Kembali ke Menu Level
                            </button>
                            <button class="btn btn-outline-secondary rounded-pill" onclick="retryCurrentLevel()">
                                <i class="fa-solid fa-rotate-right me-1"></i> Coba Lagi Level Ini
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>

</div>

<!-- CERTIFICATE MODAL -->
<div class="modal fade" id="certificateModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content border-0 rounded-4">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold font-heading">📜 Cetak Sertifikat Pahlawan Lingkungan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <div class="certificate-box text-center" id="printableCertificate">
                    <div class="certificate-seal mb-3">
                        🌿
                    </div>
                    <h6 class="text-success fw-bold font-heading text-uppercase mb-1" style="letter-spacing: 2px;">SERTIFIKAT KELULUSAN</h6>
                    <h3 class="fw-bold font-heading text-dark mb-4">PAHLAWAN LINGKUNGAN DESA</h3>
                    
                    <p class="text-muted mb-1">Sertifikat ini diberikan secara bangga kepada:</p>
                    <h2 class="fw-bold font-heading text-success text-decoration-underline mb-2" id="certDisplayName">Siswa Peduli Lingkungan</h2>
                    <h5 class="text-muted font-heading mb-4" id="certDisplayClass">Kelas</h5>
                    
                    <p class="text-muted col-md-10 mx-auto small mb-4">
                        Atas keberhasilan dan ketuntasan mempelajari seluruh materi edukasi pengelolaan sampah serta menyelesaikan Kuis & Game Mini Level 1 s.d. 5 pada sistem PilahPintar.
                    </p>

                    <div class="row align-items-center mt-4 pt-3 border-top border-2">
                        <div class="col-6 text-start">
                            <small class="text-muted d-block">Tanggal Kelulusan:</small>
                            <strong class="text-dark small"><?php echo e(date('d F Y')); ?></strong>
                        </div>
                        <div class="col-6 text-end">
                            <small class="text-muted d-block">Penyelenggara:</small>
                            <strong class="text-success small">Tim KKN Edukasi Sampah</strong>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer border-0 pt-0">
                <button type="button" class="btn btn-secondary rounded-pill" data-bs-dismiss="modal">Tutup</button>
                <button type="button" class="btn btn-success rounded-pill fw-bold px-4" onclick="window.print()">
                    <i class="fa-solid fa-print me-1"></i> Cetak / Simpan PDF
                </button>
            </div>
        </div>
    </div>
</div>

<!-- LEADERBOARD CARD -->
<div class="row justify-content-center mt-5 mb-5" id="leaderboardSection">
    <div class="col-lg-8">
        <div class="card card-eco p-4 p-md-5 border-0 shadow-sm text-center">
            <h4 class="fw-bold font-heading text-success mb-3">
                <i class="fa-solid fa-trophy text-warning me-2"></i> Papan Peringkat Pahlawan Lingkungan
            </h4>
            <p class="text-muted small mb-4">Berikut adalah 10 petualang hebat dengan nilai tertinggi dalam kuis pengelolaan sampah!</p>
            <div class="table-responsive text-start">
                <table class="table table-hover align-middle text-center mb-0">
                    <thead class="table-light font-heading">
                        <tr>
                            <th style="width: 15%;">Peringkat</th>
                            <th>Nama Petualang</th>
                            <th>Kelas</th>
                            <th>Nilai Tertinggi</th>
                        </tr>
                    </thead>
                    <tbody id="leaderboardBody">
                        <tr>
                            <td colspan="4" class="text-muted py-3">Memuat data papan peringkat...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
    // Database seeded questions
    const rawQuestions = <?php echo json_encode($questionsByLevel, 15, 512) ?>;
    
    // Mini-Game level lists (5 items to sort per game level)
    const level2GameItems = [
        { name: 'Kulit Pisang', emoji: '🍌', type: 'Organik', desc: 'Kulit pisang berasal dari alam dan sangat mudah membusuk.' },
        { name: 'Botol Plastik', emoji: '🥤', type: 'Anorganik', desc: 'Botol plastik buatan pabrik, tidak bisa membusuk.' },
        { name: 'Daun Kering', emoji: '🍂', type: 'Organik', desc: 'Daun kering berasal dari pepohonan hayati.' },
        { name: 'Kaleng Minuman', emoji: '🥫', type: 'Anorganik', desc: 'Kaleng soda alumunium adalah benda logam keras.' },
        { name: 'Sisa Sayur', emoji: '🥬', type: 'Organik', desc: 'Sisa sayuran memasak sisa mamah mudah terurai.' }
    ];

    const level4GameItems = [
        { name: 'Baterai Bekas', emoji: '🔋', type: 'B3', desc: 'Baterai mengandung asam kimia beracun.' },
        { name: 'Tulang Ayam', emoji: '🦴', type: 'Organik', desc: 'Tulang sisa makanan adalah zat hayati organik.' },
        { name: 'Kantong Kresek', emoji: '🛍️', type: 'Anorganik', desc: 'Plastik belanja tidak bisa terurai alami.' },
        { name: 'Lampu Neon', emoji: '💡', type: 'B3', desc: 'Lampu neon berisi gas raksa beracun.' },
        { name: 'Kardus Bekas', emoji: '📦', type: 'Anorganik', desc: 'Kardus terbuat dari serat kayu pabrikan anorganik.' }
    ];

    let studentName = '';
    let studentClass = '';

    let currentLevel = 1;
    let quizQuestions = [];
    let currentQuestionIndex = 0;
    
    // Game state variables
    let gameItemsList = [];
    let gameCurrentIndex = 0;
    let gameIncorrectAttempts = 0;

    let score = 0;
    let soundEnabled = true;

    // Web Audio Synthesizer Sounds
    function playSound(type) {
        if (!soundEnabled) return;
        try {
            const ctx = new (window.AudioContext || window.webkitAudioContext)();
            const osc = ctx.createOscillator();
            const gain = ctx.createGain();
            osc.connect(gain);
            gain.connect(ctx.destination);

            if (type === 'correct') {
                osc.frequency.setValueAtTime(523.25, ctx.currentTime);
                osc.frequency.setValueAtTime(659.25, ctx.currentTime + 0.1);
                osc.frequency.setValueAtTime(783.99, ctx.currentTime + 0.2);
                gain.gain.setValueAtTime(0.3, ctx.currentTime);
                gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.4);
                osc.start(ctx.currentTime);
                osc.stop(ctx.currentTime + 0.4);
            } else if (type === 'wrong') {
                osc.type = 'sawtooth';
                osc.frequency.setValueAtTime(220, ctx.currentTime);
                osc.frequency.setValueAtTime(164.81, ctx.currentTime + 0.15);
                gain.gain.setValueAtTime(0.3, ctx.currentTime);
                gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.35);
                osc.start(ctx.currentTime);
                osc.stop(ctx.currentTime + 0.35);
            }
        } catch (e) {
            console.log('Audio error:', e);
        }
    }

    // REGISTRATION CONTROL
    document.addEventListener('DOMContentLoaded', () => {
        const savedName = localStorage.getItem('pilahpintar_student_name');
        const savedClass = localStorage.getItem('pilahpintar_student_class');

        loadLeaderboard();

        if (savedName && savedClass) {
            studentName = savedName;
            studentClass = savedClass;
            showMainGameArea();
        } else {
            showRegistrationScreen();
        }
    });

    function showRegistrationScreen() {
        document.getElementById('registrationScreen').style.display = 'flex';
        document.getElementById('mainGameArea').style.display = 'none';
        document.getElementById('leaderboardSection').style.display = 'flex';
    }

    function showMainGameArea() {
        document.getElementById('registrationScreen').style.display = 'none';
        document.getElementById('mainGameArea').style.display = 'block';
        document.getElementById('leaderboardSection').style.display = 'flex';

        document.getElementById('dashName').innerText = studentName;
        document.getElementById('dashClass').innerText = studentClass;

        loadUserProgress();
    }

    function saveRegistration(e) {
        e.preventDefault();
        const nameInput = document.getElementById('regName').value.trim();
        const classInput = document.getElementById('regClass').value;

        if (nameInput && classInput) {
            studentName = nameInput;
            studentClass = classInput;

            localStorage.setItem('pilahpintar_student_name', studentName);
            localStorage.setItem('pilahpintar_student_class', studentClass);

            // Reset progress to level 1 for the new student name
            localStorage.removeItem('pilahpintar_quiz_progress');

            submitScoreToBackend(studentName, studentClass, 0);

            showMainGameArea();
        }
    }

    function logoutStudent() {
        if (confirm('Ganti akun siswa? Progress kamu saat ini tidak akan dihapus.')) {
            localStorage.removeItem('pilahpintar_student_name');
            localStorage.removeItem('pilahpintar_student_class');
            showRegistrationScreen();
        }
    }

    // PROGRESS MANAGEMENT
    function getProgress() {
        const saved = localStorage.getItem('pilahpintar_quiz_progress');
        return saved ? JSON.parse(saved) : { unlockedLevel: 1, levelScores: {} };
    }

    function saveProgress(unlockedLevel, level, score) {
        let progress = getProgress();
        if (unlockedLevel > progress.unlockedLevel) {
            progress.unlockedLevel = unlockedLevel;
        }
        progress.levelScores[level] = Math.max(progress.levelScores[level] || 0, score);
        localStorage.setItem('pilahpintar_quiz_progress', JSON.stringify(progress));
        loadUserProgress();

        let totalScore = 0;
        for (let i = 1; i <= 5; i++) {
            totalScore += (progress.levelScores[i] || 0);
        }
        if (studentName && studentClass) {
            submitScoreToBackend(studentName, studentClass, totalScore);
        }
    }

    function resetProgress() {
        if (confirm('Apakah kamu yakin ingin mereset progress kuis?')) {
            localStorage.removeItem('pilahpintar_quiz_progress');
            loadUserProgress();

            if (studentName && studentClass) {
                submitScoreToBackend(studentName, studentClass, 0);
            }
        }
    }

    function loadUserProgress() {
        const progress = getProgress();
        const unlockedLvl = progress.unlockedLevel;

        document.getElementById('dashLevel').innerText = unlockedLvl;

        // Calculate and show total high score
        let totalScore = 0;
        for (let i = 1; i <= 5; i++) {
            totalScore += (progress.levelScores[i] || 0);
        }
        document.getElementById('dashHighScore').innerText = totalScore;

        for (let i = 1; i <= 5; i++) {
            const card = document.getElementById(`levelCard-${i}`);
            const badge = document.getElementById(`levelBadge-${i}`);
            const status = document.getElementById(`levelStatus-${i}`);
            const playBtn = document.getElementById(`playBtn-${i}`);

            if (i <= unlockedLvl) {
                card.classList.remove('locked');
                card.classList.add('unlocked');
                badge.className = 'badge badge-level bg-success text-white';
                badge.innerHTML = '✨ Terbuka';
                playBtn.disabled = false;

                const scoreLvl = progress.levelScores[i];
                if (scoreLvl !== undefined) {
                    status.innerHTML = `Nilai Tertinggi: <strong class="text-success">${scoreLvl}</strong>`;
                } else {
                    status.innerHTML = `<span class="text-primary">Siap Dimainkan!</span>`;
                }
            } else {
                card.classList.remove('unlocked');
                card.classList.add('locked');
                badge.className = 'badge badge-level bg-secondary text-white';
                badge.innerHTML = '🔒 Terkunci';
                playBtn.disabled = true;
                status.innerHTML = `Luluskan Level ${i-1} Dulu`;
            }
        }

        // Show certificate claim if Level 5 cleared
        const certBanner = document.getElementById('certClaimBanner');
        if (progress.levelScores[5] && progress.levelScores[5] >= 80) {
            certBanner.style.display = 'block';
        } else {
            certBanner.style.display = 'none';
        }
    }

    // GAME CONTROLLER
    function startLevel(lvl) {
        currentLevel = lvl;
        score = 0;

        document.getElementById('levelSelectionScreen').style.display = 'none';
        document.getElementById('resultScreen').style.display = 'none';
        document.getElementById('leaderboardSection').style.display = 'none';

        if (lvl === 2 || lvl === 4) {
            // Start Mini-Game Sorting
            startMiniGame(lvl);
        } else {
            // Start Multiple Choice Quiz
            startMultipleChoice(lvl);
        }
    }

    // MULTIPLE CHOICE QUIZ LOGIC (LEVEL 1, 3, 5)
    function startMultipleChoice(lvl) {
        quizQuestions = rawQuestions[lvl] || [];
        if (quizQuestions.length === 0) {
            alert('Belum ada soal untuk level ini.');
            backToLevels();
            return;
        }

        currentQuestionIndex = 0;
        document.getElementById('gameplayScreen').style.display = 'block';
        document.getElementById('activeLevelTitle').innerText = `Level ${lvl} - Kuis`;
        
        renderQuestion();
    }

    function renderQuestion() {
        const q = quizQuestions[currentQuestionIndex];
        document.getElementById('questionNum').innerText = currentQuestionIndex + 1;
        document.getElementById('questionText').innerText = q.question_text;

        const progressPercent = (currentQuestionIndex / 5) * 100;
        document.getElementById('quizProgressBar').style.width = `${progressPercent}%`;

        document.getElementById('explanationBox').style.display = 'none';
        document.getElementById('nextQuestionBtn').style.display = 'none';

        // Set visual emojis based on question content
        const visualBox = document.getElementById('questionVisual');
        if (q.question_text.includes('Organik')) {
            visualBox.innerText = '🥬🍏';
        } else if (q.question_text.includes('Anorganik') || q.question_text.includes('plastik')) {
            visualBox.innerText = '🧴🥤';
        } else if (q.question_text.includes('B3') || q.question_text.includes('baterai')) {
            visualBox.innerText = '🔋💡';
        } else if (q.question_text.includes('3R') || q.question_text.includes('Daur Ulang')) {
            visualBox.innerText = '🔄 pot';
            visualBox.innerHTML = '🔄🏺';
        } else {
            visualBox.innerText = '❓♻️';
        }

        const optionsContainer = document.getElementById('optionsContainer');
        optionsContainer.innerHTML = '';

        const options = [
            { key: 'A', text: q.option_a },
            { key: 'B', text: q.option_b },
            { key: 'C', text: q.option_c },
            { key: 'D', text: q.option_d }
        ];

        options.forEach(opt => {
            const btn = document.createElement('button');
            btn.className = 'option-btn d-flex align-items-center gap-3';
            btn.innerHTML = `<span class="badge bg-secondary rounded-circle px-2 py-1">${opt.key}</span> <span>${opt.text}</span>`;
            btn.onclick = () => selectOption(opt.key, q.correct_option, q.explanation, btn);
            optionsContainer.appendChild(btn);
        });
    }

    // SELECT OPTION
    function selectOption(selectedKey, correctKey, explanation, clickedBtn) {
        const btns = document.querySelectorAll('.option-btn');
        btns.forEach(b => b.disabled = true);

        const expBox = document.getElementById('explanationBox');
        const feedbackTitle = document.getElementById('feedbackTitle');
        const explanationText = document.getElementById('explanationText');

        if (selectedKey === correctKey) {
            playSound('correct');
            clickedBtn.classList.add('selected-correct');
            score += 20; // 5 questions = 20 points each

            expBox.className = 'p-3 rounded-3 mb-4 bg-success bg-opacity-10 text-success border border-success border-opacity-25';
            feedbackTitle.innerText = '✅ Benar! Hebat!';
        } else {
            playSound('wrong');
            clickedBtn.classList.add('selected-wrong');
            btns.forEach(b => {
                if (b.innerText.includes(correctKey)) {
                    b.classList.add('selected-correct');
                }
            });

            expBox.className = 'p-3 rounded-3 mb-4 bg-danger bg-opacity-10 text-danger border border-danger border-opacity-25';
            feedbackTitle.innerText = '❌ Kurang tepat, ayo pelajari!';
        }

        explanationText.innerText = explanation || 'Cermati petunjuk pengelolaan sampah!';
        expBox.style.display = 'block';
        document.getElementById('nextQuestionBtn').style.display = 'block';
    }

    function nextQuestion() {
        currentQuestionIndex++;
        if (currentQuestionIndex < 5) {
            renderQuestion();
        } else {
            finishLevel();
        }
    }

    // INTERACTIVE MINI-GAME LOGIC (LEVEL 2 & 4)
    function startMiniGame(lvl) {
        document.getElementById('miniGameScreen').style.display = 'block';
        document.getElementById('gameLevelTitle').innerText = `Level ${lvl} - Game Memilah`;
        
        gameItemsList = (lvl === 2) ? [...level2GameItems] : [...level4GameItems];
        
        // Show/Hide B3 bucket based on level
        const b3Col = document.getElementById('b3BucketCol');
        if (lvl === 4) {
            b3Col.style.display = 'block';
        } else {
            b3Col.style.display = 'none';
        }

        gameCurrentIndex = 0;
        gameIncorrectAttempts = 0;

        document.getElementById('gameExplanationBox').style.display = 'none';
        renderGameItem();
    }

    function renderGameItem() {
        document.getElementById('gameExplanationBox').style.display = 'none';
        
        const item = gameItemsList[gameCurrentIndex];
        document.getElementById('gameItemsLeft').innerText = gameItemsList.length - gameCurrentIndex;
        document.getElementById('gameEmojiDisplay').innerText = item.emoji;
        document.getElementById('gameItemName').innerText = item.name;

        // Reset anim classes
        const display = document.getElementById('gameItemDisplay');
        display.className = 'game-item-display';
    }

    function throwItem(selectedType) {
        const item = gameItemsList[gameCurrentIndex];
        const display = document.getElementById('gameItemDisplay');
        
        const feedbackBox = document.getElementById('gameExplanationBox');
        const feedbackTitle = document.getElementById('gameFeedbackTitle');
        const feedbackText = document.getElementById('gameExplanationText');

        if (selectedType === item.type) {
            playSound('correct');
            display.classList.add('success-pulse');
            score += 20;

            feedbackBox.className = 'p-3 rounded-3 mt-4 bg-success bg-opacity-10 text-success border border-success border-opacity-25';
            feedbackTitle.innerText = '🎉 Tepat Sekali!';
            feedbackText.innerText = item.desc;
            feedbackBox.style.display = 'block';

            // Advance automatically after 1.8 seconds
            setTimeout(() => {
                gameCurrentIndex++;
                if (gameCurrentIndex < gameItemsList.length) {
                    renderGameItem();
                } else {
                    finishLevel();
                }
            }, 1800);
        } else {
            playSound('wrong');
            display.classList.add('shake-animation');
            
            // Deduct points slightly if they fail
            score = Math.max(0, score - 5);

            feedbackBox.className = 'p-3 rounded-3 mt-4 bg-danger bg-opacity-10 text-danger border border-danger border-opacity-25';
            feedbackTitle.innerText = '❌ Salah Masuk Rumah!';
            feedbackText.innerText = `Ingat, ${item.name} adalah sampah ${item.type}. Coba lagi ya!`;
            feedbackBox.style.display = 'block';

            setTimeout(() => {
                display.classList.remove('shake-animation');
            }, 500);
        }
    }

    // LEVEL COMPLETE & FINISH
    function finishLevel() {
        document.getElementById('gameplayScreen').style.display = 'none';
        document.getElementById('miniGameScreen').style.display = 'none';
        document.getElementById('resultScreen').style.display = 'block';

        score = Math.min(100, Math.max(0, score));
        document.getElementById('resultScore').innerText = score;

        const isPassed = score >= 80; // Passing score 80% (equivalent to 4 out of 5 correct)
        const statusBadge = document.getElementById('resultStatusBadge');
        const emoji = document.getElementById('resultEmoji');
        const title = document.getElementById('resultTitle');

        if (isPassed) {
            emoji.innerText = '🎉🏆';
            title.innerText = `Selamat! Level ${currentLevel} Tuntas!`;
            statusBadge.className = 'badge bg-success px-3 py-2 rounded-pill fs-6';
            statusBadge.innerText = 'LULUS ✨';

            // Unlock next level
            const nextLvl = Math.min(5, currentLevel + 1);
            saveProgress(nextLvl, currentLevel, score);
        } else {
            emoji.innerText = '💪😅';
            title.innerText = `Belum Lulus Level ${currentLevel}`;
            statusBadge.className = 'badge bg-danger px-3 py-2 rounded-pill fs-6';
            statusBadge.innerText = 'BELUM LULUS (Minimal Skor 80)';
        }
    }

    function backToLevels() {
        document.getElementById('resultScreen').style.display = 'none';
        document.getElementById('levelSelectionScreen').style.display = 'block';
        document.getElementById('leaderboardSection').style.display = 'flex';
        loadUserProgress();
    }

    function retryCurrentLevel() {
        startLevel(currentLevel);
    }

    function quitQuiz() {
        if (confirm('Apakah kamu ingin keluar dari kuis? Progress level ini tidak disimpan.')) {
            backToLevels();
        }
    }

    // CERTIFICATE CLAIM CONTROL
    function openCertificateModal() {
        document.getElementById('certDisplayName').innerText = studentName;
        document.getElementById('certDisplayClass').innerText = studentClass;

        const modal = new bootstrap.Modal(document.getElementById('certificateModal'));
        modal.show();
    }

    // LEADERBOARD AJAX SYNC
    function submitScoreToBackend(name, studentClass, score) {
        fetch('<?php echo e(route("quiz.submit-score")); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
            },
            body: JSON.stringify({
                name: name,
                class: studentClass,
                score: score
            })
        })
        .then(response => response.json())
        .then(data => {
            console.log('Score synced with database:', data);
            loadLeaderboard();
        })
        .catch(error => console.error('Error syncing score:', error));
    }

    function loadLeaderboard() {
        fetch('<?php echo e(route("quiz.leaderboard")); ?>')
        .then(response => response.json())
        .then(data => {
            const tbody = document.getElementById('leaderboardBody');
            tbody.innerHTML = '';

            if (data.length === 0) {
                tbody.innerHTML = `<tr><td colspan="4" class="text-muted py-3">Belum ada data nilai tertinggi. Jadilah yang pertama! 🏆</td></tr>`;
                return;
            }

            data.forEach((item, index) => {
                const tr = document.createElement('tr');
                
                let badgeClass = 'bg-secondary';
                let rankLabel = index + 1;
                if (index === 0) {
                    badgeClass = 'bg-warning text-dark';
                    rankLabel = '👑 1';
                } else if (index === 1) {
                    badgeClass = 'bg-light text-dark border';
                    rankLabel = '🥈 2';
                } else if (index === 2) {
                    badgeClass = 'bg-danger-subtle text-danger-emphasis';
                    rankLabel = '🥉 3';
                }

                tr.innerHTML = `
                    <td><span class="badge ${badgeClass} rounded-pill px-3 py-1 font-heading fs-6">${rankLabel}</span></td>
                    <td class="fw-bold text-dark">${escapeHtml(item.name)}</td>
                    <td class="text-muted">${escapeHtml(item.class)}</td>
                    <td><strong class="text-success">${item.score} / 500</strong></td>
                `;
                tbody.appendChild(tr);
            });
        })
        .catch(error => {
            console.error('Error loading leaderboard:', error);
            document.getElementById('leaderboardBody').innerHTML = `<tr><td colspan="4" class="text-danger py-3">Gagal memuat papan peringkat.</td></tr>`;
        });
    }

    function escapeHtml(text) {
        return text
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\ProkerKKN\resources\views/quiz/index.blade.php ENDPATH**/ ?>