<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');
require_once 'db/adn-status-logic.php';

$quiz_status = '';
$results = [];
$score = 0;

$class_to_unlock = isset($_GET['unlock_id']) ? (int)$_GET['unlock_id'] : 2;
$class_number = $class_to_unlock - 1;

if ($class_number < 1 || $class_number > TOTAL_ADN_CLASSES || !isset($adn_progress['class_status'][$class_number])) {
    header('Location: adn-dashboard.php');
    exit;
}

if ($adn_progress['class_status'][$class_number] === 'locked') {
    header('Location: adn-dashboard.php');
    exit;
}
if ($adn_progress['class_status'][$class_number] === 'completed') {
    header('Location: adn-dashboard.php?class_completed=' . $class_number);
    exit;
}

const QUESTIONS_PER_QUIZ = 5;
const POINTS_PER_QUESTION = 20;
const PASSING_SCORE = 80;

if (!can_attempt_quiz($class_number)) {
    $retry_timestamp = $adn_progress['quiz_attempts'][$class_number];
    $remaining_time = $retry_timestamp - time();
    $hours = floor($remaining_time / 3600);
    $minutes = floor(($remaining_time % 3600) / 60);

    $quiz_status = 'locked';
    $quiz_message = "Debe esperar <b>{$hours} horas y {$minutes} minutos</b> antes de volver a intentarlo.";
}

$current_quiz_questions = [];

if ($quiz_status !== 'locked' && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    $current_quiz_questions = get_selected_questions($pdo, $class_number, QUESTIONS_PER_QUIZ);

    if (count($current_quiz_questions) < QUESTIONS_PER_QUIZ) {
        $quiz_status = 'error';
        $quiz_message = 'Error: No hay suficientes preguntas en el banco para esta clase. Contacte a soporte.';
        $current_quiz_questions = [];
    } else {
        $_SESSION['current_quiz_' . $class_number] = $current_quiz_questions;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $quiz_status !== 'locked') {
    $submitted_answers = $_POST;
    $validation_questions = $_SESSION['current_quiz_' . $class_number] ?? [];

    if (empty($validation_questions)) {
        $quiz_status = 'error';
        $quiz_message = 'Error de sesión. Vuelva a la clase para iniciar el quiz.';
    } else {
        foreach ($validation_questions as $index => $q) {
            $user_answer = strtolower($submitted_answers['answer_' . $index] ?? '');
            $is_correct = ($user_answer === $q['a']);

            $results[] = [
                'question' => $q['q'],
                'user_answer' => $user_answer,
                'correct_answer' => $q['a'],
                'is_correct' => $is_correct,
            ];

            if ($is_correct) {
                $score += POINTS_PER_QUESTION;
            }
        }

        try {
            $pdo->beginTransaction();

            if ($score >= PASSING_SCORE) {
                $stmt_pass = $pdo->prepare("
                    UPDATE adn_user_progress
                    SET status = 'completed', last_attempt = NULL
                    WHERE user_id = :user_id AND class_id = :class_number
                ");
                $stmt_pass->execute([
                    ':user_id' => $current_user_id,
                    ':class_number' => $class_number
                ]);

                if ($class_to_unlock <= TOTAL_ADN_CLASSES) {
                    $stmt_unlock = $pdo->prepare("
                        INSERT INTO adn_user_progress (user_id, class_id, status)
                        VALUES (:user_id, :class_id, 'unlocked')
                        ON DUPLICATE KEY UPDATE status = 'unlocked'
                    ");
                    $stmt_unlock->execute([
                        ':user_id' => $current_user_id,
                        ':class_id' => $class_to_unlock
                    ]);
                }

                $pdo->commit();

                $quiz_status = 'passed';
                $quiz_message = '¡Felicidades! Ha superado el quiz con ' . $score . ' puntos. La siguiente clase ha sido desbloqueada. Revise sus respuestas abajo.';

            } else {
                set_quiz_retry_lock($pdo, $current_user_id, $class_number);

                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }

                $retry_timestamp = $adn_progress['quiz_attempts'][$class_number];
                $remaining_time = $retry_timestamp - time();
                $hours = floor($remaining_time / 3600);
                $minutes = floor(($remaining_time % 3600) / 60);

                $quiz_status = 'failed';
                $quiz_message = "No ha alcanzado el puntaje mínimo (" . PASSING_SCORE . " puntos). Podrá volver a intentar con preguntas diferentes en {$hours} horas y {$minutes} minutos.";
            }

        } catch (PDOException $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $quiz_status = 'error';
            $quiz_message = 'Error grave de base de datos. Inténtelo de nuevo o contacte a soporte.';
        }
    }
    unset($_SESSION['current_quiz_' . $class_number]);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $current_quiz_questions = $_SESSION['current_quiz_' . $class_number] ?? $current_quiz_questions;
}

$correct_answers_count = 0;
if ($quiz_status === 'passed' || $quiz_status === 'failed') {
    foreach ($results as $r) {
        if ($r['is_correct']) {
            $correct_answers_count++;
        }
    }
}

$current_class_title = htmlspecialchars($adn_classes[$class_number]['title'] ?? "Semana {$class_number}");

if (ob_get_level() > 0) {
    ob_end_clean();
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Cuestionario ADN Semana <?php echo $class_number; ?> <?php echo htmlspecialchars($branding['full_title']); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">
  
  <?php include 'files/gtm-head.php'; ?>
  
  <script src="https://unpkg.com/lucide@latest"></script>
  <link rel="stylesheet" href="style.css"> 
  <script src="files/header-manager.js"></script>
    
    <style>
        .quiz-content-grid { display: flex; gap: 2rem; align-items: flex-start; }
        .quiz-col-main { flex-grow: 1; background-color: white; padding: 2.5rem; border-radius: 0.75rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1); color: var(--color-text-dark); }
        .quiz-col-status { width: 300px; flex-shrink: 0; position: sticky; top: 1.5rem; padding: 1.5rem; background-color: var(--color-text-light); border-radius: 0.75rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1); }
        @media (max-width: 1023px) {
            .quiz-card-wrapper { padding: 0; margin-left: -1rem; margin-right: -1rem; border-radius: 0 !important; }
            .quiz-content-grid { flex-direction: column; gap: 1.5rem; }
            .quiz-col-main { padding: 1.5rem; border-radius: 0; }
            .quiz-col-status { width: 100%; position: relative; top: 0; order: -1; padding: 1.5rem; border-radius: 0; }
        }
        .quiz-header-top { color: var(--color-primary); font-weight: 900; line-height: 1.1; }
        .question-box-wrapper { border: 1px solid #e2e8f0; border-radius: 0.5rem; overflow: hidden; background-color: #f8fafc; box-shadow: 0 1px 3px 0 rgba(0,0,0,0.05); transition: opacity 0.3s ease-in-out; }
        .question-box { background-color: white; border-left: 4px solid var(--color-secondary); padding: 1.5rem; }
        .result-correct { background-color: #f0fff4; border-left-color: #10B981; } 
        .result-incorrect { background-color: #fff5f5; border-left-color: var(--color-secondary); } 
        .radio-option { transition: all 0.2s; border: 1px solid #e5e7eb; background-color: #fff; }
        .radio-option:hover { border-color: var(--color-highlight); background-color: #fefce8; }
        .radio-option input:checked { accent-color: var(--color-secondary); }
        .radio-option input:checked + span { color: var(--color-primary); font-weight: 700; }
        .radio-option input:disabled + span { color: #9ca3af; }
        .radio-option input:disabled { background-color: #f3f4f6; border-color: #e5e7eb; }
        
        .btn-quiz-primary { background-color: var(--color-primary); color: var(--color-text-light); }
        .btn-quiz-primary:hover { background-color: #1a2b42; transform: translateY(-2px); box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1); }
        .btn-quiz-primary:disabled { background-color: #9ca3af; opacity: 0.7; cursor: not-allowed; }
        .btn-quiz-secondary { background-color: var(--color-secondary); color: var(--color-text-light); }
        .btn-quiz-secondary:hover { background-color: #7c1020; transform: translateY(-2px); box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1); }
        .quiz-nav-btn { transition: transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1); }
        
        .feedback-container {
            min-height: 50px; 
            transition: all 0.3s;
        }
        .feedback-box {
            padding: 1rem;
            border-radius: 0.5rem;
            font-weight: 700;
            display: block; 
            animation: fadeIn 0.3s;
        }
        .feedback-box .explanation-text {
            margin-top: 0.75rem;
            padding-top: 0.75rem;
            font-weight: 500;
        }
        
        .feedback-correct {
            background-color: #f0fff4; 
            border: 1px solid #68d391;
            color: #2f855a; 
        }
        .feedback-correct .explanation-text {
             border-top: 1px solid #c6f6d5; 
             color: #2f855a; 
        }
        
        .feedback-incorrect {
            background-color: #fff5f5; 
            border: 1px solid #fc8181; 
            color: #c53030; 
        }
        .feedback-incorrect .explanation-text {
             border-top: 1px solid #fed7d7; 
             color: #a02020; 
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
    
</head>
<body data-page-title="Questionario De Progreso Programa ADN" 
      data-page-subtitle="Semana <?php echo $class_number; ?>: Validación De Conocimiento" 
      data-page-icon="award">
    
    <div id="toast-container" class="toast-container"></div>
    
<?php include 'files/gtm-body.php'; ?> 

<div class="relative min-h-screen md:flex">
    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    <div id="task-panel-overlay" class="fixed inset-0 bg-black/60 z-40 hidden transition-opacity duration-300"></div>  
    
    <?php include 'adn-menu.php'; ?>
    
    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>

        <div id="content-area" class="p-4 md:p-8 space-y-8">
            
                        <div class="quiz-card-wrapper">
                <div class="quiz-content-grid">
                    
                    <div class="quiz-col-main">
                        
                             <div class="text-center mb-8">
                            <div class="flex items-center justify-center mb-4">
                                 <i data-lucide="award" class="w-10 h-10 text-[var(--color-secondary)] mx-auto"></i>
                            </div>
                            <h2 class="text-xl font-extrabold quiz-header-top">Cuestionario De Validación</h2>
                             <h2 class="text-5xl font-black uppercase quiz-header-top"><?php echo htmlspecialchars($current_class_title); ?></h2>
                            <h1 class="text-2xl font-black uppercase text-[var(--color-primary)]">Semana <?php echo $class_number; ?></h1>
                            <p class="text-sm text-gray-600 mt-2">Puntaje Mínimo Requerido Para Aprobar: <b><?php echo PASSING_SCORE; ?>/100</b> (<?php echo QUESTIONS_PER_QUIZ; ?> Preguntas de <?php echo POINTS_PER_QUESTION; ?> Puntos)</p>
                        </div>
                        
                        <?php if ($quiz_status === 'locked'): ?>
                            <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-6 mb-6 rounded-lg text-center" role="alert">
                                <i data-lucide="lock" class="w-8 h-8 mx-auto mb-3"></i>
                                <p class="font-black text-3xl uppercase">Acceso Bloqueado Temporalmente</p>
                                <p class="mt-3 text-lg font-semibold uppercase"><?php echo $quiz_message; ?></p>
                            </div>
                        
                        <?php elseif ($quiz_status === 'error'): ?>
                             <div class="bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 p-6 mb-6 rounded-lg text-center" role="alert">
                                <i data-lucide="alert-triangle" class="w-8 h-8 mx-auto mb-3"></i>
                                <p class="font-black text-2xl">Error</p>
                                <p class="mt-3 text-lg font-semibold"><?php echo $quiz_message; ?></p>
                            </div>

                        <?php elseif ($quiz_status === 'passed' || $quiz_status === 'failed'): ?>
                                                <div class="mb-8 p-4 bg-gray-50 rounded-lg shadow-inner">
                            <h3 class="text-2xl font-black text-[var(--color-primary)] mb-4 border-b pb-2 flex items-center gap-2">
                                <i data-lucide="list-checks" class="w-6 h-6 text-[var(--color-secondary)]"></i>
                                Revisión de Preguntas (Total: <?php echo $score; ?>/100)
                            </h3>
                            <div class="space-y-4">
                                <?php foreach ($results as $r): ?>
                                <div class="p-4 rounded-lg shadow-md border-l-8 <?php echo $r['is_correct'] ? 'result-correct' : 'result-incorrect'; ?>">
                                    <p class="font-bold text-gray-800 flex items-start">
                                        <i data-lucide="<?php echo $r['is_correct'] ? 'check' : 'x'; ?>" class="w-5 h-5 mr-3 mt-1 flex-shrink-0 <?php echo $r['is_correct'] ? 'text-green-600' : 'text-red-700'; ?>"></i>
                                        <?php echo htmlspecialchars($r['question']); ?>
                                    </p>
                                    <p class="text-sm ml-8 mt-1">
                                        Tu Respuesta: <span class="font-semibold <?php echo $r['is_correct'] ? 'text-green-700' : 'text-red-700'; ?>"><?php echo htmlspecialchars(ucfirst($r['user_answer'])); ?></span>
                                        <?php if (!$r['is_correct']): ?>
                                            | Correcta: <span class="font-semibold text-green-700"><?php echo htmlspecialchars(ucfirst($r['correct_answer'])); ?></span>
                                        <?php endif; ?>
                                    </p>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="text-center">
                            <a href="adn-dashboard.php" class="btn-quiz-secondary py-3 px-6 rounded-lg font-black uppercase inline-flex items-center quiz-nav-btn">
                                <i data-lucide="layout-dashboard" class="w-5 h-5 mr-2"></i> Volver al Dashboard
                            </a>
                        </div>

                        <?php else: // Oculta el formulario si hay un error o un resultado ?>
                                                
                        <p id="quiz-instrucciones" class="font-black text-[var(--color-primary)] bg-yellow-100 p-4 rounded-lg border-l-4 border-[var(--color-highlight)] flex items-center gap-2 mb-6">
                            <i data-lucide="info" class="w-5 h-5 flex-shrink-0"></i>
                            Seleccione Verdadero o Falso para cada pregunta. Progrese a la siguiente con el botón inferior.
                        </p>

                        <form method="POST" action="adn-quiz.php?unlock_id=<?php echo $class_to_unlock; ?>" id="quiz-form" class="space-y-4">
                            
                            <?php 
                            foreach ($current_quiz_questions as $index => $q): 
                            ?>
                            <div class="question-box-wrapper hidden" 
                                 data-question-index="<?php echo $index; ?>" 
                                 data-answer="<?php echo htmlspecialchars($q['a']); ?>" 
                                 data-explanation="<?php echo htmlspecialchars($q['e']); ?>"
                                 data-state="unanswered">
                                <div class="p-4 bg-gray-100 border-b border-gray-200">
                                    <p class="text-2xl font-black uppercase text-[var(--color-secondary)] flex items-center gap-2">
                                        <i data-lucide="zap" class="w-4 h-4"></i> Pregunta <span class="current-q-num"><?php echo $index + 1; ?></span>/<?php echo QUESTIONS_PER_QUIZ; ?> (<?php echo POINTS_PER_QUESTION; ?> Puntos)
                                    </p>
                                </div>
                                
                                <div class="question-box">
                                    <p class="text-2xl font-bold text-gray-800 mb-6"><?php echo htmlspecialchars($q['q']); ?></p>

                                    <div class="flex flex-col md:flex-row md:space-x-6 space-y-4 md:space-y-0">
                                        <label class="flex items-center space-x-3 text-lg font-black cursor-pointer p-3 rounded-lg flex-grow radio-option">
                                            <input type="radio" name="answer_<?php echo $index; ?>" value="verdadero" class="w-5 h-5 text-[var(--color-secondary)] focus:ring-[var(--color-highlight)]" required>
                                            <span>VERDADERO</span>
                                        </label>
                                        <label class="flex items-center space-x-3 text-lg font-black cursor-pointer p-3 rounded-lg flex-grow radio-option">
                                            <input type="radio" name="answer_<?php echo $index; ?>" value="falso" class="w-5 h-5 text-[var(--color-secondary)] focus:ring-[var(--color-highlight)]" required>
                                            <span>FALSO</span>
                                        </label>
                                    </div>

                                    <div class="feedback-container mt-4"></div>

                                </div>
                            </div>
                            <?php endforeach; ?>

                            <div class="flex justify-end items-center pt-4 space-x-4">
                                <a href="adn-video-semana.php?class=<?php echo $class_number; ?>" 
                                   class="py-2 px-4 rounded-lg font-bold flex items-center uppercase text-sm transition-all duration-300 quiz-nav-btn"
                                   style="
                                       background-color: var(--color-highlight); 
                                       color: var(--color-primary); 
                                       order: 1;
                                       box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
                                   "
                                >
                                    <i data-lucide="undo-2" class="w-4 h-4 mr-2 inline-block"></i> Volver a revisar el video
                                </a>
                                
                                <button type="button" id="next-question-btn" class="btn-quiz-primary font-bold py-3 px-6 rounded-lg flex items-center uppercase quiz-nav-btn" style="order: 2;">
                                    SIGUIENTE <i data-lucide="chevron-right" class="w-5 h-5 ml-2"></i>
                                </button>
                                
                                <button type="submit" id="submit-quiz-btn" class="btn-quiz-secondary font-bold py-3 px-6 rounded-lg flex items-center uppercase quiz-nav-btn hidden" style="order: 2;">
                                    FINALIZAR <i data-lucide="rocket" class="w-5 h-5 ml-2"></i>
                                </button>
                            </div>
                        </form>
                        
                        <?php endif; ?>
                        </div>
                    
                    <div class="quiz-col-status bg-[var(--color-primary)] text-[var(--color-text-light)]">
                        <div class="flex items-center text-2xl uppercase font-black mb-4 border-b border-gray-600 pb-3">
                            <i data-lucide="bar-chart-2" class="w-6 h-6 mr-2 text-[var(--color-highlight)]"></i>
                            Puntuación
                        </div>
                        
                        <?php if ($quiz_status === 'passed' || $quiz_status === 'failed'): ?>
                            <div class="space-y-3">
                                <p class="text-sm font-semibold text-gray-300">Resultado Final:</p>
                                <div class="w-full bg-gray-600 rounded-full h-2.5 mb-4">
                                    <div class="h-2.5 rounded-full <?php echo $quiz_status === 'passed' ? 'bg-green-500' : 'bg-red-500'; ?>" style="width: <?php echo ($correct_answers_count / QUESTIONS_PER_QUIZ) * 100; ?>%"></div>
                                </div>
                                <p class="text-3xl font-black text-[var(--color-text-light)]"><?php echo $score; ?>/100 Puntos</p>
                                <p class="text-lg font-bold <?php echo $quiz_status === 'passed' ? 'text-green-400' : 'text-red-400'; ?>"><?php echo $correct_answers_count; ?>/<?php echo QUESTIONS_PER_QUIZ; ?> Correctas</p>
                            </div>
                        <?php elseif ($quiz_status === 'locked'): ?>
                            <div class="text-center p-4">
                                <i data-lucide="hourglass" class="w-8 h-8 mx-auto text-[var(--color-highlight)] mb-2"></i>
                                <p class="font-bold text-lg uppercase text-[var(--color-highlight)]">Reintento Bloqueado</p>
                                <p class="text-sm mt-1 text-gray-300">Vuelve A Intentarlo En:</p>
                                <p class="font-black text-4xl text-[var(--color-secondary)] mt-1"><?php echo "{$hours}h {$minutes}m"; ?></p>
                            </div>
                        <?php else: // Estado 'en progreso' (default) ?>
                            <div class="space-y-4">
                                <div class="text-center">
                                    <p class="text-sm font-semibold text-gray-300 mb-1">PROGRESO ACTUAL</p>
                                    <p id="status-text" class="text-4xl font-black text-[var(--color-text-light)]">1/<?php echo QUESTIONS_PER_QUIZ; ?></p>
                                </div>
                                
                                <div class="w-full bg-gray-600 rounded-full h-2.5">
                                    <div id="progress-bar" class="bg-[var(--color-highlight)] h-2.5 rounded-full" style="width: <?php echo (1 / QUESTIONS_PER_QUIZ) * 100; ?>%"></div>
                                </div>
                                
                                <div class="mt-4 p-3 bg-gray-800 rounded-md text-sm text-[var(--color-text-light)]">
                                    <p class="font-bold flex text-lg items-center mb-1"><i data-lucide="info" class="w-4 h-4 mr-2 text-[var(--color-highlight)]"></i> Puntaje Requerido:</p>
                                    <p class="ml-6 font-black text-lg text-[var(--color-highlight)]"><?php echo PASSING_SCORE; ?>/100</p>
                                </div>
                                
                                <div class="mt-4 p-3 bg-gray-800 rounded-md text-sm text-[var(--color-text-light)]">
                                    <p class="font-bold text-lg flex items-center mb-1"><i data-lucide="check" class="w-4 h-4 mr-2 text-[var(--color-secondary)]"></i> Mínimo Correctas:</p>
                                    <p class="ml-6 font-black text-lg text-[var(--color-secondary)]"><?php echo ceil(PASSING_SCORE / POINTS_PER_QUESTION); ?>/<?php echo QUESTIONS_PER_QUIZ; ?></p>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>         </div>
    </main>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        if (typeof lucide !== 'undefined') { lucide.createIcons(); }
        
        // --- Lógica del Menú (sin cambios) ---
        const mobileMenuButton = document.getElementById('mobile-menu-button');
        const sidebar = document.getElementById('sidebar');
        const sidebarOverlay = document.getElementById('sidebar-overlay');
        if (mobileMenuButton && sidebar && sidebarOverlay) {
            mobileMenuButton.addEventListener('click', () => { 
                sidebar.classList.toggle('-translate-x-full'); 
                sidebarOverlay.classList.toggle('hidden'); 
            });
            sidebarOverlay.addEventListener('click', () => { 
                sidebar.classList.toggle('-translate-x-full'); 
                sidebarOverlay.classList.toggle('hidden'); 
            });
        }
        
        // --- Lógica de Navegación del Quiz ---
        const questionWrappers = document.querySelectorAll('.question-box-wrapper');
        const nextBtn = document.getElementById('next-question-btn');
        const submitBtn = document.getElementById('submit-quiz-btn');
        const quizForm = document.getElementById('quiz-form');
        const reviewLink = quizForm ? quizForm.querySelector('a') : null;
        
        const statusText = document.getElementById('status-text');
        const progressBar = document.getElementById('progress-bar');
        
        let currentQuestionIndex = 0;
        const totalQuestions = questionWrappers.length;
        
        if (totalQuestions > 0 && nextBtn && submitBtn) {
            const progressUnit = 100 / totalQuestions;
            questionWrappers[0].classList.remove('hidden');
            updateButtonsVisibility();

            function updateUI(index) {
                if (statusText) statusText.textContent = `${index + 1}/${totalQuestions}`;
                if (progressBar) progressBar.style.width = `${(index + 1) * progressUnit}%`;
                updateButtonsVisibility();
            }

            function updateButtonsVisibility() {
                const isLastQuestion = currentQuestionIndex === totalQuestions - 1;
                nextBtn.classList.toggle('hidden', isLastQuestion);
                submitBtn.classList.toggle('hidden', !isLastQuestion);
                
                const buttonContainer = nextBtn.parentElement;
                
                if(isLastQuestion) {
                    buttonContainer.classList.remove('justify-end', 'space-x-4');
                    buttonContainer.classList.add('justify-between'); 
                } else {
                    buttonContainer.classList.remove('justify-between');
                    buttonContainer.classList.add('justify-end', 'space-x-4');
                }
                
                if (submitBtn.classList.contains('hidden')) {
                    nextBtn.style.order = 2;
                } else {
                    submitBtn.style.order = 2;
                }
                if (reviewLink) reviewLink.style.order = 1;
            }
            
            function navigateToQuestion(index) {
                if (index >= 0 && index < totalQuestions) {
                    questionWrappers[currentQuestionIndex].classList.add('hidden');
                    currentQuestionIndex = index;
                    questionWrappers[currentQuestionIndex].classList.remove('hidden');
                    document.getElementById('content-area').scrollIntoView({ behavior: 'smooth', block: 'start' });
                    updateUI(currentQuestionIndex);
                }
            }
            
            // Función genérica para manejar el chequeo de respuesta
            function checkAnswer(currentQuestionDiv, isFinalQuestion = false) {
                const state = currentQuestionDiv.dataset.state;
                
                // Si ya está respondida, solo avanza (o envía)
                if (state === 'answered') {
                    if (!isFinalQuestion) {
                        navigateToQuestion(currentQuestionIndex + 1);
                    }
                    return true; // Devuelve true para que el form se envíe si es la final
                }
                
                // --- Si es la primera vez que se responde ---
                const correctAnswer = currentQuestionDiv.dataset.answer;
                const explanation = currentQuestionDiv.dataset.explanation;
                const currentQuestionName = 'answer_' + currentQuestionIndex;
                const answered = quizForm.querySelector(`input[name="${currentQuestionName}"]:checked`);
                
                if (!answered) {
                    showToast(isFinalQuestion ? 'Por favor, selecciona una opción para finalizar.' : 'Por favor, selecciona una opción para continuar.', 'warning');
                    return false; // No avanza, no envía
                }
                
                const radioButtons = currentQuestionDiv.querySelectorAll('input[type="radio"]');
                radioButtons.forEach(radio => radio.disabled = true);
                
                const feedbackBox = currentQuestionDiv.querySelector('.feedback-container');
                
                // ========= ¡LÓGICA DE FEEDBACK MODIFICADA! =========
                // Ahora la explicación se muestra en AMBOS casos.
                if (answered.value === correctAnswer) {
                    // --- RESPUESTA CORRECTA ---
                    feedbackBox.innerHTML = `<div class="feedback-box feedback-correct">
                        <div class="flex items-center gap-2"><i data-lucide="check-circle" class="w-5 h-5"></i> ¡Respuesta Correcta!</div>
                        <p class="explanation-text"><b>Por qué:</b> ${explanation}</p>
                    </div>`;
                } else {
                    // --- RESPUESTA INCORRECTA ---
                    feedbackBox.innerHTML = `<div class="feedback-box feedback-incorrect">
                        <div class="flex items-center gap-2"><i data-lucide="x-circle" class="w-5 h-5"></i> Respuesta Incorrecta. La respuesta correcta era: ${correctAnswer.toUpperCase()}</div>
                        <p class="explanation-text"><b>Por qué:</b> ${explanation}</p>
                    </div>`;
                }
                // ========= ¡FIN DE LÓGICA DE FEEDBACK! =========
                
                if (typeof lucide !== 'undefined') {
                    lucide.createIcons();
                }
                
                currentQuestionDiv.dataset.state = 'answered';
                
                // Si es la pregunta final, cambia el texto del botón
                if (isFinalQuestion) {
                    submitBtn.innerHTML = 'VER RESULTADOS <i data-lucide="rocket" class="w-5 h-5 ml-2"></i>';
                    if (typeof lucide !== 'undefined') {
                        lucide.createIcons();
                    }
                }
                
                return false; // No avanza ni envía, solo muestra feedback
            }

            // ========= LÓGICA DEL BOTÓN "SIGUIENTE" MODIFICADA =========
            nextBtn.addEventListener('click', () => {
                const currentQuestionDiv = questionWrappers[currentQuestionIndex];
                checkAnswer(currentQuestionDiv, false);
            });
            // ========= FIN DE LA LÓGICA "SIGUIENTE" =========

            
            // ========= LÓGICA DEL BOTÓN "FINALIZAR" MODIFICADA =========
            submitBtn.addEventListener('click', (e) => {
                const currentQuestionDiv = questionWrappers[currentQuestionIndex];
                
                // Llama a checkAnswer. Si devuelve 'false', previene el envío.
                // Si devuelve 'true' (porque ya estaba respondida), permite el envío.
                if (checkAnswer(currentQuestionDiv, true) === false) {
                    e.preventDefault(); 
                }
            });
            // ========= FIN DE LA LÓGICA "FINALIZAR" =========
        }
</script>
<script src="files/toast.js"></script>
</body>
</html>