<?php
/**
 * Branch Exam — Take Page (Real-Time Exam Interface, Flawless Edition)
 *
 * Features:
 *   - One question at a time with smooth transitions
 *   - Question palette sidebar (1-2-3-4-5 grid, color-coded states)
 *   - Sticky header: exam title, BRANCH NAME, user name, language toggle, timer
 *   - Progress bar
 *   - Bilingual display: ALWAYS renders both EN + HI versions; CSS toggles visibility.
 *     Falls back to English if Hindi text is empty (no broken UI).
 *   - Mark for Review + Clear Answer per question
 *   - Submit button in TWO places: (a) inline next to Prev/Next on last question,
 *     (b) sticky bottom bar always visible. Both submit the same form.
 *   - Auto-submit on timer expiry (red blinking in last 60s)
 *   - Confirmation dialog before submit
 */
$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$exam = $exam ?? [];
$questions = $questions ?? [];
$userName = $userName ?? '';
$csrfToken = $csrfToken ?? '';

$lang = $exam['language'] ?? 'en';
$duration = (int)($exam['duration_minutes'] ?? 60);
$totalQ = count($questions);
$branchName = $exam['branch_name'] ?? ($_SESSION['branch_code'] ?? '');
$branchCode = $exam['branch_code'] ?? '';

$jsConfig = [
    'duration' => $duration,
    'totalQ' => $totalQ,
    'languageMode' => $lang,
    'basePath' => $bp,
    'examId' => (int)($exam['id'] ?? 0),
];

include __DIR__ . '/../layouts/header.php';
?>
<style>
/* ========== Real-Time Exam — Flawless Edition ========== */
* { box-sizing: border-box; }
.exam-take-section { background: linear-gradient(180deg, #f4f9f9 0%, #eaf5f5 100%); padding-bottom: 80px; min-height: 100vh; }

/* Header Bar */
.exam-header-bar {
    background: linear-gradient(135deg, #0d3b3b 0%, #16a085 100%);
    color: #ffffff; padding: 14px 24px;
    display: flex; justify-content: space-between; align-items: center;
    flex-wrap: wrap; gap: 10px;
    position: sticky; top: 0; z-index: 100;
    box-shadow: 0 4px 16px rgba(13,59,59,0.25);
}
.exam-header-left { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; flex: 1; min-width: 0; }
.exam-header-left h1 {
    font-size: 1.05rem; margin: 0; white-space: nowrap;
    max-width: 100%; overflow: hidden; text-overflow: ellipsis;
}
.exam-q-count { font-size: 0.78rem; opacity: 0.85; white-space: nowrap; }

.branch-badge {
    display: inline-flex; align-items: center; gap: 5px;
    background-color: rgba(255,255,255,0.2);
    padding: 4px 12px; border-radius: 50px;
    font-size: 0.8rem; font-weight: 600;
    border: 1px solid rgba(255,255,255,0.3);
}
.user-name-badge {
    display: inline-flex; align-items: center; gap: 4px;
    background-color: rgba(255,255,255,0.15);
    padding: 3px 12px; border-radius: 50px;
    font-size: 0.78rem; font-weight: 500;
}

.exam-header-right { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }

/* Language Toggle */
.lang-toggle { display: flex; border-radius: 6px; overflow: hidden; border: 1px solid rgba(255,255,255,0.3); }
.lang-toggle-btn {
    padding: 5px 12px; font-size: 0.78rem; background: transparent;
    color: rgba(255,255,255,0.7); border: none; cursor: pointer;
    font-family: 'Poppins', sans-serif; font-weight: 600;
    transition: background-color 0.2s;
}
.lang-toggle-btn.active { background-color: rgba(255,255,255,0.3); color: #ffffff; }
.lang-toggle-btn:hover { background-color: rgba(255,255,255,0.15); }

/* Timer */
.exam-timer {
    display: flex; align-items: center; gap: 6px;
    background-color: rgba(255,255,255,0.15);
    padding: 6px 14px; border-radius: 8px;
    font-weight: 700; font-size: 0.95rem;
    font-family: 'Courier New', monospace;
    min-width: 110px; justify-content: center;
}
.timer-warning { background-color: rgba(243,156,18,0.5) !important; }
.timer-danger { background-color: rgba(232,65,24,0.6) !important; animation: blink 0.8s infinite; }
@keyframes blink { 0%,100%{opacity:1;} 50%{opacity:0.55;} }

/* Progress Bar */
.exam-progress-wrap { position: sticky; top: 56px; z-index: 99; background: #f4f9f9; padding: 6px 0; }
.exam-progress-bar { height: 5px; background-color: #d8e8e8; border-radius: 3px; overflow: hidden; max-width: 1100px; margin: 0 auto; }
.exam-progress-fill { height: 100%; background: linear-gradient(90deg, #16a085, #1abc9c); transition: width 0.4s ease; border-radius: 3px; }

/* Layout */
.exam-layout {
    display: grid; gap: 20px; padding: 20px 24px;
    max-width: 1100px; margin: 0 auto;
}
@media (min-width: 768px) { .exam-layout { grid-template-columns: 1fr 260px; } }

.exam-main { min-width: 0; }

/* Info bar */
.exam-info-bar {
    background: #ffffff; padding: 12px 18px; border-radius: 10px;
    margin-bottom: 14px; font-size: 0.82rem; color: #444;
    display: flex; flex-wrap: wrap; gap: 18px;
    box-shadow: 0 2px 8px rgba(13,59,59,0.06);
    border-left: 4px solid #16a085;
}
.exam-info-bar strong { color: #0d3b3b; font-weight: 700; }

/* Instructions box */
.exam-instructions {
    background: #fff8e1; border-left: 4px solid #f39c12;
    padding: 12px 16px; border-radius: 8px;
    margin-bottom: 14px; font-size: 0.86rem; color: #5a4a1a;
}
.exam-instructions strong { color: #b8731a; }

/* Question card */
.exam-question {
    background: #fff; border-radius: 14px; padding: 26px 30px;
    box-shadow: 0 6px 20px rgba(13,59,59,0.08);
    display: none;
    border: 1px solid #e0e8e8;
}
.exam-question.active { display: block; animation: fadeIn 0.3s ease; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }

.question-header {
    display: flex; justify-content: space-between; align-items: center;
    margin-bottom: 16px; padding-bottom: 12px;
    border-bottom: 2px solid #f0f5f5;
}
.question-number { font-size: 0.92rem; font-weight: 700; color: #16a085; }
.question-marks {
    font-size: 0.78rem; color: #0d3b3b;
    background-color: #eafaf1; padding: 4px 12px;
    border-radius: 50px; font-weight: 700;
    border: 1px solid #b8e6d4;
}

/* Question text — English & Hindi */
.question-text {
    font-size: 1.05rem; color: #1a1a1a; line-height: 1.7;
    margin-bottom: 8px; font-weight: 600;
}
.question-text-hindi {
    font-size: 1rem; color: #555; line-height: 1.8;
    margin-bottom: 14px; padding: 10px 14px;
    background: #fff8e1; border-left: 3px solid #f39c12;
    border-radius: 4px;
    font-family: 'Noto Sans Devanagari', sans-serif;
}

/* Options */
.question-options { display: flex; flex-direction: column; gap: 10px; margin-top: 16px; }
.option-label {
    display: flex; align-items: flex-start; gap: 12px;
    padding: 14px 18px; border: 2px solid #e0e8e8;
    border-radius: 10px; cursor: pointer;
    transition: all 0.2s; background: #fff;
}
.option-label:hover { border-color: #16a085; background-color: #f4f9f9; transform: translateX(3px); }
.option-radio { margin-top: 4px; accent-color: #16a085; flex-shrink: 0; transform: scale(1.2); }
.option-text { flex: 1; min-width: 0; }
.option-text-main { font-size: 0.94rem; color: #1a1a1a; line-height: 1.5; }
.option-text-hindi {
    font-size: 0.88rem; color: #666; margin-top: 4px;
    font-family: 'Noto Sans Devanagari', sans-serif;
    padding: 4px 8px; background: #fffbe6; border-radius: 4px;
    display: inline-block;
}
.option-label.selected { border-color: #16a085; background-color: #eafaf1; box-shadow: 0 2px 8px rgba(22,160,133,0.15); }
.option-label.selected .option-text-main { color: #0d3b3b; font-weight: 600; }

/* Action buttons row (Clear + Mark for Review) */
.question-actions {
    display: flex; gap: 8px; margin-top: 16px;
    padding-top: 14px; border-top: 1px solid #f0f5f5;
    flex-wrap: wrap;
}
.btn-clear-answer {
    background: #fff5f5; color: #e84118;
    border: 1px solid #f5c6cb;
    padding: 7px 14px; border-radius: 6px;
    font-size: 0.8rem; font-weight: 600; cursor: pointer;
    font-family: 'Poppins', sans-serif; transition: all 0.2s;
}
.btn-clear-answer:hover { background: #ffe0e0; }
.btn-mark-review {
    display: inline-flex; align-items: center; gap: 4px;
    padding: 7px 14px; background: #fff8e1;
    color: #b8731a; border: 1px solid #f5d68b;
    border-radius: 6px; font-size: 0.8rem; font-weight: 600;
    cursor: pointer; font-family: 'Poppins', sans-serif;
    transition: all 0.2s;
}
.btn-mark-review:hover { background: #f39c12; color: #fff; }
.btn-mark-review.is-marked { background: #f39c12; color: #fff; }

/* Navigation buttons — INLINE, right under the question */
.exam-nav {
    display: flex; gap: 10px; justify-content: space-between;
    margin-top: 18px; flex-wrap: wrap;
    background: #fff; padding: 14px 18px;
    border-radius: 10px; box-shadow: 0 2px 8px rgba(13,59,59,0.06);
}
.exam-nav-left { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.exam-nav-right { display: flex; gap: 8px; flex-wrap: wrap; }
.btn-nav {
    padding: 11px 22px; border-radius: 8px;
    font-size: 0.88rem; font-weight: 600;
    cursor: pointer; border: none;
    font-family: 'Poppins', sans-serif;
    transition: all 0.2s;
}
.btn-prev { background: #f4f9f9; color: #0d3b3b; border: 1px solid #c8e0e0; }
.btn-prev:hover:not(:disabled) { background: #eaf5f5; }
.btn-prev:disabled { opacity: 0.4; cursor: not-allowed; }
.btn-next { background: #16a085; color: #fff; }
.btn-next:hover { background: #117a65; transform: translateY(-1px); }
.btn-submit-inline { background: #27ae60; color: #fff; }
.btn-submit-inline:hover { background: #1e8e4f; transform: translateY(-1px); }

.nav-progress-text { font-size: 0.82rem; color: #666; font-weight: 500; }
.nav-progress-text strong { color: #16a085; }

/* Question Navigator Sidebar */
.exam-sidebar { display: none; }
@media (min-width: 768px) { .exam-sidebar { display: block; position: sticky; top: 110px; align-self: start; } }
.qnav-panel { background: #fff; border-radius: 12px; padding: 18px; box-shadow: 0 4px 16px rgba(13,59,59,0.08); border: 1px solid #e0e8e8; }
.qnav-title { font-size: 0.88rem; font-weight: 700; color: #0d3b3b; margin-bottom: 12px; padding-bottom: 8px; border-bottom: 2px solid #f0f5f5; }
.qnav-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 6px; }
.qnav-btn {
    width: 100%; aspect-ratio: 1; border-radius: 8px;
    border: 1.5px solid #e0e0e0; background: #fff;
    font-size: 0.82rem; font-weight: 700; color: #666;
    cursor: pointer; transition: all 0.2s;
    display: flex; align-items: center; justify-content: center;
    position: relative;
}
.qnav-btn:hover { border-color: #16a085; transform: scale(1.05); }
.qnav-btn.active { border-color: #16a085; background: #16a085; color: #fff; }
.qnav-btn.answered { background: #eafaf1; border-color: #27ae60; color: #1e7e44; }
.qnav-btn.marked-review { background: #fff3e0; border-color: #f39c12; color: #b8731a; }
.qnav-btn.answered-marked { background: #fff3e0; border-color: #f39c12; color: #b8731a; }
.qnav-btn.answered-marked::after {
    content: ''; position: absolute; top: 3px; right: 3px;
    width: 7px; height: 7px; border-radius: 50%; background: #27ae60;
}
.qnav-legend { display: flex; flex-direction: column; gap: 7px; margin-top: 16px; font-size: 0.74rem; color: #666; }
.qnav-legend-item { display: flex; align-items: center; gap: 6px; }
.qnav-dot { width: 14px; height: 14px; border-radius: 3px; display: inline-block; border: 1.5px solid #ddd; }

/* Sticky bottom bar */
.exam-sticky-bar {
    position: fixed; bottom: 0; left: 0; right: 0; z-index: 200;
    background: #fff; border-top: 2px solid #16a085;
    padding: 10px 24px; display: flex; align-items: center;
    justify-content: space-between; gap: 12px;
    box-shadow: 0 -4px 20px rgba(0,0,0,0.08);
}
.sticky-left { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
.sticky-right { display: flex; align-items: center; gap: 8px; }
.sticky-answered-info { font-size: 0.86rem; color: #444; font-weight: 500; }
.sticky-answered-info strong { color: #16a085; font-size: 1.05rem; }
.sticky-marked-info { font-size: 0.78rem; color: #999; }
.sticky-marked-info strong { color: #f39c12; }
.btn-sticky-submit {
    display: inline-flex; align-items: center; gap: 6px;
    padding: 11px 28px; background: linear-gradient(135deg, #27ae60, #1e8e4f); color: #fff;
    border: none; border-radius: 8px; font-size: 0.92rem; font-weight: 700;
    cursor: pointer; font-family: 'Poppins', sans-serif;
    transition: all 0.2s; box-shadow: 0 4px 12px rgba(39,174,96,0.3);
}
.btn-sticky-submit:hover { transform: translateY(-2px); box-shadow: 0 6px 16px rgba(39,174,96,0.4); }

/* Responsive */
@media (max-width: 576px) {
    .exam-header-left h1 { font-size: 0.92rem; max-width: 200px; }
    .branch-badge { font-size: 0.74rem; padding: 3px 10px; }
    .user-name-badge { font-size: 0.74rem; }
    .exam-question { padding: 18px 20px; }
    .question-text { font-size: 0.98rem; }
    .btn-nav { padding: 10px 16px; font-size: 0.82rem; }
    .exam-sticky-bar { padding: 8px 14px; }
    .btn-sticky-submit { padding: 10px 18px; font-size: 0.86rem; }
}
</style>

<!-- ============================================================
     Exam Interface
     ============================================================ -->
<section class="exam-take-section" aria-label="Online Exam">
    <!-- Header Bar -->
    <div class="exam-header-bar">
        <div class="exam-header-left">
            <h1 title="<?= htmlspecialchars($exam['title'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                <?= htmlspecialchars($exam['title'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                <?php if (!empty($exam['title_hindi'])): ?>
                    <span style="font-weight:400;opacity:0.85;font-family:'Noto Sans Devanagari',sans-serif;"> · <?= htmlspecialchars($exam['title_hindi'], ENT_QUOTES, 'UTF-8') ?></span>
                <?php endif; ?>
            </h1>
            <span class="exam-q-count"><?= $totalQ ?> Qs · <?= (int)($exam['total_marks'] ?? 100) ?> marks</span>
            <?php if (!empty($branchName)): ?>
            <span class="branch-badge" title="Your branch">
                <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/></svg>
                <?= htmlspecialchars($branchName, ENT_QUOTES, 'UTF-8') ?>
                <?php if (!empty($branchCode)): ?> <small style="opacity:0.8;">(<?= htmlspecialchars($branchCode, ENT_QUOTES, 'UTF-8') ?>)</small><?php endif; ?>
            </span>
            <?php endif; ?>
            <span class="user-name-badge">
                <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 00-3-3.87"/><path d="M4 21v-2a4 4 0 013-3.87"/><circle cx="12" cy="7" r="4"/></svg>
                <?= htmlspecialchars($userName, ENT_QUOTES, 'UTF-8') ?>
            </span>
        </div>
        <div class="exam-header-right">
            <?php if ($lang === 'both'): ?>
            <div class="lang-toggle" role="group" aria-label="Language toggle">
                <button type="button" class="lang-toggle-btn active" data-lang="both">Both</button>
                <button type="button" class="lang-toggle-btn" data-lang="english">EN</button>
                <button type="button" class="lang-toggle-btn" data-lang="hindi">हि</button>
            </div>
            <?php elseif ($lang === 'hi'): ?>
            <span class="lang-toggle" style="padding: 5px 12px; font-size: 0.78rem; font-weight: 600;">हिंदी</span>
            <?php else: ?>
            <span class="lang-toggle" style="padding: 5px 12px; font-size: 0.78rem; font-weight: 600;">English</span>
            <?php endif; ?>
            <div class="exam-timer" id="examTimer" aria-label="Time left">
                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                <span id="timerDisplay"><?= sprintf('%02d:%02d:%02d', intdiv($duration, 60), $duration % 60, 0) ?></span>
            </div>
        </div>
    </div>

    <!-- Progress Bar (sticky under header) -->
    <div class="exam-progress-wrap">
        <div class="exam-progress-bar">
            <div class="exam-progress-fill" id="examProgress" style="width:0%"></div>
        </div>
    </div>

    <div class="exam-layout">
        <!-- Main Question Area -->
        <div class="exam-main">
            <!-- Info bar -->
            <div class="exam-info-bar">
                <span>📋 <strong><?= $totalQ ?></strong> Questions</span>
                <span>⏱ <strong><?= $duration ?></strong> min</span>
                <span>🏆 <strong><?= (int)($exam['total_marks'] ?? 100) ?></strong> Total</span>
                <span>✓ <strong><?= (int)($exam['pass_marks'] ?? 40) ?></strong> Pass</span>
                <?php if (!empty($exam['start_time'])): ?>
                    <span>📅 <?= date('d M Y, g:i A', strtotime($exam['start_time'])) ?><?php if (!empty($exam['end_time'])): ?> → <?= date('g:i A', strtotime($exam['end_time'])) ?><?php endif; ?></span>
                <?php endif; ?>
            </div>

            <?php if (!empty($exam['instructions']) || !empty($exam['instructions_hindi'])): ?>
            <div class="exam-instructions">
                <strong>📋 Instructions:</strong>
                <?php if (!empty($exam['instructions'])): ?>
                    <div style="margin-top:5px;"><?= nl2br(htmlspecialchars($exam['instructions'], ENT_QUOTES, 'UTF-8')) ?></div>
                <?php endif; ?>
                <?php if (!empty($exam['instructions_hindi'])): ?>
                    <div style="margin-top:5px;font-family:'Noto Sans Devanagari',sans-serif;"><?= nl2br(htmlspecialchars($exam['instructions_hindi'], ENT_QUOTES, 'UTF-8')) ?></div>
                <?php endif; ?>
            </div>
            <?php endif; ?>

            <form id="examForm" method="POST" action="<?= $bp ?>/branch-exam/submit/<?= (int)$exam['id'] ?>">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">
                <input type="hidden" name="started_at" id="startedAt" value="<?= date('Y-m-d H:i:s') ?>">

                <?php foreach ($questions as $index => $q):
                    $qId = (int)$q['id'];
                    $qEn = $q['question_text'] ?? '';
                    $qHi = $q['question_text_hindi'] ?? '';
                ?>
                <div class="exam-question<?= $index === 0 ? ' active' : '' ?>" data-question="<?= $index ?>" id="question-<?= $index ?>">
                    <div class="question-header">
                        <span class="question-number">Question <?= $index + 1 ?> of <?= $totalQ ?></span>
                        <span class="question-marks">[<?= (int)($q['marks'] ?? 1) ?> Marks]</span>
                    </div>

                    <?php if (!empty($qEn)): ?>
                    <div class="question-text lang-en"><?= htmlspecialchars($qEn, ENT_QUOTES, 'UTF-8') ?></div>
                    <?php endif; ?>
                    <?php if (!empty($qHi)): ?>
                    <div class="question-text-hindi lang-hi"><?= htmlspecialchars($qHi, ENT_QUOTES, 'UTF-8') ?></div>
                    <?php endif; ?>
                    <?php if (empty($qEn) && empty($qHi)): ?>
                    <div class="question-text" style="color:#e84118;">⚠ Question text not available. Please contact your branch.</div>
                    <?php endif; ?>
                    <?php if (empty($qHi) && !empty($qEn)): ?>
                    <div class="missing-hindi-notice" style="display:none;margin-top:6px;padding:6px 10px;background:#fff5e6;border:1px solid #f5d68b;border-radius:4px;font-size:0.76rem;color:#b8731a;">⚠ Hindi translation not available for this question. Showing English instead.</div>
                    <?php endif; ?>
                    <?php if (empty($qEn) && !empty($qHi)): ?>
                    <div class="missing-english-notice" style="display:none;margin-top:6px;padding:6px 10px;background:#fff5e6;border:1px solid #f5d68b;border-radius:4px;font-size:0.76rem;color:#b8731a;">⚠ English translation not available for this question. Showing Hindi instead.</div>
                    <?php endif; ?>

                    <div class="question-options">
                        <?php
                        $optionKeys = ['a','b','c','d'];
                        foreach ($optionKeys as $key):
                            $optEn = $q['option_' . $key] ?? '';
                            $optHi = $q['option_' . $key . '_hindi'] ?? '';
                            if (empty($optEn) && empty($optHi)) continue;
                        ?>
                        <label class="option-label" data-qid="<?= $qId ?>" data-opt="<?= $key ?>">
                            <input type="radio" name="answers[<?= $qId ?>]" value="<?= $key ?>" class="option-radio">
                            <div class="option-text">
                                <?php if (!empty($optEn)): ?>
                                <div class="option-text-main lang-en"><strong><?= strtoupper($key) ?>.</strong> <?= htmlspecialchars($optEn, ENT_QUOTES, 'UTF-8') ?></div>
                                <?php endif; ?>
                                <?php if (!empty($optHi)): ?>
                                <div class="option-text-hindi lang-hi"><strong><?= strtoupper($key) ?>.</strong> <?= htmlspecialchars($optHi, ENT_QUOTES, 'UTF-8') ?></div>
                                <?php endif; ?>
                            </div>
                        </label>
                        <?php endforeach; ?>
                    </div>

                    <div class="question-actions">
                        <button type="button" class="btn-clear-answer" data-question="<?= $index ?>">✕ Clear Answer</button>
                        <button type="button" class="btn-mark-review" data-question="<?= $index ?>" id="markReviewBtn-<?= $index ?>">
                            <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4v20l4-3 4 3 4-3 4 3V4z"/></svg>
                            <span class="mark-review-label">Mark for Review</span>
                        </button>
                    </div>
                </div>
                <?php endforeach; ?>

                <!-- INLINE Navigation buttons — right under the question, not at the bottom -->
                <div class="exam-nav">
                    <div class="exam-nav-left">
                        <button type="button" class="btn-nav btn-prev" id="prevBtn" disabled>← Previous</button>
                        <span class="nav-progress-text">Question <strong id="navCurrentQ">1</strong> of <?= $totalQ ?></span>
                    </div>
                    <div class="exam-nav-right">
                        <button type="button" class="btn-nav btn-next" id="nextBtn">Next →</button>
                        <button type="submit" class="btn-nav btn-submit-inline" id="submitInlineBtn" style="display:none;" onclick="return confirm('Submit your exam? You cannot change your answers later.');">✓ Submit Exam</button>
                    </div>
                </div>
            </form>
        </div>

        <!-- Question Navigator Sidebar -->
        <div class="exam-sidebar">
            <div class="qnav-panel">
                <div class="qnav-title">📋 Question Navigator</div>
                <div class="qnav-grid">
                    <?php for ($i = 0; $i < $totalQ; $i++): ?>
                    <button type="button" class="qnav-btn<?= $i === 0 ? ' active' : '' ?>" data-q="<?= $i ?>"><?= $i + 1 ?></button>
                    <?php endfor; ?>
                </div>
                <div class="qnav-legend">
                    <span class="qnav-legend-item"><span class="qnav-dot" style="background:#16a085;border-color:#16a085;"></span> Current</span>
                    <span class="qnav-legend-item"><span class="qnav-dot" style="background:#eafaf1;border-color:#27ae60;"></span> Answered</span>
                    <span class="qnav-legend-item"><span class="qnav-dot" style="background:#fff3e0;border-color:#f39c12;"></span> Marked for Review</span>
                    <span class="qnav-legend-item"><span class="qnav-dot" style="background:#fff;border-color:#ddd;"></span> Not Visited</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Sticky Bottom Bar (always visible Submit) -->
    <div class="exam-sticky-bar">
        <div class="sticky-left">
            <span class="sticky-answered-info">Answered: <strong id="answeredCount">0</strong> / <?= $totalQ ?></span>
            <span class="sticky-marked-info">Marked: <strong id="markedCount">0</strong></span>
        </div>
        <div class="sticky-right">
            <button type="submit" form="examForm" class="btn-sticky-submit" onclick="return confirm('Submit your exam? You cannot change your answers later.');">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                Submit Exam
            </button>
        </div>
    </div>
</section>

<script>
(function() {
    'use strict';

    var config = <?= json_encode($jsConfig) ?>;
    var duration = config.duration;
    var totalQ = config.totalQ;
    var languageMode = config.languageMode;

    var totalSeconds = duration * 60;
    var timerInterval = null;
    var currentQuestion = 0;
    var currentLang = languageMode === 'both' ? 'both' : languageMode;
    var markedForReview = {};

    // ========== Timer ==========
    var timerEl = document.getElementById('timerDisplay');
    var startTime = Date.now();

    function pad(n) { return (n < 10 ? '0' : '') + n; }

    function updateTimer() {
        var elapsed = Math.floor((Date.now() - startTime) / 1000);
        var remaining = totalSeconds - elapsed;
        if (remaining <= 0) {
            clearInterval(timerInterval);
            timerEl.textContent = '00:00:00';
            alert('⏰ Time is up! Your exam will be submitted automatically.');
            document.getElementById('examForm').submit();
            return;
        }
        var h = Math.floor(remaining / 3600);
        var m = Math.floor((remaining % 3600) / 60);
        var s = remaining % 60;
        timerEl.textContent = pad(h) + ':' + pad(m) + ':' + pad(s);

        var timerBox = document.getElementById('examTimer');
        timerBox.classList.remove('timer-warning', 'timer-danger');
        if (remaining < 60) timerBox.classList.add('timer-danger');
        else if (remaining < 300) timerBox.classList.add('timer-warning');
    }
    timerInterval = setInterval(updateTimer, 1000);
    updateTimer();

    // ========== Question Navigation ==========
    function showQuestion(idx) {
        if (idx < 0 || idx >= totalQ) return;
        document.querySelectorAll('.exam-question').forEach(function(el) { el.classList.remove('active'); });
        var target = document.querySelector('.exam-question[data-question="' + idx + '"]');
        if (target) target.classList.add('active');

        document.querySelectorAll('.qnav-btn').forEach(function(b) { b.classList.remove('active'); });
        var navBtn = document.querySelector('.qnav-btn[data-q="' + idx + '"]');
        if (navBtn) navBtn.classList.add('active');

        currentQuestion = idx;
        document.getElementById('prevBtn').disabled = (idx === 0);
        document.getElementById('nextBtn').style.display = (idx === totalQ - 1) ? 'none' : 'inline-flex';
        document.getElementById('submitInlineBtn').style.display = (idx === totalQ - 1) ? 'inline-flex' : 'none';
        document.getElementById('navCurrentQ').textContent = (idx + 1);

        var pct = ((idx + 1) / totalQ) * 100;
        document.getElementById('examProgress').style.width = pct + '%';

        // Scroll to top of question area (below sticky header)
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    document.getElementById('prevBtn').addEventListener('click', function() { showQuestion(currentQuestion - 1); });
    document.getElementById('nextBtn').addEventListener('click', function() { showQuestion(currentQuestion + 1); });
    document.querySelectorAll('.qnav-btn').forEach(function(b) {
        b.addEventListener('click', function() { showQuestion(parseInt(b.dataset.q, 10)); });
    });

    // ========== Option Selection ==========
    document.querySelectorAll('.option-label').forEach(function(label) {
        label.addEventListener('click', function(e) {
            // Prevent double-fire from radio input click
            if (e.target.tagName === 'INPUT') return;
            var qid = this.dataset.qid;
            document.querySelectorAll('.option-label[data-qid="' + qid + '"]').forEach(function(l) {
                l.classList.remove('selected');
            });
            this.classList.add('selected');
            var radio = this.querySelector('input[type=radio]');
            if (radio) radio.checked = true;
            updateAnsweredCount();
            updateNavButtons();
        });
    });

    // Also handle radio direct click
    document.querySelectorAll('.option-radio').forEach(function(radio) {
        radio.addEventListener('change', function() {
            var qid = this.closest('.option-label').dataset.qid;
            document.querySelectorAll('.option-label[data-qid="' + qid + '"]').forEach(function(l) {
                l.classList.remove('selected');
            });
            this.closest('.option-label').classList.add('selected');
            updateAnsweredCount();
            updateNavButtons();
        });
    });

    // ========== Clear Answer ==========
    document.querySelectorAll('.btn-clear-answer').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var idx = parseInt(this.dataset.question, 10);
            var q = document.querySelector('.exam-question[data-question="' + idx + '"]');
            if (!q) return;
            q.querySelectorAll('input[type=radio]').forEach(function(r) { r.checked = false; });
            q.querySelectorAll('.option-label').forEach(function(l) { l.classList.remove('selected'); });
            updateAnsweredCount();
            updateNavButtons();
        });
    });

    // ========== Mark for Review ==========
    document.querySelectorAll('.btn-mark-review').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var idx = parseInt(this.dataset.question, 10);
            markedForReview[idx] = !markedForReview[idx];
            this.classList.toggle('is-marked', markedForReview[idx]);
            this.querySelector('.mark-review-label').textContent = markedForReview[idx] ? 'Marked for Review' : 'Mark for Review';
            updateNavButtons();
            updateMarkedCount();
        });
    });

    function updateAnsweredCount() {
        var answered = document.querySelectorAll('input[type=radio]:checked').length;
        document.getElementById('answeredCount').textContent = answered;
    }

    function updateMarkedCount() {
        var c = 0;
        for (var k in markedForReview) if (markedForReview[k]) c++;
        document.getElementById('markedCount').textContent = c;
    }

    function updateNavButtons() {
        document.querySelectorAll('.qnav-btn').forEach(function(b, i) {
            b.classList.remove('answered', 'marked-review', 'answered-marked');
            var q = document.querySelector('.exam-question[data-question="' + i + '"]');
            var isAnswered = q && q.querySelector('input[type=radio]:checked');
            var isMarked = markedForReview[i];
            if (isAnswered && isMarked) b.classList.add('answered-marked');
            else if (isAnswered) b.classList.add('answered');
            else if (isMarked) b.classList.add('marked-review');
        });
    }

    // ========== Language Toggle (always works for 'both' mode) ==========
    if (languageMode === 'both') {
        document.querySelectorAll('.lang-toggle-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                document.querySelectorAll('.lang-toggle-btn').forEach(function(b) { b.classList.remove('active'); });
                this.classList.add('active');
                currentLang = this.dataset.lang;
                applyLanguage();
            });
        });
    }

    function applyLanguage() {
        var showEn = (currentLang === 'both' || currentLang === 'english' || currentLang === 'en');
        var showHi = (currentLang === 'both' || currentLang === 'hindi' || currentLang === 'hi');

        // SMART FALLBACK: For every question/option, we look at the "language group"
        // and check whether both languages are available. If only one is available,
        // we show that one regardless of the user's language preference.
        // This prevents the page from going blank when a question has only English
        // text but the user clicked "हि" (Hindi-only mode).

        // First, reset all visibility based on user preference
        document.querySelectorAll('.lang-en').forEach(function(el) { el.style.display = showEn ? '' : 'none'; });
        document.querySelectorAll('.lang-hi').forEach(function(el) { el.style.display = showHi ? '' : 'none'; });

        // Now apply fallback for question text pairs
        document.querySelectorAll('.exam-question').forEach(function(qEl) {
            var enEl = qEl.querySelector('.question-text.lang-en');
            var hiEl = qEl.querySelector('.question-text-hindi.lang-hi');
            applyFallbackForPair(enEl, hiEl, showEn, showHi);
        });

        // Apply fallback for option text pairs
        document.querySelectorAll('.option-text').forEach(function(optEl) {
            var enEl = optEl.querySelector('.option-text-main.lang-en');
            var hiEl = optEl.querySelector('.option-text-hindi.lang-hi');
            applyFallbackForPair(enEl, hiEl, showEn, showHi);
        });

        // Apply fallback for any standalone .lang-en element (header, info bar, instructions)
        // that has no .lang-hi sibling
        document.querySelectorAll('.lang-en').forEach(function(el) {
            // Skip if already inside a question/option (handled above)
            if (el.closest('.exam-question') || el.closest('.option-text')) return;
            var sibling = el.parentElement.querySelector('.lang-hi');
            if (!sibling && !showEn) {
                // No Hindi sibling exists — show English as fallback
                el.style.display = '';
            }
        });
        document.querySelectorAll('.lang-hi').forEach(function(el) {
            if (el.closest('.exam-question') || el.closest('.option-text')) return;
            var sibling = el.parentElement.querySelector('.lang-en');
            if (!sibling && !showHi) {
                el.style.display = '';
            }
        });

        // Show/hide the "missing translation" notices (only shown when user
        // requests a language that doesn't exist for a question)
        document.querySelectorAll('.missing-hindi-notice').forEach(function(el) {
            el.style.display = (showHi && !showEn) ? '' : 'none';
        });
        document.querySelectorAll('.missing-english-notice').forEach(function(el) {
            el.style.display = (showEn && !showHi) ? '' : 'none';
        });
    }

    /**
     * Apply fallback logic for a pair of (English, Hindi) elements.
     * If user wants only one language but that language element is missing (null),
     * show the other language instead of leaving a blank.
     */
    function applyFallbackForPair(enEl, hiEl, showEn, showHi) {
        if (!enEl && !hiEl) return; // nothing to do — no text at all

        if (showEn && showHi) {
            // Both mode — show whatever exists
            if (enEl) enEl.style.display = '';
            if (hiEl) hiEl.style.display = '';
        } else if (showEn && !showHi) {
            // English-only mode
            if (enEl) {
                enEl.style.display = '';
            } else if (hiEl) {
                // No English available — show Hindi as fallback
                hiEl.style.display = '';
            }
        } else if (!showEn && showHi) {
            // Hindi-only mode
            if (hiEl) {
                hiEl.style.display = '';
            } else if (enEl) {
                // No Hindi available — show English as fallback
                enEl.style.display = '';
            }
        }
    }

    // ========== Form submit confirmation ==========
    document.getElementById('examForm').addEventListener('submit', function(e) {
        var answered = document.querySelectorAll('input[type=radio]:checked').length;
        if (answered < totalQ) {
            if (!confirm('You have answered ' + answered + ' of ' + totalQ + ' questions. Unanswered questions will be marked wrong. Submit anyway?')) {
                e.preventDefault();
            }
        }
    });

    // ========== Keyboard shortcuts ==========
    document.addEventListener('keydown', function(e) {
        // Don't intercept if user is typing in an input
        if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
        if (e.key === 'ArrowLeft' && currentQuestion > 0) { showQuestion(currentQuestion - 1); }
        else if (e.key === 'ArrowRight' && currentQuestion < totalQ - 1) { showQuestion(currentQuestion + 1); }
    });

    // ========== Init ==========
    showQuestion(0);
    updateAnsweredCount();
    updateMarkedCount();
    updateNavButtons();
    // ALWAYS apply language on init — this handles 'hi' mode (hide English,
    // show Hindi), 'en' mode (hide Hindi, show English), and 'both' mode (show both).
    // The applyLanguage() function has built-in fallback: if a question has only
    // one language available, that one is shown regardless of the mode.
    applyLanguage();
})();
</script>

<?php
include __DIR__ . '/../layouts/footer.php';
