<?php
require_once '../includes/init.php';

$user = new User($pdo);
if (!$user->isLoggedIn() || $user->isAdmin()) {
    header("Location: ../index.php");
    exit;
}

if (!isset($_GET['exam_id'])) {
    header("Location: dashboard.php");
    exit;
}

$exam_id = $_GET['exam_id'];
$user_id = $_SESSION['user_id'];

// Verify Assignment and Status
$stmt = null;
try {
    $stmt = $pdo->prepare("
        SELECT e.*, s.name as subject_name 
        FROM exams e
        JOIN exam_assignments ea ON e.exam_id = ea.exam_id
        JOIN subjects s ON e.subject_id = s.subject_id
        WHERE e.exam_id = ? AND ea.user_id = ?
          AND (
            (e.start_at IS NULL OR NOW() >= e.start_at)
            AND (e.end_at IS NULL OR NOW() <= e.end_at)
          )
    ");
    $stmt->execute([$exam_id, $user_id]);
} catch (PDOException $ex) {
    $stmt = $pdo->prepare("
        SELECT e.*, s.name as subject_name 
        FROM exams e
        JOIN exam_assignments ea ON e.exam_id = ea.exam_id
        JOIN subjects s ON e.subject_id = s.subject_id
        WHERE e.exam_id = ? AND ea.user_id = ? AND e.status = 'active'
    ");
    $stmt->execute([$exam_id, $user_id]);
}
$exam = $stmt->fetch();

if (!$exam) {
    die("Access Denied: This exam is not available for you.");
}

try {
    $stmtLog = $pdo->prepare("INSERT INTO student_activity_log (user_id, activity, exam_id) VALUES (?, ?, ?)");
    $stmtLog->execute([$user_id, 'exam_enter', $exam_id]);
} catch(Exception $e) {}

// Enforce per-student scheduled slot if exists
try {
    $stmtSched = $pdo->prepare("SELECT slot_start, slot_end FROM student_exam_schedule WHERE exam_id = ? AND user_id = ?");
    $stmtSched->execute([$exam_id, $user_id]);
    $sched = $stmtSched->fetch();
    if ($sched) {
        $now = new DateTime();
        $slotStart = new DateTime($sched['slot_start']);
        $slotEnd = new DateTime($sched['slot_end']);
        if ($now < $slotStart || $now > $slotEnd) {
        }
    }
} catch (Exception $e) { /* ignore */ }

// Check attempts
$stmt = $pdo->prepare("SELECT COUNT(*) FROM results WHERE user_id = ? AND exam_id = ?");
$stmt->execute([$user_id, $exam_id]);
$attempts_taken = $stmt->fetchColumn();

$allowed = $exam['allowed_attempts'] ?? 1;
if ($attempts_taken >= $allowed) {
    header("Location: result_slip.php?exam_id=$exam_id"); 
    exit;
}

// Initialize Exam Session
if (!isset($_SESSION['exam_session']) || $_SESSION['exam_session']['id'] != $exam_id) {
    // Load Questions with Passage and Media data
    $order_clause = $exam['randomize_questions'] ? "ORDER BY RAND()" : "ORDER BY question_id ASC";
    $conditions = ["q.subject_id = ?"];
    $params = [$exam['subject_id']];
    if (!empty($exam['class_id'])) {
        $conditions[] = "q.class_id = ?";
        $params[] = $exam['class_id'];
    }
    if (!empty($exam['session'])) {
        $conditions[] = "q.session = ?";
        $params[] = $exam['session'];
    }
    if (!empty($exam['term'])) {
        $conditions[] = "q.term = ?";
        $params[] = $exam['term'];
    }

    // Apply Quota if set
    $limit_clause = "";
    if (!empty($exam['question_quota']) && $exam['question_quota'] > 0) {
        $limit_clause = " LIMIT " . (int)$exam['question_quota'];
    }

    $sql = "SELECT q.*, p.content as passage_content, p.title as passage_title, m.file_path as media_path 
            FROM questions q 
            LEFT JOIN passages p ON q.passage_id = p.passage_id 
            LEFT JOIN media_library m ON q.media_id = m.media_id 
            WHERE " . implode(" AND ", $conditions) . " $order_clause $limit_clause";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $questions = $stmt->fetchAll();

    $_SESSION['exam_session'] = [
        'id' => $exam_id,
        'start_time' => time(),
        'duration' => $exam['duration'] * 60,
        'questions' => $questions
    ];
}

$questions = $_SESSION['exam_session']['questions'];
$elapsed = time() - $_SESSION['exam_session']['start_time'];
$remaining = $_SESSION['exam_session']['duration'] - $elapsed;

if ($remaining <= 0) {
    // Auto submit logic handled by JS or on post
    $remaining = 0;
}

// Handle Submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $score = 0;
    $total = count($questions);
    
    foreach ($questions as $q) {
        $qid = $q['question_id'];
        if (isset($_POST['q_' . $qid]) && $_POST['q_' . $qid] == $q['correct_answer']) {
            $score++;
        }
    }

    // Save Result
    $stmt = $pdo->prepare("INSERT INTO results (user_id, exam_id, score, total_questions) VALUES (?, ?, ?, ?)");
    $stmt->execute([$user_id, $exam_id, $score, $total]);
    
    // Clear Session
    unset($_SESSION['exam_session']);
    
    if (!empty($exam['show_result_to_student'])) {
        header("Location: result_slip.php?exam_id=$exam_id");
    } else {
        header("Location: dashboard.php?completed=1");
    }
    exit;
}

// Get User Info for Display
$stmtUser = $pdo->prepare("SELECT full_name, username FROM users WHERE user_id = ?");
$stmtUser->execute([$user_id]);
$currentUser = $stmtUser->fetch();
$displayName = $currentUser['full_name'] ?: $currentUser['username'];
$passport = 'https://ui-avatars.com/api/?name='.urlencode($displayName).'&background=random';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exam: <?php echo htmlspecialchars($exam['title']); ?></title>
    <style>
        :root {
            --primary: #2563eb;
            --secondary: #64748b;
            --success: #22c55e;
            --danger: #ef4444;
            --bg: #f8fafc;
            --card: #ffffff;
            --border: #e2e8f0;
        }
        * { box-sizing: border-box; }
        body { 
            margin: 0; 
            height: 100vh; 
            display: flex; 
            flex-direction: column; 
            font-family: 'Segoe UI', system-ui, sans-serif; 
            background: var(--bg); 
            color: #1e293b;
            overflow: hidden;
        }
        
        /* Header */
        .cbt-header {
            height: 60px;
            background: #1e293b;
            color: white;
            display: flex;
            align-items: center;
            padding: 0 24px;
            justify-content: space-between;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            z-index: 10;
        }
        .brand { font-size: 1.5rem; font-weight: 800; letter-spacing: -1px; }
        .exam-info { text-align: right; font-size: 0.9rem; color: #94a3b8; }
        .exam-info strong { color: white; display: block; font-size: 1rem; }

        /* Layout */
        .cbt-container {
            flex: 1;
            display: flex;
            overflow: hidden;
        }
        
        /* Left: Main Content */
        .cbt-main {
            flex: 1;
            padding: 24px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            max-width: 100%;
        }
        
        /* Right: Sidebar */
        .cbt-sidebar {
            width: 320px;
            background: white;
            border-left: 1px solid var(--border);
            display: flex;
            flex-direction: column;
            box-shadow: -2px 0 10px rgba(0,0,0,0.05);
        }

        /* Question Card */
        .question-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);
            padding: 32px;
            flex: 1;
            overflow-y: auto;
            margin-bottom: 20px;
        }
        .stem-block { max-height: 40vh; overflow-y: auto; padding-right: 8px; }
        .q-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 24px;
            padding-bottom: 16px;
            border-bottom: 2px solid var(--bg);
        }
        .q-number { font-size: 1.1rem; font-weight: 700; color: var(--primary); }
        .q-marks { font-size: 0.9rem; color: var(--secondary); font-weight: 600; }
        
        .q-content { font-size: 1.05rem; line-height: 1.5; margin-bottom: 16px; overflow-x: auto; }
        .q-content img { max-width: 100%; height: auto; display: block; margin: 10px 0; }
        .q-content table { width: 100%; border-collapse: collapse; margin: 10px 0; }
        .q-content th, .q-content td { border: 1px solid #cbd5e1; padding: 8px; text-align: left; }
        .q-image { max-width: 100%; max-height: 400px; border-radius: 8px; margin: 16px 0; border: 1px solid var(--border); display: block; }
        
        .preset-compact .q-content { line-height: 1.35; font-size: 1rem; }
        .preset-compact .options-grid { gap: 6px; }
        .preset-compact .option-item { padding: 10px; }
        .preset-compact .stem-block { max-height: 38vh; }
        
        .preset-reading .q-content { line-height: 1.8; font-size: 1.1rem; }
        .preset-reading .option-item { padding: 16px; }
        .preset-reading .stem-block { max-height: 52vh; }
        
        /* Options */
        .options-grid { display: flex; flex-direction: column; gap: 10px; }
        .option-item {
            display: flex;
            align-items: center;
            padding: 14px;
            border: 2px solid var(--border);
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s;
        }
        .option-item:hover { background: #f1f5f9; border-color: #cbd5e1; }
        .option-item.selected { 
            background: #eff6ff; 
            border-color: var(--primary); 
            box-shadow: 0 0 0 1px var(--primary);
        }
        .radio-custom {
            width: 20px;
            height: 20px;
            border: 2px solid #cbd5e1;
            border-radius: 50%;
            margin-right: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }
        .option-item.selected .radio-custom {
            border-color: var(--primary);
        }
        .option-item.selected .radio-custom::after {
            content: '';
            width: 10px;
            height: 10px;
            background: var(--primary);
            border-radius: 50%;
        }
        .opt-key { width: 26px; height: 26px; border-radius: 6px; background: #e2e8f0; color: #334155; display: inline-flex; align-items: center; justify-content: center; font-weight: 700; margin-right: 12px; flex-shrink: 0; }
        .option-item.selected .opt-key { background: #dbeafe; color: var(--primary); }
        .opt-text { font-weight: 500; }

        /* Navigation */
        .nav-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            position: sticky;
            bottom: 0;
            background: white;
            border-top: 1px solid var(--border);
            z-index: 5;
        }
        .btn {
            padding: 12px 24px;
            border-radius: 8px;
            border: none;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: opacity 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .btn:active { transform: translateY(1px); }
        .btn-prev { background: #e2e8f0; color: #475569; }
        .btn-next { background: var(--primary); color: white; }
        .btn-next:hover { opacity: 0.9; }

        /* Sidebar Elements */
        .timer-display {
            background: #fee2e2;
            color: #b91c1c;
            padding: 20px;
            text-align: center;
            font-size: 2rem;
            font-weight: 800;
            font-family: 'Courier New', monospace;
            border-bottom: 1px solid #fecaca;
        }
        .timer-label { font-size: 0.8rem; text-transform: uppercase; letter-spacing: 1px; color: #ef4444; display: block; margin-bottom: 4px; }
        
        .user-profile {
            padding: 20px;
            text-align: center;
            border-bottom: 1px solid var(--border);
            background: #f8fafc;
        }
        .user-avatar { width: 64px; height: 64px; border-radius: 50%; object-fit: cover; border: 3px solid white; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 8px; }
        .user-name { font-weight: 700; font-size: 0.95rem; color: #334155; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

        .grid-wrapper {
            flex: 1;
            padding: 16px;
            overflow-y: auto;
        }
        .question-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 8px;
        }
        .q-btn {
            aspect-ratio: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid var(--border);
            border-radius: 6px;
            background: white;
            font-weight: 600;
            font-size: 0.9rem;
            cursor: pointer;
            color: #64748b;
        }
        .q-btn:hover { border-color: var(--primary); color: var(--primary); }
        .q-btn.current { border-color: var(--primary); color: var(--primary); background: #eff6ff; box-shadow: inset 0 0 0 1px var(--primary); }
        .q-btn.answered { background: var(--success); color: white; border-color: var(--success); }
        .q-btn.current.answered { border-color: #15803d; box-shadow: inset 0 0 0 2px white; }

        .submit-area { padding: 16px; border-top: 1px solid var(--border); }
        .btn-submit { width: 100%; background: var(--danger); color: white; padding: 16px; font-size: 1.1rem; }

        /* Legend */
        .legend { display: flex; gap: 12px; justify-content: center; font-size: 0.75rem; margin-bottom: 16px; color: #64748b; }
        .legend-item { display: flex; align-items: center; gap: 4px; }
        .dot { width: 8px; height: 8px; border-radius: 50%; }

        /* Confirm Modal */
        .modal-backdrop {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.5); backdrop-filter: blur(2px);
            display: none; align-items: center; justify-content: center; z-index: 1000;
        }
        .modal-backdrop.active { display: flex; animation: fadeIn 0.2s ease-out; }
        .modal {
            background: white; padding: 32px; border-radius: 16px;
            width: 90%; max-width: 400px; text-align: center;
            box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1);
            transform: scale(0.95); transition: transform 0.2s;
        }
        .modal-backdrop.active .modal { transform: scale(1); }
        
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }

        /* Responsive */
        @media (max-width: 768px) {
            .cbt-container { flex-direction: column; }
            .cbt-sidebar { 
                width: 100%; 
                height: auto; 
                flex-direction: row; 
                flex-wrap: wrap; 
                order: -1; 
                border-left: none; 
                border-bottom: 1px solid var(--border);
                align-items: center;
                padding: 8px;
            }
            .timer-display { padding: 8px 16px; font-size: 1.5rem; border: none; background: transparent; flex: 1; text-align: right; }
            .timer-label { display: none; }
            .user-profile { display: none; }
            .grid-wrapper { display: none; /* Hide grid on mobile to save space, maybe add a toggle later */ }
            .submit-area { display: none; /* Move submit to main area or nav */ }
            .cbt-header { padding: 0 16px; }
            .brand { font-size: 1.2rem; }
            .cbt-main { padding: 16px; }
            .question-card { padding: 20px; margin-bottom: 80px; /* Space for fixed nav */ }
            
            /* Mobile Nav */
            .nav-footer { 
                position: fixed; bottom: 0; left: 0; right: 0; 
                background: white; padding: 16px; 
                box-shadow: 0 -4px 6px -1px rgba(0,0,0,0.1); 
                z-index: 50;
            }
        }
    </style>
</head>
<body class="<?php echo ($exam['layout_preset'] === 'reading') ? 'preset-reading' : 'preset-compact'; ?>">

    <!-- Header -->
    <header class="cbt-header">
        <div class="brand-group" style="display:flex; flex-direction:column; justify-content:center;">
            <div class="brand" style="line-height:1; margin-bottom:2px;">FGV</div>
            <div style="font-size:0.75rem; font-weight:400; opacity:0.8; letter-spacing:0.5px;">Your CBT Companion</div>
        </div>
        <div class="exam-info">
            <strong><?php echo htmlspecialchars($exam['title']); ?></strong>
            <?php echo htmlspecialchars($exam['subject_name']); ?>
            <div style="margin-top:4px; font-size:0.8rem;">
                Attempted: <span id="attemptedCountHeader">0</span> / <?php echo count($questions); ?>
            </div>
        </div>
    </header>

    <div class="cbt-container">
        
        <!-- Sidebar (Right) -->
        <aside class="cbt-sidebar">
            <div class="timer-display">
                <span class="timer-label">Time Remaining</span>
                <span id="timerDisplay">00:00</span>
            </div>
            
            <div class="user-profile">
                <img src="<?php echo $passport; ?>" alt="User" class="user-avatar">
                <div class="user-name"><?php echo htmlspecialchars($displayName); ?></div>
                <div style="font-size: 0.8rem; color: #64748b; margin-top: 4px;">ID: <?php echo htmlspecialchars($currentUser['username']); ?></div>
            </div>

            <div class="grid-wrapper">
                <div class="legend">
                    <div class="legend-item"><span class="dot" style="background:#22c55e;"></span> Answered</div>
                    <div class="legend-item"><span class="dot" style="background:white; border:1px solid #cbd5e1;"></span> Pending</div>
                </div>
                <div class="question-grid" id="questionGrid">
                    <!-- JS generated -->
                </div>
            </div>

            <div class="submit-area">
                <button type="button" class="btn btn-submit" id="sidebarSubmitBtn">Submit Exam</button>
            </div>
        </aside>

        <!-- Main Content (Left) -->
        <main class="cbt-main">
            <form method="POST" id="examForm">
                <?php foreach ($questions as $index => $q): ?>
                <div class="question-card" id="q-card-<?php echo $index; ?>" style="<?php echo $index === 0 ? '' : 'display:none;'; ?>">
                    <div class="q-header">
                        <div class="q-number">Question <?php echo $index + 1; ?> of <?php echo count($questions); ?></div>
                        <div class="q-marks">2 Marks</div>
                    </div>

                    <div class="stem-block">
                        <?php if (!empty($q['passage_content'])): ?>
                            <div class="passage" style="background:#f1f5f9; padding:16px; border-radius:8px; margin-bottom:12px; border-left: 4px solid var(--primary);">
                                <h4 style="margin-top:0; margin-bottom:8px; color:var(--primary); font-size:0.9rem; text-transform:uppercase; letter-spacing:1px;">Passage / Instruction</h4>
                                <div style="font-size:1rem; line-height:1.6;">
                                    <?php echo $q['passage_content']; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                        <div class="q-content">
                            <?php echo $q['question_text']; ?>
                        </div>
                        <?php if ($q['image_path']): ?>
                            <img src="../<?php echo $q['image_path']; ?>" class="q-image" alt="Question Image">
                        <?php endif; ?>
                        <?php if (!empty($q['media_id'])): 
                             $ms = $pdo->prepare("SELECT file_path FROM media_library WHERE media_id = ?");
                             $ms->execute([$q['media_id']]);
                             $mf = $ms->fetch();
                             if ($mf) echo '<img src="../'.htmlspecialchars($mf['file_path']).'" class="q-image" alt="Media">';
                        endif; ?>
                    </div>

                    <div class="options-grid">
                        <?php 
                        $opts = ['A'=>$q['option_a'], 'B'=>$q['option_b'], 'C'=>$q['option_c'], 'D'=>$q['option_d']];
                        if(!empty($q['option_e'])) $opts['E'] = $q['option_e'];
                        
                        foreach($opts as $key => $val): 
                        ?>
                        <label class="option-item" onclick="selectOption(this, <?php echo $index; ?>)">
                            <div class="radio-custom"></div>
                            <input type="radio" name="q_<?php echo $q['question_id']; ?>" value="<?php echo $key; ?>" style="display:none;">
                            <span class="opt-key"><?php echo $key; ?></span>
                            <span class="opt-text"><?php echo $val; ?></span>
                        </label>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </form>

            <div class="nav-footer">
                <button type="button" class="btn btn-prev" id="prevBtn" disabled>Previous (P)</button>
                
                <!-- Mobile Submit (Visible only on mobile via CSS) -->
                <button type="button" class="btn btn-submit" id="mobileSubmitBtn" style="display:none; width:auto; padding:10px 20px; font-size:0.9rem;">Submit (S)</button>

                <button type="button" class="btn btn-next" id="nextBtn">Next (N) &rarr;</button>
            </div>
        </main>
    </div>

    <!-- Confirm Modal -->
    <div class="modal-backdrop" id="confirmModal">
        <div class="modal">
            <h2 style="margin-top:0;">Submit Exam?</h2>
            <p style="color:#64748b; margin-bottom:24px;">You have attempted <strong id="attemptCount">0</strong> out of <strong><?php echo count($questions); ?></strong> questions.</p>
            <div style="display:flex; gap:12px;">
                <button class="btn btn-prev" style="flex:1; justify-content:center;" onclick="closeModal()">Cancel</button>
                <button class="btn btn-next" style="flex:1; background:var(--danger); justify-content:center;" onclick="submitExam()">Yes, Submit</button>
            </div>
        </div>
    </div>

    <script>
        // State
        const totalQuestions = <?php echo count($questions); ?>;
        let currentIndex = 0;
        let timeRemaining = <?php echo $remaining; ?>;
        
        // Timer Logic
        function updateTimer() {
            if (timeRemaining < 0) timeRemaining = 0;
            
            const hours = Math.floor(timeRemaining / 3600);
            const minutes = Math.floor((timeRemaining % 3600) / 60);
            const seconds = timeRemaining % 60;
            
            let display = '';
            if (hours > 0) {
                display += hours.toString().padStart(2, '0') + ':';
            }
            display += minutes.toString().padStart(2, '0') + ':';
            display += seconds.toString().padStart(2, '0');
            
            const el = document.getElementById('timerDisplay');
            if(el) {
                el.innerText = display;
                // Visual alert for low time (last 5 mins)
                if(timeRemaining < 300) {
                    el.style.color = '#dc2626';
                    el.parentElement.style.backgroundColor = '#fef2f2';
                    el.parentElement.style.borderColor = '#fecaca';
                }
            }
            
            if (timeRemaining <= 0) {
                submitExam();
            } else {
                timeRemaining--;
                setTimeout(updateTimer, 1000);
            }
        }
        
        // Navigation Logic
        function showQuestion(index) {
            // Hide all
            document.querySelectorAll('.question-card').forEach(el => el.style.display = 'none');
            // Show current
            document.getElementById('q-card-' + index).style.display = 'block';
            
            // Update Buttons
            document.getElementById('prevBtn').disabled = index === 0;
            const nextBtn = document.getElementById('nextBtn');
            if (index === totalQuestions - 1) {
                nextBtn.innerHTML = 'Finish';
                nextBtn.style.backgroundColor = '#22c55e'; // Green for finish
            } else {
                nextBtn.innerHTML = 'Next Question &rarr;';
                nextBtn.style.backgroundColor = ''; // Reset
            }
            
            currentIndex = index;
            updateGridUI();
        }

        function nextQuestion() {
            if (currentIndex < totalQuestions - 1) {
                showQuestion(currentIndex + 1);
            } else {
                openModal();
            }
        }

        function prevQuestion() {
            if (currentIndex > 0) {
                showQuestion(currentIndex - 1);
            }
        }

        // Selection Logic
        function selectOption(labelEl, qIndex) {
            const card = document.getElementById('q-card-' + qIndex);
            card.querySelectorAll('.option-item').forEach(el => el.classList.remove('selected'));
            labelEl.classList.add('selected');
            
            const radio = labelEl.querySelector('input[type="radio"]');
            radio.checked = true;
            
            updateGridUI();
        }
        function selectByKey(letter) {
            const card = document.getElementById('q-card-' + currentIndex);
            if (!card) return;
            const labels = Array.from(card.querySelectorAll('.option-item'));
            for (const lbl of labels) {
                const k = lbl.querySelector('.opt-key');
                if (k && k.textContent.trim().toUpperCase() === letter.toUpperCase()) {
                    selectOption(lbl, currentIndex);
                    break;
                }
            }
        }

        // Grid Logic
        function initGrid() {
            const grid = document.getElementById('questionGrid');
            for(let i=0; i<totalQuestions; i++) {
                const btn = document.createElement('div');
                btn.className = 'q-btn';
                btn.innerText = i + 1;
                btn.onclick = () => showQuestion(i);
                btn.id = 'grid-btn-' + i;
                grid.appendChild(btn);
            }
            updateGridUI();
        }

        function updateGridUI() {
            for(let i=0; i<totalQuestions; i++) {
                const btn = document.getElementById('grid-btn-' + i);
                const card = document.getElementById('q-card-' + i);
                const answered = card.querySelector('input[type="radio"]:checked');
                
                btn.className = 'q-btn';
                if (i === currentIndex) btn.classList.add('current');
                if (answered) btn.classList.add('answered');
            }
            
            const answeredCount = document.querySelectorAll('input[type="radio"]:checked').length;
            document.getElementById('attemptCount').innerText = answeredCount;
            const hdr = document.getElementById('attemptedCountHeader');
            if (hdr) hdr.innerText = answeredCount;
        }

        // Modal Logic
        function openModal() {
            document.getElementById('confirmModal').classList.add('active');
        }
        function closeModal() {
            document.getElementById('confirmModal').classList.remove('active');
        }
        function submitExam() {
            document.getElementById('examForm').submit();
        }

        // Event Listeners
        document.getElementById('nextBtn').addEventListener('click', nextQuestion);
        document.getElementById('prevBtn').addEventListener('click', prevQuestion);
        document.getElementById('sidebarSubmitBtn').addEventListener('click', openModal);
        
        // Mobile special handling
        if (window.innerWidth <= 768) {
             document.getElementById('mobileSubmitBtn').style.display = 'inline-block';
             document.getElementById('mobileSubmitBtn').addEventListener('click', openModal);
        }

        // Initialize
        window.addEventListener('load', () => {
            updateTimer();
            initGrid();
        });

        // Anti-cheat
        window.onblur = function() {
            // alert("Focus on the exam!"); 
        };
        document.addEventListener('contextmenu', event => event.preventDefault());
        
        // Keyboard Shortcuts
        document.addEventListener('keydown', (e) => {
            const key = e.key.toLowerCase();
            if (key === 'arrowright') nextQuestion();
            if (key === 'arrowleft') prevQuestion();
            if (['a','b','c','d','e'].includes(key)) selectByKey(key);
            if (key === 'n') nextQuestion();
            if (key === 'p') prevQuestion();
            if (key === 's') openModal();
            if (/^[1-9]$/.test(key)) {
                const idx = parseInt(key,10) - 1;
                if (idx >= 0 && idx < totalQuestions) showQuestion(idx);
            }
            if (key === 'enter') {
                const card = document.getElementById('q-card-' + currentIndex);
                if (card && card.querySelector('input[type="radio"]:checked')) nextQuestion();
            }
        });

    </script>
</body>
</html>
