<?php
/**
 * Practice Test Taking Interface — Gmind Institute
 *
 * Full practice test interface with start modal, timer, progress bar,
 * bilingual question display, language toggle, question navigator sidebar,
 * radio options with bilingual text, and auto-submit on timer expiry.
 *
 * Shows user name prominently throughout exam, displays remaining attempts,
 * and enforces max attempt limits.
 *
 * For guest users: AJAX checks attempt count by email after they type it.
 * For logged-in users: attempt count is known from server-side data.
 */

$set        = $set        ?? [];
$csrfToken  = $csrfToken  ?? '';
$basePath   = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$currentPage = $currentNav ?? 'practice';

$setId             = $set['id'] ?? 0;
$setTitle          = getBilingual($set, 'title') ?: __('practice.title');
$setDuration       = (int) ($set['duration_minutes'] ?? 30);
$totalMarks        = (int) ($set['total_marks'] ?? 0);
$passMarks         = (int) ($set['pass_marks'] ?? 0);
$negativeMarks     = (float) ($set['negative_marks'] ?? 0);
$languageMode      = $set['language_mode'] ?? 'english';
$questions         = $set['questions'] ?? [];
$totalQ            = count($questions);
$showCorrect       = !empty($set['show_correct_answers']);

// User info for name display and attempt tracking
$userName             = $userName ?? '';
$userEmail            = $userEmail ?? '';
$isLoggedIn           = $isLoggedIn ?? false;
$userAlreadyAttempted = $userAlreadyAttempted ?? false;
$attemptCount         = $attemptCount ?? 0;
$maxAttempts          = $maxAttempts ?? 0;
$remainingAttempts    = $remainingAttempts ?? -1;

// Calculate next attempt number (for display)
$nextAttemptNumber = $attemptCount + 1;

// Ordinal suffix helper for translation
$attemptOrdinal = $nextAttemptNumber . ($nextAttemptNumber === 1 ? 'st' : ($nextAttemptNumber === 2 ? 'nd' : ($nextAttemptNumber === 3 ? 'rd' : 'th')));
include __DIR__ . '/../layouts/header.php';

?>
<!-- Practice Test Styles -->
<style>
/* Start Modal */
.practice-start-overlay {
    position: fixed; top: 0; left: 0; width: 100%; height: 100%;
    background-color: rgba(0,0,0,0.6); z-index: 9999;
    display: flex; align-items: center; justify-content: center;
    padding: 16px;
}
.practice-start-modal {
    background-color: #ffffff; border-radius: 16px; max-width: 520px; width: 100%;
    max-height: 90vh; overflow-y: auto;
    box-shadow: 0 20px 60px rgba(0,0,0,0.3);
}
.practice-start-header {
    background: linear-gradient(135deg, #1a4fa0, #0d2b6e);
    color: #ffffff; padding: 24px 28px; border-radius: 16px 16px 0 0; text-align: center;
}
.practice-start-header h2 { font-size: 1.3rem; margin: 0; }
.practice-start-header p { font-size: 0.9rem; opacity: 0.85; margin-top: 4px; margin-bottom: 0; }
.practice-start-body { padding: 24px 28px; }
.practice-start-details { margin-bottom: 20px; }
.practice-start-detail {
    display: flex; justify-content: space-between; align-items: center;
    padding: 10px 0; border-bottom: 1px solid #f0f0f0;
}
.practice-start-detail:last-child { border-bottom: none; }
.practice-start-detail-label { font-size: 0.88rem; color: #666; }
.practice-start-detail-value { font-size: 0.92rem; font-weight: 600; color: #0d2b6e; }
.practice-start-detail-value.negative { color: #e84118; }

/* Guest Fields */
.practice-guest-fields {
    background-color: #f4f7fc; border-radius: 10px; padding: 18px; margin-bottom: 20px;
}
.practice-guest-fields h4 { font-size: 0.95rem; color: #0d2b6e; margin-bottom: 4px; }
.practice-guest-fields p { font-size: 0.82rem; color: #666; margin-bottom: 12px; }
.practice-guest-fields .form-group { margin-bottom: 10px; }
.practice-guest-fields label { font-size: 0.82rem; font-weight: 600; color: #333; display: block; margin-bottom: 4px; }
.practice-guest-fields input {
    width: 100%; padding: 10px 14px; border: 1px solid #ddd; border-radius: 8px;
    font-size: 0.88rem; transition: border-color 0.2s;
}
.practice-guest-fields input:focus { border-color: #1a4fa0; outline: none; }

/* Attempt Info Box (shown after email check for guests) */
.guest-attempt-info {
    background-color: #fff8e1; border: 1px solid #f39c12; border-radius: 8px;
    padding: 12px 16px; margin-top: 12px; font-size: 0.85rem; color: #8a6d3b;
    display: none;
}
.guest-attempt-info.attempt-blocked {
    background-color: #fff5f5; border-color: #e84118; color: #c0392b;
}
.guest-attempt-info strong { color: inherit; }

/* Start Button */
.btn-start-test {
    display: block; width: 100%; padding: 14px;
    background: linear-gradient(135deg, #1a4fa0, #0d2b6e);
    color: #ffffff; border: none; border-radius: 10px;
    font-size: 1rem; font-weight: 600; cursor: pointer;
    transition: transform 0.2s, box-shadow 0.2s;
    font-family: 'Poppins', sans-serif;
}
.btn-start-test:hover {
    transform: translateY(-2px); box-shadow: 0 6px 20px rgba(26,79,160,0.35);
}
.btn-start-test:disabled {
    background: #cccccc; cursor: not-allowed; transform: none; box-shadow: none;
}

/* Practice Section */
.practice-take-section { background-color: #f4f7fc; padding-bottom: 20px; min-height: 100vh; }

/* Header Bar */
.practice-header-bar {
    background: linear-gradient(135deg, #1a4fa0, #0d2b6e); 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;
}
.practice-header-left { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.practice-header-left h1 { font-size: 1rem; margin: 0; white-space: nowrap; }
.practice-q-count { font-size: 0.78rem; opacity: 0.8; }
.user-name-badge {
    display: inline-flex; align-items: center; gap: 4px;
    background-color: rgba(255,255,255,0.2); padding: 3px 12px;
    border-radius: 50px; font-size: 0.82rem; font-weight: 500;
}
.attempt-info-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;
}
.practice-header-right { display: flex; align-items: center; gap: 10px; }

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

/* Timer */
.practice-timer {
    display: flex; align-items: center; gap: 6px;
    background-color: rgba(255,255,255,0.15); padding: 6px 14px;
    border-radius: 8px; font-weight: 600; font-size: 0.92rem;
}
.timer-warning { background-color: rgba(243,156,18,0.4); }
.timer-danger { background-color: rgba(232,65,24,0.5); animation: blink 0.8s infinite; }
@keyframes blink { 0%,100%{opacity:1;} 50%{opacity:0.5;} }

/* Progress Bar */
.practice-progress-bar { height: 4px; background-color: #e0e0e0; position: sticky; top: 52px; z-index: 99; }
.practice-progress-fill { height: 100%; background: linear-gradient(90deg, #27ae60, #2ecc71); transition: width 0.3s; }

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

/* Questions */
.practice-main { min-width: 0; }
.practice-question { display: none; }
.practice-question.active { display: block; }
.question-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; }
.question-number { font-size: 0.88rem; font-weight: 600; color: #1a4fa0; }
.question-marks { font-size: 0.78rem; color: #666; background-color: #eaf0fb; padding: 2px 10px; border-radius: 50px; }
.question-text { font-size: 0.95rem; color: #333; line-height: 1.7; margin-bottom: 8px; }
.question-text-hindi { font-size: 0.9rem; color: #777; line-height: 1.7; margin-bottom: 14px; border-left: 3px solid #f39c12; padding-left: 10px; }

/* Options */
.question-options { display: flex; flex-direction: column; gap: 10px; margin-top: 12px; }
.option-label {
    display: flex; align-items: flex-start; gap: 12px; padding: 12px 16px;
    border: 2px solid #e8e8e8; border-radius: 10px; cursor: pointer;
    transition: border-color 0.2s, background-color 0.2s;
}
.option-label:hover { border-color: #1a4fa0; background-color: #f4f7fc; }
.option-radio { margin-top: 3px; accent-color: #1a4fa0; flex-shrink: 0; }
.option-text { flex: 1; }
.option-text-main { font-size: 0.9rem; color: #333; }
.option-text-hindi { font-size: 0.82rem; color: #999; margin-top: 2px; }

/* Navigation */
.practice-nav { display: flex; gap: 10px; justify-content: space-between; margin-top: 20px; flex-wrap: wrap; }
.btn-nav {
    padding: 10px 20px; border-radius: 8px; font-size: 0.88rem; font-weight: 600;
    cursor: pointer; border: none; font-family: 'Poppins', sans-serif;
    transition: background-color 0.2s, transform 0.2s;
}
.btn-prev { background-color: #f4f7fc; color: #1a4fa0; border: 1px solid #d0d7e3; }
.btn-prev:hover { background-color: #eaf0fb; }
.btn-next { background-color: #1a4fa0; color: #ffffff; }
.btn-next:hover { background-color: #0d2b6e; }
.btn-submit-exam { background-color: #27ae60; color: #ffffff; }
.btn-submit-exam:hover { background-color: #219a52; }
.btn-clear-answer { background-color: #fff5f5; color: #e84118; border: 1px solid #f5c6cb; font-size: 0.82rem; padding: 6px 14px; }
.btn-clear-answer:hover { background-color: #ffe0e0; }

/* Question Navigator Sidebar */
.practice-sidebar { display: none; }
@media (min-width: 768px) {
    .practice-sidebar { display: block; position: sticky; top: 80px; align-self: start; }
}
.qnav-panel { background-color: #ffffff; border-radius: 10px; padding: 16px; box-shadow: 0 4px 16px rgba(26,79,160,0.08); }
.qnav-title { font-size: 0.88rem; font-weight: 600; color: #0d2b6e; margin-bottom: 10px; }
.qnav-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 6px; }
.qnav-btn {
    width: 36px; height: 36px; border-radius: 8px; border: 1px solid #e0e0e0;
    background-color: #ffffff; font-size: 0.78rem; font-weight: 600; color: #666;
    cursor: pointer; transition: all 0.2s; display: flex; align-items: center; justify-content: center;
}
.qnav-btn.active { border-color: #1a4fa0; background-color: #1a4fa0; color: #ffffff; }
.qnav-btn.answered { background-color: #eafaf1; border-color: #27ae60; color: #27ae60; }
.qnav-btn.visited { background-color: #f4f7fc; }
.qnav-legend { display: flex; gap: 12px; margin-top: 10px; font-size: 0.72rem; color: #999; flex-wrap: wrap; }
.qnav-legend-item { display: flex; align-items: center; gap: 4px; }
.qnav-dot { width: 10px; height: 10px; border-radius: 3px; display: inline-block; }

/* Sticky Bottom Bar */
.practice-sticky-bar {
    position: sticky; bottom: 0; z-index: 100;
    background-color: #ffffff; border-top: 1px solid #e0e0e0;
    padding: 10px 24px; display: flex; align-items: center;
    justify-content: space-between; gap: 12px; box-shadow: 0 -2px 10px rgba(0,0,0,0.08);
}
.sticky-left { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
.sticky-right { display: flex; align-items: center; gap: 8px; }
.btn-back-review {
    display: inline-flex; align-items: center; gap: 4px; padding: 8px 14px;
    background-color: #f4f7fc; color: #1a4fa0; border: 1px solid #d0d7e3;
    border-radius: 6px; font-size: 0.82rem; font-weight: 600; text-decoration: none;
    font-family: 'Poppins', sans-serif;
}
.sticky-answered-info { font-size: 0.82rem; color: #666; }
.sticky-user-name {
    display: inline-flex; align-items: center; gap: 3px; font-size: 0.82rem;
    color: #1a4fa0; font-weight: 500; max-width: 150px; overflow: hidden;
    text-overflow: ellipsis; white-space: nowrap;
}
.sticky-attempt-info { font-size: 0.78rem; color: #e84118; font-weight: 600; }
.btn-sticky-submit {
    display: inline-flex; align-items: center; gap: 6px; padding: 10px 20px;
    background-color: #27ae60; color: #ffffff; border: none; border-radius: 6px;
    font-size: 0.88rem; font-weight: 600; cursor: pointer;
    font-family: 'Poppins', sans-serif; transition: background-color 0.2s;
}
.btn-sticky-submit:hover { background-color: #219a52; }

/* Responsive */
@media (max-width: 576px) {
    .user-name-badge { font-size: 0.78rem; padding: 4px 10px; }
    .sticky-user-name { max-width: 120px; font-size: 0.75rem; }
    .sticky-attempt-info { font-size: 0.72rem; }
}
</style>

<!-- ============================================================
     Start Modal
     ============================================================ -->
<?php if ($userAlreadyAttempted): ?>
<!-- Already Attempted - Show message instead of test -->
<div class="practice-start-overlay" id="startModal">
    <div class="practice-start-modal">
        <div class="practice-start-header">
            <h2><?= htmlspecialchars($setTitle, ENT_QUOTES, 'UTF-8') ?></h2>
            <?php if (!empty($set['title_hindi']) && getCurrentLocale() !== 'hi'): ?>
            <p><?= htmlspecialchars($set['title_hindi'], ENT_QUOTES, 'UTF-8') ?></p>
            <?php endif; ?>
        </div>
        <div class="practice-start-body" style="text-align:center; padding:32px;">
            <div style="display:inline-flex;align-items:center;justify-content:center;width:64px;height:64px;border-radius:50%;background-color:#fff8e1;margin-bottom:16px;">
                <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#f39c12" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
            </div>
            <h3 style="color:#0d2b6e;margin-bottom:10px;"><?= __('practice.attempt_limit_reached') ?></h3>
            <p style="color:#666;margin-bottom:16px;"><?= __('practice.attempt_limit_msg', ['max' => $maxAttempts]) ?></p>
            <?php if (!empty($userName)): ?>
            <p style="font-size:0.88rem;color:#999;margin-bottom:16px;"><?= __('practice.logged_in_as') ?> <strong style="color:#1a4fa0;"><?= htmlspecialchars($userName, ENT_QUOTES, 'UTF-8') ?></strong></p>
            <?php endif; ?>
            <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap;">
                <a href="<?= $basePath ?>/practice" style="display:inline-block;padding:12px 28px;background-color:#1a4fa0;color:#ffffff;border-radius:8px;text-decoration:none;font-weight:600;font-size:0.92rem;"><?= __('practice.back_to_list') ?></a>
                <a href="<?= $basePath ?>/practice/history" style="display:inline-block;padding:12px 28px;background-color:#ffffff;color:#1a4fa0;border:2px solid #1a4fa0;border-radius:8px;text-decoration:none;font-weight:600;font-size:0.92rem;"><?= __('practice.view_my_history') ?></a>
            </div>
        </div>
    </div>
</div>
<?php else: ?>
<div class="practice-start-overlay" id="startModal">
    <div class="practice-start-modal">
        <div class="practice-start-header">
            <h2><?= htmlspecialchars($setTitle, ENT_QUOTES, 'UTF-8') ?></h2>
            <?php if (!empty($set['title_hindi']) && getCurrentLocale() !== 'hi'): ?>
            <p><?= htmlspecialchars($set['title_hindi'], ENT_QUOTES, 'UTF-8') ?></p>
            <?php endif; ?>
        </div>
        <div class="practice-start-body">
            <div class="practice-start-details">
                <div class="practice-start-detail">
                    <span class="practice-start-detail-label"><?= __('practice.duration') ?></span>
                    <span class="practice-start-detail-value"><?= $setDuration ?> <?= __('practice.minutes') ?></span>
                </div>
                <div class="practice-start-detail">
                    <span class="practice-start-detail-label"><?= __('practice.total_questions') ?></span>
                    <span class="practice-start-detail-value"><?= $totalQ ?></span>
                </div>
                <div class="practice-start-detail">
                    <span class="practice-start-detail-label"><?= __('practice.total_marks') ?></span>
                    <span class="practice-start-detail-value"><?= $totalMarks ?></span>
                </div>
                <div class="practice-start-detail">
                    <span class="practice-start-detail-label"><?= __('practice.pass_marks_label') ?></span>
                    <span class="practice-start-detail-value"><?= $passMarks ?></span>
                </div>
                <?php if ($negativeMarks > 0): ?>
                <div class="practice-start-detail">
                    <span class="practice-start-detail-label"><?= __('practice.negative_marks') ?></span>
                    <span class="practice-start-detail-value negative">-<?= $negativeMarks ?> <?= __('practice.per_wrong_answer') ?></span>
                </div>
                <?php endif; ?>
                <div class="practice-start-detail">
                    <span class="practice-start-detail-label"><?= __('practice.language') ?></span>
                    <span class="practice-start-detail-value"><?= htmlspecialchars(ucfirst($languageMode), ENT_QUOTES, 'UTF-8') ?></span>
                </div>
                <?php if ($maxAttempts > 0): ?>
                <div class="practice-start-detail">
                    <span class="practice-start-detail-label"><?= __('practice.max_attempts') ?></span>
                    <span class="practice-start-detail-value" id="maxAttemptsDisplay"><?= $maxAttempts ?> (<?= __('practice.used') ?>: <span id="usedAttemptsDisplay"><?= $attemptCount ?></span> | <?= __('practice.remaining') ?>: <span id="remainingAttemptsDisplay"><?= max(0, $maxAttempts - $attemptCount) ?></span>)</span>
                </div>
                <?php else: ?>
                <div class="practice-start-detail">
                    <span class="practice-start-detail-label"><?= __('practice.attempts_label') ?></span>
                    <span class="practice-start-detail-value"><?= __('practice.unlimited') ?></span>
                </div>
                <?php endif; ?>
                <!-- Attempt number display — updated dynamically for guests -->
                <div class="practice-start-detail" id="attemptNumberRow" style="<?= $attemptCount > 0 ? '' : 'display:none;' ?>">
                    <span class="practice-start-detail-label"><?= __('practice.this_is_your') ?></span>
                    <span class="practice-start-detail-value" style="color:#e84118;" id="attemptNumberValue"><?= $attemptOrdinal ?> <?= __('practice.attempt') ?></span>
                </div>
            </div>

            <?php if ($isLoggedIn && !empty($userName)): ?>
            <!-- Logged-in user info display -->
            <div class="practice-guest-fields" style="background-color:#eafaf1;border:1px solid #c8e6c9;">
                <h4 style="color:#27ae60;">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:middle;margin-right:4px;"><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>
                    <?= __('practice.welcome') ?>, <?= htmlspecialchars($userName, ENT_QUOTES, 'UTF-8') ?>
                </h4>
                <p style="color:#27ae60;margin-bottom:0;"><?= __('practice.tracked_account_msg') ?></p>
                <?php if ($maxAttempts > 0 && $attemptCount > 0): ?>
                <p style="color:#e84118;margin-top:6px;margin-bottom:0;font-weight:600;">
                    <?= __('practice.already_taken_msg', ['count' => $attemptCount, 'ordinal' => $attemptOrdinal]) ?>
                </p>
                <?php endif; ?>
            </div>
            <?php else: ?>
            <div class="practice-guest-fields">
                <h4><?= __('practice.your_details_optional') ?></h4>
                <p><?= __('practice.guest_details_desc') ?></p>
                <div class="form-group">
                    <label for="guestName"><?= __('practice.name') ?></label>
                    <input type="text" id="guestName" name="guest_name" placeholder="<?= __('practice.enter_name') ?>" autocomplete="name">
                </div>
                <div class="form-group">
                    <label for="guestEmail"><?= __('practice.email') ?></label>
                    <input type="email" id="guestEmail" name="guest_email" placeholder="<?= __('practice.enter_email') ?>" autocomplete="email">
                </div>
                <!-- Dynamic attempt info box for guests -->
                <div class="guest-attempt-info" id="guestAttemptInfo"></div>
            </div>
            <?php endif; ?>

            <button type="button" class="btn-start-test" id="startTestBtn"><?= __('practice.start_practice_test') ?></button>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- ============================================================
     Practice Test Interface (hidden until start)
     ============================================================ -->
<section class="practice-take-section" id="practiceSection" style="display:none;" aria-label="<?= __('practice.title') ?>">
    <div class="container">
        <!-- Header Bar with User Name + Attempt Info -->
        <div class="practice-header-bar">
            <div class="practice-header-left">
                <h1><?= htmlspecialchars($setTitle, ENT_QUOTES, 'UTF-8') ?></h1>
                <span class="practice-q-count"><?= $totalQ ?> <?= __('practice.questions') ?> | <?= $totalMarks ?> <?= __('practice.marks') ?></span>
                <span class="user-name-badge" id="headerUserName" style="<?= ($isLoggedIn && !empty($userName)) ? '' : 'display:none;' ?>">
                    <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>
                    <span id="headerUserNameText"><?= htmlspecialchars($userName, ENT_QUOTES, 'UTF-8') ?></span>
                </span>
                <?php if ($maxAttempts > 0): ?>
                <span class="attempt-info-badge" id="headerAttemptBadge">
                    <?= __('practice.attempt') ?> <span id="headerAttemptNum"><?= $nextAttemptNumber ?></span>/<?= $maxAttempts ?>
                </span>
                <?php endif; ?>
            </div>
            <div class="practice-header-right">
                <?php if ($languageMode === 'both' || $languageMode === 'hindi'): ?>
                <div class="lang-toggle" role="group" aria-label="Language toggle">
                    <?php if ($languageMode === 'both'): ?>
                    <button type="button" class="lang-toggle-btn active" data-lang="both" aria-label="Show both languages"><?= __('practice.lang_both') ?></button>
                    <?php endif; ?>
                    <button type="button" class="lang-toggle-btn<?= $languageMode === 'english' ? ' active' : '' ?>" data-lang="english" aria-label="Show English only"><?= __('lang.toggle_en') ?></button>
                    <button type="button" class="lang-toggle-btn<?= $languageMode === 'hindi' && $languageMode !== 'both' ? ' active' : '' ?>" data-lang="hindi" aria-label="Show Hindi only"><?= __('lang.toggle_hi') ?></button>
                </div>
                <?php endif; ?>
                <div class="practice-timer" id="practiceTimer" aria-label="<?= __('practice.time_left') ?>">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                    <span id="timerDisplay"><?= sprintf('%02d:%02d', $setDuration, 0) ?></span>
                </div>
            </div>
        </div>

        <!-- Progress Bar -->
        <div class="practice-progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
            <div class="practice-progress-fill" id="practiceProgress" style="width:0%"></div>
        </div>

        <div class="practice-layout">
            <!-- Main Question Area -->
            <div class="practice-main">
                <form id="practiceForm" method="POST" action="<?= $basePath ?>/practice/<?= htmlspecialchars((string) $setId, ENT_QUOTES, 'UTF-8') ?>/submit">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="started_at" id="startedAt" value="">
                    <input type="hidden" name="student_name" id="hiddenGuestName" value="">
                    <input type="hidden" name="student_email" id="hiddenGuestEmail" value="">

                    <?php foreach ($questions as $index => $question): ?>
                    <?php $qId = (int) ($question['id'] ?? $index); ?>
                    <div class="practice-question<?= $index === 0 ? ' active' : '' ?>" data-question="<?= $index ?>" id="question-<?= $index ?>">
                        <div class="question-header">
                            <span class="question-number"><?= __('practice.question') ?> <?= $index + 1 ?> <?= __('practice.of') ?> <?= $totalQ ?></span>
                            <span class="question-marks">[<?= (int) ($question['marks'] ?? 1) ?> <?= __('practice.marks') ?>]</span>
                        </div>
                        <div class="question-text lang-en"><?= htmlspecialchars($question['question_text'] ?? __('practice.question'), ENT_QUOTES, 'UTF-8') ?></div>
                        <?php if (!empty($question['question_text_hindi'])): ?>
                        <div class="question-text-hindi lang-hi"><?= htmlspecialchars($question['question_text_hindi'], ENT_QUOTES, 'UTF-8') ?></div>
                        <?php endif; ?>
                        <div class="question-options">
                            <?php
                            $optionKeys = ['a', 'b', 'c', 'd'];
                            $optionFields = [];
                            foreach ($optionKeys as $key) {
                                $optionFields[$key] = [
                                    'text' => $question['option_' . $key] ?? '',
                                    'text_hindi' => $question['option_' . $key . '_hindi'] ?? '',
                                ];
                            }
                            ?>
                            <?php foreach ($optionFields as $key => $optionData): ?>
                            <?php if (!empty($optionData['text'])): ?>
                            <label class="option-label">
                                <input type="radio" name="answers[<?= $qId ?>]" value="<?= $key ?>" class="option-radio">
                                <div class="option-text">
                                    <div class="option-text-main lang-en"><strong><?= strtoupper($key) ?>.</strong> <?= htmlspecialchars($optionData['text'], ENT_QUOTES, 'UTF-8') ?></div>
                                    <?php if (!empty($optionData['text_hindi'])): ?>
                                    <div class="option-text-hindi lang-hi">(<?= htmlspecialchars($optionData['text_hindi'], ENT_QUOTES, 'UTF-8') ?>)</div>
                                    <?php endif; ?>
                                </div>
                            </label>
                            <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                        <div class="practice-nav">
                            <button type="button" class="btn-nav btn-clear-answer" data-question="<?= $index ?>"><?= __('practice.clear') ?></button>
                            <div style="display:flex;gap:8px;">
                                <button type="button" class="btn-nav btn-prev" id="prevBtn" disabled><?= __('practice.prev') ?></button>
                                <button type="button" class="btn-nav btn-next" id="nextBtn"><?= __('practice.next') ?></button>
                                <button type="button" class="btn-nav btn-submit-exam" id="submitBtn" style="display:none;"><?= __('practice.submit_test') ?></button>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </form>
            </div>

            <!-- Question Navigator Sidebar -->
            <div class="practice-sidebar">
                <div class="qnav-panel">
                    <div class="qnav-title"><?= __('practice.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-color:#1a4fa0;"></span> <?= __('practice.current') ?></span>
                        <span class="qnav-legend-item"><span class="qnav-dot" style="background-color:#27ae60;"></span> <?= __('practice.answered') ?></span>
                        <span class="qnav-legend-item"><span class="qnav-dot" style="background-color:#f4f7fc;border:1px solid #ddd;"></span> <?= __('practice.not_visited') ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Sticky Bottom Bar (inside practice section so it stays below test) -->
        <div class="practice-sticky-bar" id="stickyBar" style="display:none;">
            <div class="sticky-left">
                <a href="<?= $basePath ?>/practice" class="btn-back-review" id="backBtn">
                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 18 9 12 15 6"/></svg>
                    <?= __('practice.back') ?>
                </a>
                <span class="sticky-answered-info" id="answeredInfo"><?= __('practice.answered_label') ?> <strong>0</strong> / <?= $totalQ ?></span>
                <span class="sticky-user-name" id="stickyUserName" style="<?= ($isLoggedIn && !empty($userName)) ? '' : 'display:none;' ?>">
                    <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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>
                    <span id="stickyUserNameText"><?= htmlspecialchars($userName, ENT_QUOTES, 'UTF-8') ?></span>
                </span>
                <?php if ($maxAttempts > 0): ?>
                <span class="sticky-attempt-info" id="stickyAttemptInfo"><?= __('practice.attempt') ?> <span id="stickyAttemptNum"><?= $nextAttemptNumber ?></span>/<?= $maxAttempts ?></span>
                <?php endif; ?>
            </div>
            <div class="sticky-right">
                <button type="submit" form="practiceForm" class="btn-sticky-submit" onclick="return confirm('<?= __('practice.submit_confirm') ?>');">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                    <?= __('practice.submit_test') ?>
                </button>
            </div>
        </div>
    </div>
</section>

<!-- Practice Test JavaScript -->
<?php if (!$userAlreadyAttempted): ?>
<script>
(function() {
    'use strict';

    // Configuration from PHP
    var durationMinutes = <?= $setDuration ?>;
    var totalQuestions = <?= $totalQ ?>;
    var languageMode = <?= json_encode($languageMode) ?>;
    var isLoggedIn = <?= $isLoggedIn ? 'true' : 'false' ?>;
    var userName = <?= json_encode($userName) ?>;
    var userEmail = <?= json_encode($userEmail) ?>;
    var setId = <?= (int) $setId ?>;
    var maxAttempts = <?= (int) $maxAttempts ?>;
    var basePath = <?= json_encode($basePath) ?>;

    // Translated strings for JS
    var transAnswered = <?= json_encode(__('practice.answered_label')) ?>;
    var transAttemptBlocked = <?= json_encode(__('practice.attempt_blocked_msg')) ?>;
    var transAttemptHistory = <?= json_encode(__('practice.attempt_history_msg')) ?>;
    var transFirstAttempt = <?= json_encode(__('practice.first_attempt_msg')) ?>;
    var transAllAttemptsUsed = <?= json_encode(__('practice.all_attempts_used_alert')) ?>;
    var transUnlimited = <?= json_encode(__('practice.unlimited')) ?>;

    // State
    var totalSeconds = durationMinutes * 60;
    var timerInterval = null;
    var currentQuestion = 0;
    var testStarted = false;
    var currentLang = languageMode === 'both' ? 'both' : languageMode;
    var guestAttemptData = null; // Stores AJAX response for guest attempt info

    // DOM Elements
    var startModal = document.getElementById('startModal');
    var startTestBtn = document.getElementById('startTestBtn');
    var practiceSection = document.getElementById('practiceSection');
    var questions = document.querySelectorAll('.practice-question');
    var qnavBtns = document.querySelectorAll('.qnav-btn');
    var prevBtn = document.getElementById('prevBtn');
    var nextBtn = document.getElementById('nextBtn');
    var submitBtn = document.getElementById('submitBtn');
    var stickyBar = document.getElementById('stickyBar');
    var answeredInfo = document.getElementById('answeredInfo');
    var practiceForm = document.getElementById('practiceForm');
    var timerDisplay = document.getElementById('timerDisplay');
    var progressBar = document.getElementById('practiceProgress');
    var startedAtInput = document.getElementById('startedAt');
    var hiddenGuestName = document.getElementById('hiddenGuestName');
    var hiddenGuestEmail = document.getElementById('hiddenGuestEmail');
    var clearAnswerBtns = document.querySelectorAll('.btn-clear-answer');
    var langToggleBtns = document.querySelectorAll('.lang-toggle-btn');

    // ========================================
    // GUEST: AJAX attempt check by email
    // ========================================
    if (!isLoggedIn) {
        var guestEmailInput = document.getElementById('guestEmail');
        var guestNameInput = document.getElementById('guestName');
        var guestAttemptInfoDiv = document.getElementById('guestAttemptInfo');
        var attemptNumberRow = document.getElementById('attemptNumberRow');
        var attemptNumberValue = document.getElementById('attemptNumberValue');
        var usedAttemptsDisplay = document.getElementById('usedAttemptsDisplay');
        var remainingAttemptsDisplay = document.getElementById('remainingAttemptsDisplay');

        var emailCheckTimeout = null;

        if (guestEmailInput) {
            guestEmailInput.addEventListener('input', function() {
                clearTimeout(emailCheckTimeout);
                var email = this.value.trim();

                // Basic email format check
                if (!email || email.indexOf('@') === -1 || email.indexOf('.') === -1) {
                    if (guestAttemptInfoDiv) {
                        guestAttemptInfoDiv.style.display = 'none';
                    }
                    return;
                }

                // Debounce: wait 500ms after user stops typing
                emailCheckTimeout = setTimeout(function() {
                    checkGuestAttempts(email);
                }, 500);
            });
        }

        function checkGuestAttempts(email) {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', basePath + '/practice/' + setId + '/check-attempts?email=' + encodeURIComponent(email), true);
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    try {
                        var data = JSON.parse(xhr.responseText);
                        guestAttemptData = data;
                        updateGuestAttemptDisplay(data, email);
                    } catch(e) {
                        console.error('Failed to parse attempt check response', e);
                    }
                }
            };
            xhr.send();
        }

        function updateGuestAttemptDisplay(data, email) {
            if (!guestAttemptInfoDiv) return;

            if (data.attemptCount > 0) {
                guestAttemptInfoDiv.style.display = 'block';

                if (data.blocked) {
                    guestAttemptInfoDiv.className = 'guest-attempt-info attempt-blocked';
                    guestAttemptInfoDiv.innerHTML = '<strong>' + transAttemptBlocked + '</strong> ' + data.maxAttempts + ' ' + email + ' <strong>' + email + '</strong>.';
                    if (startTestBtn) startTestBtn.disabled = true;
                } else {
                    guestAttemptInfoDiv.className = 'guest-attempt-info';
                    guestAttemptInfoDiv.innerHTML = '<strong>' + transAttemptHistory + '</strong> <strong>' + data.attemptCount + '</strong> ' + email + ' <strong>' + email + '</strong>. <strong>' + data.nextAttemptLabel + '</strong>. ' + data.remaining + '';
                    if (startTestBtn) startTestBtn.disabled = false;
                }

                // Update the attempt number row in details
                if (attemptNumberRow) attemptNumberRow.style.display = '';
                if (attemptNumberValue) attemptNumberValue.textContent = data.nextAttemptLabel;
                if (usedAttemptsDisplay) usedAttemptsDisplay.textContent = data.attemptCount;
                if (remainingAttemptsDisplay) remainingAttemptsDisplay.textContent = data.remaining;

                // Also update header/sticky attempt numbers
                var headerAttemptNum = document.getElementById('headerAttemptNum');
                var stickyAttemptNum = document.getElementById('stickyAttemptNum');
                if (headerAttemptNum) headerAttemptNum.textContent = data.nextAttempt;
                if (stickyAttemptNum) stickyAttemptNum.textContent = data.nextAttempt;
            } else {
                guestAttemptInfoDiv.style.display = 'block';
                guestAttemptInfoDiv.className = 'guest-attempt-info';
                guestAttemptInfoDiv.innerHTML = '<strong>' + transFirstAttempt + '</strong> ' + email + ' <strong>' + email + '</strong>.';
                if (startTestBtn) startTestBtn.disabled = false;

                if (attemptNumberRow) attemptNumberRow.style.display = '';
                if (attemptNumberValue) attemptNumberValue.textContent = '1st';
                if (usedAttemptsDisplay) usedAttemptsDisplay.textContent = '0';
                if (remainingAttemptsDisplay) remainingAttemptsDisplay.textContent = data.remaining >= 0 ? data.remaining : transUnlimited;
            }
        }
    }

    // ===========================
    // Start Test
    // ===========================
    startTestBtn.addEventListener('click', function() {
        // Capture guest info or use logged-in user info
        var guestNameVal = '';
        var guestEmailVal = '';

        if (isLoggedIn) {
            guestNameVal = userName;
            guestEmailVal = userEmail;
        } else {
            guestNameVal = document.getElementById('guestName') ? document.getElementById('guestName').value.trim() : '';
            guestEmailVal = document.getElementById('guestEmail') ? document.getElementById('guestEmail').value.trim() : '';

            // If guest has attempt data and is blocked, prevent starting
            if (guestAttemptData && guestAttemptData.blocked) {
                alert(transAllAttemptsUsed);
                return;
            }
        }

        hiddenGuestName.value = guestNameVal;
        hiddenGuestEmail.value = guestEmailVal;

        // Update user name display in exam UI
        var displayName = guestNameVal || userName || 'Guest';
        var headerUserNameText = document.getElementById('headerUserNameText');
        var stickyUserNameText = document.getElementById('stickyUserNameText');
        var headerUserName = document.getElementById('headerUserName');
        var stickyUserName = document.getElementById('stickyUserName');

        if (headerUserNameText) headerUserNameText.textContent = displayName;
        if (stickyUserNameText) stickyUserNameText.textContent = displayName;
        if (headerUserName) headerUserName.style.display = '';
        if (stickyUserName) stickyUserName.style.display = '';

        // Set started_at timestamp
        startedAtInput.value = new Date().toISOString();

        // Hide modal, show test
        startModal.style.display = 'none';
        practiceSection.style.display = 'block';
        stickyBar.style.display = 'flex';
        document.body.classList.add('test-active');
        testStarted = true;

        // Start the timer
        startTimer();

        // Apply initial language
        applyLanguage(currentLang);

        // Prevent back navigation
        window.history.pushState(null, '', window.location.href);
    });

    // ===========================
    // Timer
    // ===========================
    function startTimer() {
        timerInterval = setInterval(function() {
            totalSeconds--;
            if (totalSeconds <= 0) {
                clearInterval(timerInterval);
                totalSeconds = 0;
                practiceForm.submit();
                return;
            }
            var mins = Math.floor(totalSeconds / 60);
            var secs = totalSeconds % 60;
            timerDisplay.textContent = String(mins).padStart(2, '0') + ':' + String(secs).padStart(2, '0');

            var timerEl = document.getElementById('practiceTimer');
            if (totalSeconds <= 60) {
                timerEl.classList.add('timer-danger');
                timerEl.classList.remove('timer-warning');
            } else if (totalSeconds <= 300) {
                timerEl.classList.add('timer-warning');
                timerEl.classList.remove('timer-danger');
            }
        }, 1000);
    }

    // ===========================
    // Question Navigation
    // ===========================
    function showQuestion(index) {
        questions.forEach(function(q) { q.classList.remove('active'); });
        qnavBtns.forEach(function(b) { b.classList.remove('active'); });

        if (questions[index]) questions[index].classList.add('active');
        if (qnavBtns[index]) {
            qnavBtns[index].classList.add('active');
            qnavBtns[index].classList.add('visited');
        }

        currentQuestion = index;

        prevBtn.disabled = (index === 0);
        if (index === totalQuestions - 1) {
            nextBtn.style.display = 'none';
            submitBtn.style.display = 'inline-flex';
        } else {
            nextBtn.style.display = 'inline-flex';
            submitBtn.style.display = 'none';
        }

        var progress = ((index + 1) / totalQuestions) * 100;
        progressBar.style.width = progress + '%';

        updateAnsweredState();
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    function updateAnsweredState() {
        var answeredCount = 0;
        questions.forEach(function(q, i) {
            var selected = q.querySelector('input[type="radio"]:checked');
            if (selected && qnavBtns[i]) {
                qnavBtns[i].classList.add('answered');
                answeredCount++;
            } else if (qnavBtns[i]) {
                qnavBtns[i].classList.remove('answered');
            }
        });

        var progress = (answeredCount / totalQuestions) * 100;
        progressBar.style.width = progress + '%';

        if (answeredInfo) {
            answeredInfo.innerHTML = transAnswered + ' <strong>' + answeredCount + '</strong> / ' + totalQuestions;
        }
    }

    prevBtn.addEventListener('click', function() {
        if (currentQuestion > 0) showQuestion(currentQuestion - 1);
    });

    nextBtn.addEventListener('click', function() {
        if (currentQuestion < totalQuestions - 1) showQuestion(currentQuestion + 1);
    });

    submitBtn.addEventListener('click', function() {
        var transSubmitConfirm = <?= json_encode(__('practice.submit_confirm')) ?>;
        if (confirm(transSubmitConfirm)) {
            practiceForm.submit();
        }
    });

    qnavBtns.forEach(function(btn) {
        btn.addEventListener('click', function() {
            var qIndex = parseInt(this.getAttribute('data-q'));
            showQuestion(qIndex);
        });
    });

    document.querySelectorAll('.option-radio').forEach(function(radio) {
        radio.addEventListener('change', updateAnsweredState);
    });

    clearAnswerBtns.forEach(function(btn) {
        btn.addEventListener('click', function() {
            var qIndex = parseInt(this.getAttribute('data-question'));
            var questionEl = document.getElementById('question-' + qIndex);
            if (questionEl) {
                var radios = questionEl.querySelectorAll('input[type="radio"]');
                radios.forEach(function(r) { r.checked = false; });
                updateAnsweredState();
            }
        });
    });

    // ===========================
    // Language Toggle
    // ===========================
    function applyLanguage(lang) {
        currentLang = lang;
        var allEnglish = document.querySelectorAll('.lang-en');
        var allHindi = document.querySelectorAll('.lang-hi');

        if (lang === 'both') {
            allEnglish.forEach(function(el) { el.style.display = ''; });
            allHindi.forEach(function(el) { el.style.display = ''; });
        } else if (lang === 'english') {
            allEnglish.forEach(function(el) { el.style.display = ''; });
            allHindi.forEach(function(el) { el.style.display = 'none'; });
        } else if (lang === 'hindi') {
            allEnglish.forEach(function(el) { el.style.display = 'none'; });
            allHindi.forEach(function(el) { el.style.display = ''; });
        }

        langToggleBtns.forEach(function(btn) {
            btn.classList.remove('active');
            if (btn.getAttribute('data-lang') === lang) btn.classList.add('active');
        });
    }

    langToggleBtns.forEach(function(btn) {
        btn.addEventListener('click', function() {
            applyLanguage(this.getAttribute('data-lang'));
        });
    });

    // ===========================
    // Prevent Back Navigation
    // ===========================
    window.addEventListener('popstate', function() {
        if (testStarted) window.history.pushState(null, '', window.location.href);
    });

    // ===========================
    // Keyboard Navigation
    // ===========================
    document.addEventListener('keydown', function(e) {
        if (!testStarted) return;

        if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
            e.preventDefault();
            if (currentQuestion < totalQuestions - 1) showQuestion(currentQuestion + 1);
        } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
            e.preventDefault();
            if (currentQuestion > 0) showQuestion(currentQuestion - 1);
        }

        var activeTag = document.activeElement ? document.activeElement.tagName.toLowerCase() : '';
        if (activeTag === 'input' || activeTag === 'textarea') return;

        var keyMap = { 'a': 0, 'b': 1, 'c': 2, 'd': 3 };
        var lowerKey = e.key.toLowerCase();
        if (keyMap.hasOwnProperty(lowerKey)) {
            var currentQ = questions[currentQuestion];
            if (currentQ) {
                var radios = currentQ.querySelectorAll('input[type="radio"]');
                if (radios[keyMap[lowerKey]]) {
                    radios[keyMap[lowerKey]].checked = true;
                    updateAnsweredState();
                }
            }
        }
    });

    applyLanguage(currentLang);

})();
</script>
<?php endif; include __DIR__ . '/../layouts/footer.php';
?>
