<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Diagnóstico Libre - Compromiso de Gestión 3 - DIAGNOSTIKA</title>

        <!-- Fonts -->
        <link rel="preconnect" href="https://fonts.bunny.net">
        <link href="https://fonts.bunny.net/css?family=roboto:400,500,700&display=swap" rel="stylesheet" />

        <!-- Tailwind CSS -->
        @if (file_exists(public_path('build/manifest.json')) || file_exists(public_path('hot')))
            @vite(['resources/css/app.css', 'resources/js/app.js'])
        @else
            <script src="https://cdn.tailwindcss.com"></script>
        @endif

        <style>
            /* Estilos de grilla profesional para preguntas */
            .question-container {
                display: flex;
                flex-direction: column;
                gap: 0.75rem;
                margin-bottom: 0;
                padding: 1rem 0.75rem;
                border-radius: 6px;
                transition: background-color 0.2s ease;
                border: 1px solid #e5e7eb;
            }

            /* Responsive: desktop con flex-row */
            @media (min-width: 768px) {
                .question-container {
                    flex-direction: row;
                    justify-content: space-between;
                    align-items: center;
                    gap: 2rem;
                    padding: 1.5rem;
                }
            }

            /* Alternancia de colores para grilla - usando nth-of-type para contar solo question-container */
            .question-container:nth-of-type(odd) {
                background-color: #ffffff;
            }

            .question-container:nth-of-type(even) {
                background-color: #f8f9fa;
            }

            /* Hover effect para mejor interactividad */
            .question-container:hover {
                background-color: #f3f4f6;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            }

            .question-text {
                flex: 1;
                text-align: left;
            }

            .question-text p {
                font-size: 0.875rem;
            }

            @media (min-width: 768px) {
                .question-text p {
                    font-size: 1rem;
                }
            }

            .question-select {
                flex: 1;
            }

            @media (min-width: 768px) {
                .question-select {
                    flex: 0 0 200px;
                }
            }

            .error-message {
                color: #dc2626;
                font-size: 0.75rem;
                margin-top: 0.5rem;
            }

            /* Separador entre secciones de preguntas */
            .mt-12 {
                margin-top: 1.5rem;
                padding-top: 1.5rem;
            }

            @media (min-width: 768px) {
                .mt-12 {
                    margin-top: 2rem;
                    padding-top: 2rem;
                }
            }

            /* Espaciado adicional dentro de cada sección */
            .question-container:first-of-type {
                margin-top: 1rem;
            }

            /* Bordes suaves y colores profesionales para selects en grilla */
            .question-select select {
                background-color: white;
                border: 1px solid #d1d5db;
                border-radius: 4px;
                padding: 0.5rem 0.75rem;
                font-size: 0.875rem;
                width: 100%;
            }

            @media (min-width: 768px) {
                .question-select select {
                    width: auto;
                }
            }

            .question-select select:focus {
                border-color: #3b82f6;
                box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            }

            select:invalid {
                color: #999;
            }

            select {
                cursor: pointer;
            }

            /* Section headers responsive */
            h3 {
                font-size: 0.95rem;
            }

            @media (min-width: 768px) {
                h3 {
                    font-size: 1.125rem;
                }
            }

            /* Estilos para feedback de guardado */
            .save-indicator {
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 12px 20px;
                border-radius: 8px;
                font-size: 14px;
                font-weight: 500;
                opacity: 0;
                transform: translateY(-10px);
                transition: all 0.3s ease;
                z-index: 1000;
                display: flex;
                align-items: center;
                gap: 8px;
            }

            .save-indicator.show {
                opacity: 1;
                transform: translateY(0);
            }

            .save-indicator.saving {
                background-color: #3b82f6;
                color: white;
            }

            .save-indicator.saved {
                background-color: #10b981;
                color: white;
            }

            .save-indicator.error {
                background-color: #ef4444;
                color: white;
            }

            .spinner {
                border: 2px solid rgba(255, 255, 255, 0.3);
                border-top: 2px solid white;
                border-radius: 50%;
                width: 16px;
                height: 16px;
                animation: spin 0.6s linear infinite;
            }

            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }

            .animate-bounce-short {
                animation: bounce 0.4s ease-out;
            }

            @keyframes bounce {
                0% { transform: scale(0.9); opacity: 0; }
                100% { transform: scale(1); opacity: 1; }
            }

            .checkmark {
                width: 20px;
                height: 20px;
                border-radius: 50%;
                background-color: white;
                display: flex;
                align-items: center;
                justify-content: center;
                color: #10b981;
            }

            .progress-info {
                background-color: #dbeafe;
                border-left: 4px solid #3b82f6;
                padding: 12px 16px;
                margin-bottom: 16px;
                border-radius: 4px;
            }

            .progress-info-text {
                font-size: 14px;
                color: #1e40af;
            }

            .progress-bar {
                width: 100%;
                height: 6px;
                background-color: #e5e7eb;
                border-radius: 3px;
                overflow: hidden;
                margin-top: 8px;
            }

            .progress-bar-fill {
                height: 100%;
                background-color: #3b82f6;
                transition: width 0.3s ease;
                display: flex;
                align-items: center;
                justify-content: center;
                color: white;
                font-size: 10px;
                font-weight: bold;
            }

            /* Barra de progreso fija */
            #progress-bar-container {
                transition: all 0.3s ease;
                background: white;
                padding: 12px 16px;
            }

            #progress-bar-container.fixed {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                z-index: 50;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }

            /* Estilos responsivos para botones al pie */
            .button-footer {
                display: flex;
                gap: 0.5rem;
                justify-content: flex-end;
                flex-wrap: wrap;
                padding-top: 2rem;
                border-top: 1px solid #d1d5db;
            }

            @media (max-width: 640px) {
                .button-footer {
                    flex-direction: column;
                    gap: 0.75rem;
                    padding-top: 1.5rem;
                    align-items: center;
                }

                .button-footer a,
                .button-footer button {
                    width: 100%;
                    max-width: 300px;
                    padding: 0.75rem 1rem !important;
                    font-size: 0.95rem !important;
                    text-align: center;
                    margin: 0 auto;
                }
            }

            @media (min-width: 641px) and (max-width: 1024px) {
                .button-footer {
                    gap: 0.5rem;
                }

                .button-footer a,
                .button-footer button {
                    padding: 0.75rem 0.75rem !important;
                    font-size: 0.9rem !important;
                }
            }

            @media (min-width: 1025px) {
                .button-footer a,
                .button-footer button {
                    white-space: nowrap;
                }
            }
        </style>
    </head>
    <body class="min-h-screen bg-gradient-to-b from-blue-900 to-blue-800 font-sans">
        <!-- Header Navigation -->
        <header class="bg-blue-950 px-3 sm:px-6 py-3 sm:py-4 shadow-lg">
            <div class="max-w-7xl mx-auto flex justify-between items-center">
                <!-- Logo -->
                <div class="flex items-center">
                    <img src="{{ asset('images/logo.gif') }}" alt="DIAGNOSTIKA Logo" class="h-10 sm:h-16" />
                </div>
                
                <!-- Navigation Buttons -->
                <nav class="flex items-center gap-2 sm:space-x-4">
                    @auth
                        <div class="flex items-center gap-2 sm:space-x-3">
                            <span class="text-white font-semibold text-xs sm:text-base hidden sm:inline">{{ Auth::user()->name ?? 'Usuario' }}</span>
                            <form method="POST" action="{{ route('logout') }}" style="display:inline;">
                                @csrf
                                <button type="submit" class="text-white border border-white px-2 sm:px-4 py-1 sm:py-2 rounded text-xs sm:text-base hover:bg-red-600 hover:border-red-600 transition">
                                    Salir
                                </button>
                            </form>
                        </div>
                    @else
                        @if (Route::has('login'))
                            <a href="{{ route('login') }}" class="text-white border border-white px-2 sm:px-4 py-1 sm:py-2 rounded text-xs sm:text-base hover:bg-white hover:text-blue-900 transition">
                                Iniciar
                            </a>
                            @if (Route::has('register'))
                                <a href="{{ route('register') }}" class="bg-blue-600 text-white px-2 sm:px-4 py-1 sm:py-2 rounded text-xs sm:text-base hover:bg-blue-700 transition">
                                    Registrar
                                </a>
                            @endif
                        @endif
                    @endauth
                </nav>
            </div>
        </header>

        <!-- Main Content -->
        <main class="max-w-6xl mx-auto px-3 sm:px-6 py-6 sm:py-12">
            <!-- Page Title -->
            <div class="text-center mb-6 sm:mb-8">
                <h1 class="text-xl sm:text-3xl font-bold text-white mb-2 sm:mb-4">Ficha Diagnóstica - Instituciones Educativas</h1>
            </div>

            @if (session('success'))
                <div class="bg-green-100 border-l-4 border-green-600 p-4 mb-6 text-green-700">
                    {{ session('success') }}
                </div>
            @endif

            @if (session('warning'))
                <div class="bg-yellow-100 border-l-4 border-yellow-600 p-4 mb-6 text-yellow-700">
                    {{ session('warning') }}
                </div>
            @endif

            <!-- Auto-Save Indicator -->
            <div id="saveIndicator" class="save-indicator"></div>

            <div class="fixed inset-0 bg-black bg-opacity-60 flex items-center justify-center z-[9999] transition-opacity duration-300" id="modalDemo">
                <div class="bg-white rounded-2xl p-8 max-w-md w-full mx-4 shadow-2xl transform transition-all duration-300 scale-100 animate-bounce-short border-t-8 border-indigo-600">
                    <div class="text-center">
                        <div class="inline-flex items-center justify-center w-20 h-20 bg-indigo-100 rounded-full mb-6">
                            <i class="fas fa-flask text-indigo-600 text-4xl"></i>
                        </div>
                        <h2 class="text-3xl font-extrabold text-gray-900 mb-2">Modo de Prueba (DEMO)</h2>
                        <div class="w-16 h-1 bg-indigo-600 mx-auto mb-4 rounded-full"></div>
                        <p class="text-gray-600 text-lg mb-8 leading-relaxed">
                            ¡Bienvenido! Estás en una versión de demostración. Completa el <strong>Compromiso de Gestión 3</strong> de forma gratuita para ver un ejemplo de tus resultados.
                        </p>
                        <button onclick="document.getElementById('modalDemo').style.display='none'" 
                                class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-4 px-6 rounded-xl transition-all duration-200 transform hover:scale-[1.02] shadow-lg flex items-center justify-center gap-2 group">
                            <span>Comenzar ahora</span>
                            <i class="fas fa-arrow-right group-hover:translate-x-1 transition-transform"></i>
                        </button>
                    </div>
                </div>
            </div>

            <!-- White Container for Form -->
            <div class="bg-white rounded-lg shadow-xl p-4 sm:p-8">
                <!-- Subtitles -->
                <div class="mb-6 sm:mb-8">
                    <h2 class="text-lg sm:text-2xl font-bold text-blue-900 mb-2 sm:mb-4">COMPROMISO DE GESTIÓN 3 - GESTIÓN DE LAS CONDICIONES OPERATIVAS</h2>
                    <h3 class="text-base sm:text-lg font-semibold text-blue-800 mb-3 sm:mb-4">1. Práctica de gestión 1. - Calendarización: elaboración, difusión, seguimiento y prevención <span class="text-red-600">*</span></h3>
                </div>

                <!-- Progress Information -->
                <div id="progress-bar-container" class="progress-info">
                    <div class="progress-info-text text-xs sm:text-base">
                        <strong>Tu progreso:</strong> <span id="answeredCount">{{ $compromise ? count(array_filter([$compromise->pregunta_1, $compromise->pregunta_2, $compromise->pregunta_3, $compromise->pregunta_4, $compromise->pregunta_5, $compromise->pregunta_6, $compromise->pregunta_7, $compromise->pregunta_8, $compromise->pregunta_9, $compromise->pregunta_10, $compromise->pregunta_11, $compromise->pregunta_12, $compromise->pregunta_13, $compromise->pregunta_14, $compromise->pregunta_15, $compromise->pregunta_16, $compromise->pregunta_17, $compromise->pregunta_18, $compromise->pregunta_19, $compromise->pregunta_20, $compromise->pregunta_21, $compromise->pregunta_22, $compromise->pregunta_23, $compromise->pregunta_24, $compromise->pregunta_25])) : 0 }}</span>/25 preguntas respondidas
                    </div>
                    <div class="progress-bar">
                        <div class="progress-bar-fill" id="progressFill" style="width: {{ $compromise ? (count(array_filter([$compromise->pregunta_1, $compromise->pregunta_2, $compromise->pregunta_3, $compromise->pregunta_4, $compromise->pregunta_5, $compromise->pregunta_6, $compromise->pregunta_7, $compromise->pregunta_8, $compromise->pregunta_9, $compromise->pregunta_10, $compromise->pregunta_11, $compromise->pregunta_12, $compromise->pregunta_13, $compromise->pregunta_14, $compromise->pregunta_15, $compromise->pregunta_16, $compromise->pregunta_17, $compromise->pregunta_18, $compromise->pregunta_19, $compromise->pregunta_20, $compromise->pregunta_21, $compromise->pregunta_22, $compromise->pregunta_23, $compromise->pregunta_24, $compromise->pregunta_25])) / 25) * 100 : 0 }}%"></div>
                    </div>
                    <p class="text-xs text-gray-600 mt-2">✓ Los cambios se guardan automáticamente</p>
                </div>

                <!-- Important Note -->
                <div class="bg-blue-50 border-l-4 border-blue-900 p-3 sm:p-4 mb-6 sm:mb-8">
                    <p class="text-gray-800 font-semibold text-xs sm:text-sm">
                       “Es fundamental que asignes un número a cada pregunta de manera coherente con la realidad, ya que necesitamos identificar con precisión cuál es el aspecto más crítico según tu percepción y conocimiento de la IE.”
                    </p>
                </div>

                <!-- Form -->
                <form id="compromiseForm" method="GET" action="{{ route('resumen-compromiso1.libre') }}">
                    @csrf

                    <!-- Question 1 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700 text-sm sm:text-base">
                                Contamos con una calendarización oficial del año lectivo aprobada y comunicada a toda la comunidad (alumnos, docentes, directivos, padres responsables)
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_1" id="pregunta_1" class="w-full sm:w-auto px-3 py-2 sm:px-4 sm:py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900 text-sm sm:text-base" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_1 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_1 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_1 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_1 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_1 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_1" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 2 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                La calendarización se difunde oportunamente a docentes, familias y estudiantes por canales institucionales.
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_2" id="pregunta_2" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_2 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_2 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_2 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_2 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_2 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_2" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 3 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Realizamos seguimiento mensual del cumplimiento de la calendarización (con correcciones).
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_3" id="pregunta_3" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_3 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_3 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_3 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_3 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_3 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_3" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 4 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Identificamos con anticipación riesgos que puedan afectar el calendario (clima, obras, conflictos, salud pública) y tenemos medidas previstas.
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_4" id="pregunta_4" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_4 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_4 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_4 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_4 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_4 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_4" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 5 -->
                    <div class="question-container mb-8">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Cuando ocurre una contingencia reprogramamos sin perder el foco del tiempo lectivo y comunicamos los cambios oportunamente.
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_5" id="pregunta_5" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_5 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_5 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_5 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_5 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_5 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_5" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Section 2: Práctica de gestión 2 -->
                    <div class="mt-12 pt-8 border-t-2 border-gray-300">
                        <h3 class="text-lg font-semibold text-blue-800 mb-4">
                            2. Práctica de gestión 2. Matrícula oportuna y sin condicionamientos (acceso y continuidad) <span class="text-red-600">*</span>
                        </h3>
                    </div>

                    <!-- Question 6 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                El proceso de matrícula se realiza en las fechas previstas, sin generar colas ni demoras reiteradas.
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_6" id="pregunta_6" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_6 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_6 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_6 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_6 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_6 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_6" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 7 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Brindamos orientación clara sobre requisitos, vacantes y pasos del proceso, evitando interpretaciones discrecionales.
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_7" id="pregunta_7" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_7 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_7 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_7 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_7 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_7 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_7" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 8 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                La matrícula y/o ratificación se gestiona sin condicionamientos (pagos, compras u otros requisitos no autorizados).
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_8" id="pregunta_8" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_8 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_8 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_8 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_8 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_8 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_8" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 9 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Contamos con un procedimiento para continuidad de estudios (traslados, reincorporación, transferencias) de manera uniforme.
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_9" id="pregunta_9" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_9 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_9 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_9 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_9 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_9 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_9" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 10 -->
                    <div class="question-container mb-8">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Las familias conocen y usan canales de atención para dudas o reclamos sobre matrícula que atiende en plazos razonables.
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_10" id="pregunta_10" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_10 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_10 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_10 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_10 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_10 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_10" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Section 3: Práctica de gestión 3 -->
                    <div class="mt-12 pt-8 border-t-2 border-gray-300">
                        <h3 class="text-lg font-semibold text-blue-800 mb-4">
                            3. Práctica de gestión 3. Asistencia y puntualidad: estudiantes y personal (tiempo lectivo y de gestión) <span class="text-red-600">*</span>
                        </h3>
                    </div>

                    <!-- Question 11 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Registramos <strong>asistencia y tardanzas</strong> de estudiantes <strong>todos los días</strong> de manera consistente.
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_11" id="pregunta_11" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_11 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_11 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_11 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_11 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_11 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_11" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 12 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Analizamos la asistencia (tendencias, alertas) y activamos acciones cuando hay <strong>inasistencias repetidas</strong>.
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_12" id="pregunta_12" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_12 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_12 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_12 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_12 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_12 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_12" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 13 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Se controla y registra la <strong>asistencia y puntualidad del personal</strong> (docente y no docente).
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_13" id="pregunta_13" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_13 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_13 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_13 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_13 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_13 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_13" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 14 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                La IE implementa medidas para <strong>reducir la pérdida de tiempo lectivo</strong> (cambios de hora, reemplazos, suspensión de clases).
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_14" id="pregunta_14" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_14 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_14 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_14 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_14 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_14 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_14" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 15 -->
                    <div class="question-container mb-8">
                        <div class="question-text">
                            <p class="text-gray-700">
                                La jornada escolar se cumple con <strong>inicio y cierre efectivos</strong>, evitando interrupciones no planificadas.
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_15" id="pregunta_15" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_15 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_15 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_15 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_15 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_15 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_15" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Section 4: Práctica de gestión 5 -->
                    <div class="mt-12 pt-8 border-t-2 border-gray-300">
                        <h3 class="text-lg font-semibold text-blue-800 mb-4">
                            4. Práctica de gestión 5. Entrega oportuna y uso de materiales y recursos educativos <span class="text-red-600">*</span>
                        </h3>
                    </div>

                    <!-- Question 16 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Los materiales educativos son suficientes para el inicio, desarrollo y finalización del periodo lectivo.
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_16" id="pregunta_16" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_16 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_16 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_16 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_16 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_16 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_16" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 17 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Existe un control de recepción, registro y distribución de materiales por grado/ área/aula.
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_17" id="pregunta_17" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_17 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_17 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_17 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_17 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_17 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_17" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 18 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Los docentes promueven y dan el uso pedagógico de los materiales (no se quedan almacenados).
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_18" id="pregunta_18" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_18 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_18 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_18 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_18 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_18 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_18" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 19 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Cuando faltan materiales, la IE activa alternativas viables (reposición, préstamo, recursos locales, estrategias de aula).
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_19" id="pregunta_19" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_19 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_19 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_19 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_19 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_19 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_19" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 20 -->
                    <div class="question-container mb-8">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Se prioriza el uso de recursos considerando la diversidad del estudiantado (adaptaciones, apoyos, accesibilidad).
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_20" id="pregunta_20" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_20 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_20 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_20 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_20 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_20 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_20" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Section 5: Práctica de gestión 6 -->
                    <div class="mt-12 pt-8 border-t-2 border-gray-300">
                        <h3 class="text-lg font-semibold text-blue-800 mb-4">
                            5. Práctica de gestión 6. Infraestructura, equipamiento y mobiliario: gestión y mantenimiento <span class="text-red-600">*</span>
                        </h3>
                    </div>

                    <!-- Question 21 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                La IE cuenta con un inventario actualizado de infraestructura, equipamiento y mobiliario (estado y ubicación).
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_21" id="pregunta_21" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_21 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_21 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_21 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_21 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_21 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_21" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 22 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Se ejecuta mantenimiento preventivo (no solo correctivo) de servicios básicos y ambientes (agua, electricidad, SS.HH., techos, etc.).
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_22" id="pregunta_22" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_22 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_22 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_22 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_22 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_22 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_22" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 23 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                El mobiliario es suficiente y funcional para la matrícula atendida (sin hacinamiento ni improvisaciones).
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_23" id="pregunta_23" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_23 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_23 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_23 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_23 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_23 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_23" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 24 -->
                    <div class="question-container mb-6">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Los ambientes cumplen condiciones mínimas de seguridad y funcionalidad (iluminación, ventilación, señalización, rutas).
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_24" id="pregunta_24" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_24 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_24 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_24 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_24 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_24 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_24" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Question 25 -->
                    <div class="question-container mb-8">
                        <div class="question-text">
                            <p class="text-gray-700">
                                Cuando se detecta una necesidad crítica (riesgo/colapso/falla), se actúa con priorización y registro (reporte, acción, responsable, fecha).
                            </p>
                        </div>
                        <div class="question-select">
                            <select name="pregunta_25" id="pregunta_25" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-900 focus:ring-2 focus:ring-blue-900" onchange="handleSelectChange(this)">
                                <option value="">Seleccionar...</option>
                                <option value="1" @if($compromise && $compromise->pregunta_25 == 1) selected @endif>1 - Nunca</option>
                                <option value="2" @if($compromise && $compromise->pregunta_25 == 2) selected @endif>2 - Rara vez</option>
                                <option value="3" @if($compromise && $compromise->pregunta_25 == 3) selected @endif>3 - A veces</option>
                                <option value="4" @if($compromise && $compromise->pregunta_25 == 4) selected @endif>4 - Casi siempre</option>
                                <option value="5" @if($compromise && $compromise->pregunta_25 == 5) selected @endif>5 - Siempre</option>
                            </select>
                            <div id="error_25" class="error-message"></div>
                        </div>
                    </div>

                    <!-- Validation Message -->
                    <div id="validationMessage" class="bg-red-50 border-l-4 border-red-600 p-4 mb-6 hidden">
                        <p class="text-red-700 font-semibold text-sm">
                            ⚠️ Debes responder todas las preguntas antes de continuar. Faltan <span id="missingCount">0</span> preguntas por responder.
                        </p>
                    </div>

                    <!-- Buttons -->
                    <div class="button-footer">
                        <a 
                            href="{{ route('dashboard') }}"
                            class="px-6 sm:px-8 py-3 border border-gray-400 text-gray-700 rounded-lg font-semibold hover:bg-gray-100 transition"
                        >
                            ← Atrás
                        </a>
                        <button 
                            type="button"
                            id="resumeBtn"
                            onclick="window.location.href='{{ route('resumen-compromiso1.libre') }}'"
                            class="px-6 sm:px-8 py-3 border border-green-500 text-green-700 rounded-lg font-semibold hover:bg-green-50 transition disabled:opacity-50 disabled:cursor-not-allowed"
                            disabled
                        >
                            📊 Ver Resumen
                        </button>
                        <button 
                            type="submit" 
                            class="px-6 sm:px-12 py-3 bg-blue-900 text-white rounded-lg font-semibold hover:bg-blue-800 transition disabled:opacity-50 disabled:cursor-not-allowed"
                            id="submitBtn"
                            disabled
                        >
                            Finalizar y Ver Resumen
                        </button>
                    </div>
                </form>
            </div>
        </main>

        <!-- Footer -->
        <footer class="bg-blue-950 text-blue-100 py-6 mt-12">
            <div class="max-w-7xl mx-auto px-6 text-center">
                <p>&copy; 2026 DIAGNOSTIKA. Herramienta de Evaluación Educativa</p>
            </div>
        </footer>

        <script>
            const form = document.getElementById('compromiseForm');
            const selectsNodeList = document.querySelectorAll('select[name^="pregunta_"]');
            const selects = Array.from(selectsNodeList); // Convertir NodeList a Array
            const errorSummary = document.getElementById('errorSummary');
            const saveIndicator = document.getElementById('saveIndicator');
            const validationMessage = document.getElementById('validationMessage');
            const submitBtn = document.getElementById('submitBtn');
            const resumeBtn = document.getElementById('resumeBtn');
            let saveTimer;

            // Función para verificar si todas las preguntas están respondidas
            function checkAllQuestionsAnswered() {
                const answeredQuestions = selects.filter(select => select.value !== '').length;
                const totalQuestions = selects.length;
                const allAnswered = answeredQuestions === totalQuestions;
                const missingCount = totalQuestions - answeredQuestions;

                // Actualizar estado de ambos botones
                submitBtn.disabled = !allAnswered;
                resumeBtn.disabled = !allAnswered;
                
                // Mostrar/ocultar mensaje de validación
                if (!allAnswered) {
                    validationMessage.classList.remove('hidden');
                    document.getElementById('missingCount').textContent = missingCount;
                } else {
                    validationMessage.classList.add('hidden');
                }

                return allAnswered;
            }

            // Función para mostrar indicador de guardado
            function showSaveIndicator(type, message) {
                clearTimeout(saveTimer);
                
                // Limpiar clases anteriores
                saveIndicator.className = 'save-indicator show ' + type;
                
                // Crear contenido del indicador
                let content = '';
                if (type === 'saving') {
                    content = '<div class="spinner"></div>' + message;
                } else if (type === 'saved') {
                    content = '<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/></svg>' + message;
                } else if (type === 'error') {
                    content = '<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/></svg>' + message;
                }
                
                saveIndicator.innerHTML = content;
                
                // Auto-ocultar después de 3 segundos (solo para guardado exitoso)
                if (type === 'saved') {
                    saveTimer = setTimeout(() => {
                        saveIndicator.classList.remove('show');
                    }, 3000);
                }
            }

            // Función para actualizar la barra de progreso general
            function updateGeneralProgressBar() {
                const totalQuestions = selects.length;
                const answeredQuestions = selects.filter(select => select.value !== '').length;
                const progressPercentage = (answeredQuestions / totalQuestions) * 100;

                const progressFill = document.getElementById('progressFill');
                const answeredCount = document.getElementById('answeredCount');
                
                progressFill.style.width = `${progressPercentage}%`;
                answeredCount.textContent = answeredQuestions;
                
                // Actualizar colores de los selects
                updateSelectColors();
            }

            // Función para actualizar colores de selects
            function updateSelectColors() {
                selects.forEach((select, index) => {
                    const hasValue = select.value !== '' && select.value;
                    
                    if (hasValue) {
                        // Aplicar estilos verde claro con !important si es necesario
                        select.style.cssText = `
                            background-color: #dcfce7 !important;
                            border-color: #86efac !important;
                            border-width: 2px !important;
                            color: #166534 !important;
                            font-weight: 500 !important;
                        `;
                    } else {
                        // Restaurar estilos por defecto
                        select.style.cssText = `
                            background-color: transparent;
                            border-color: #d1d5db;
                            border-width: 1px;
                            color: inherit;
                            font-weight: 400;
                        `;
                    }
                });
            }

            // Función manejadora central para cambios en selects
            function handleSelectChange(selectElement) {
                // Actualizar progreso visual siempre
                updateGeneralProgressBar();
                
                // Intentar guardar progreso
                saveProgress();
            }

            // Función para guardar progreso automáticamente
            function saveProgress() {
                // Mostrar indicador de guardando
                showSaveIndicator('saving', 'Guardando...');

                const formData = new FormData();
                
                // Enviar todos los valores (incluso vacíos) para auto-guardado
                const selects = Array.from(document.querySelectorAll('.question-select select'));
                selects.forEach(select => {
                    formData.append(select.name, select.value || '');
                });

                const token = document.querySelector('input[name="_token"]');
                if (!token) {
                    showSaveIndicator('error', '✗ Error: Token CSRF no encontrado');
                    return;
                }
                formData.append('_token', token.value);

                fetch('{{ route("compromiso1.saveProgressLibre") }}', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': token.value
                    }
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        // Mostrar éxito con información de progreso
                        showSaveIndicator('saved', '✓ Guardado (' + data.answered + '/25)');
                    } else {
                        showSaveIndicator('error', '✗ ' + (data.message || 'Error al guardar'));
                    }
                })
                .catch(error => {
                    console.error('Error de guardado:', error);
                    showSaveIndicator('error', '✗ Error en la conexión');
                });
            }

            // Validar valores únicos por sección
            function validateUniqueValues(section) {
                // Obtener las preguntas de la sección: 1-5 para sección 1, 6-10 para sección 2, 11-15 para sección 3
                const sectionRanges = {
                    1: { start: 1, end: 5 },
                    2: { start: 6, end: 10 },
                    3: { start: 11, end: 15 },
                    4: { start: 16, end: 20 },
                    5: { start: 21, end: 25 }
                };
                
                const range = sectionRanges[section];
                const sectionSelects = Array.from(selects).filter(select => {
                    const questionNum = parseInt(select.name.replace('pregunta_', ''));
                    return questionNum >= range.start && questionNum <= range.end;
                });
                
                const values = sectionSelects
                    .map(select => select.value)
                    .filter(value => value !== '');

                // Verificar duplicados
                const uniqueValues = new Set(values);
                const hasDuplicates = values.length !== uniqueValues.size;

                // Limpiar mensajes de error previos
                sectionSelects.forEach(select => {
                    const questionNum = select.name.replace('pregunta_', '');
                    const errorDiv = document.getElementById(`error_${questionNum}`);
                    if (errorDiv) {
                        errorDiv.textContent = '';
                    }
                    select.classList.remove('border-red-600', 'ring-red-600');
                });

                if (hasDuplicates) {
                    const valueCount = {};
                    sectionSelects.forEach(select => {
                        if (select.value !== '') {
                            valueCount[select.value] = (valueCount[select.value] || 0) + 1;
                        }
                    });

                    sectionSelects.forEach(select => {
                        if (select.value !== '' && valueCount[select.value] > 1) {
                            const questionNum = select.name.replace('pregunta_', '');
                            const errorDiv = document.getElementById(`error_${questionNum}`);
                            if (errorDiv) {
                                errorDiv.textContent = '⚠️ Este valor ya está seleccionado en esta sección';
                            }
                            select.classList.add('border-red-600', 'ring-red-600');
                        }
                    });

                    return false;
                }

                return true;
            }

            // Event listeners
            selects.forEach(select => {
                select.addEventListener('change', () => {
                    const questionNum = parseInt(select.name.replace('pregunta_', ''));
                    let section;
                    if (questionNum <= 5) {
                        section = 1;
                    } else if (questionNum <= 10) {
                        section = 2;
                    } else if (questionNum <= 15) {
                        section = 3;
                    } else if (questionNum <= 20) {
                        section = 4;
                    } else {
                        section = 5;
                    }
                    updateGeneralProgressBar(); // Actualizar barra de progreso general siempre
                    checkAllQuestionsAnswered(); // Verificar si todas están respondidas
                    saveProgress(); // Auto-guardar al cambiar
                });
            });

            // Validar al enviar el formulario
            form.addEventListener('submit', (e) => {
                if (!checkAllQuestionsAnswered()) {
                    e.preventDefault();
                    // Scroll hacia el mensaje de validación
                    validationMessage.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
            });

            // Inicializar la barra de progreso al cargar la página
            document.addEventListener('DOMContentLoaded', () => {
                updateGeneralProgressBar();
                checkAllQuestionsAnswered(); // Inicializar estado del botón
            });

            // Hacer que la barra de progreso sea fija al hacer scroll
            window.addEventListener('scroll', () => {
                const progressBarContainer = document.getElementById('progress-bar-container');
                const whiteBg = document.querySelector('.bg-white');
                
                if (progressBarContainer && whiteBg) {
                    const whiteContainerTop = whiteBg.offsetTop;
                    
                    if (window.scrollY > whiteContainerTop) {
                        progressBarContainer.classList.add('fixed');
                        // Agregar margen superior al contenedor blanco para compensar la barra fija
                        whiteBg.style.marginTop = '140px';
                    } else {
                        progressBarContainer.classList.remove('fixed');
                        whiteBg.style.marginTop = '0';
                    }
                }
            });
        </script>

        <!-- WhatsApp Button -->
        @include('components.whatsapp-button')
    </body>
</html>
