<!DOCTYPE html> 
<html lang="es">
<head>
    <link rel="shortcut icon" href="../../img/ElCobre.ico">
    <link rel="stylesheet" href="../CSS/agendarcss.css">
    <link rel="stylesheet" href="../CSS/agendarcss2.css">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Enlaces y Tablets</title>
    
    <!-- CORREGIDO: Cambiado a Tailwind CSS producción -->
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    
    <!-- Evitar click derecho -->
    <script>
        document.addEventListener('contextmenu', function(e) {
            e.preventDefault();
        });
    </script>
    
    <!-- Fuentes e iconos -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">

    <!-- Estilos mejorados CON LÍMITES -->
    <style>
        /* ESTILOS PARA BÚSQUEDA DE USUARIOS */
        .users-search-section {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border: 2px solid #6c757d;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 25px;
        }

        .users-search-section h4 {
            color: #495057;
            margin-bottom: 15px;
            font-size: 1.1rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .search-filters {
            display: grid;
            grid-template-columns: 2fr 1fr auto;
            gap: 15px;
            align-items: end;
        }

        .search-input-group {
            position: relative;
        }

        .search-input-group input {
            width: 100%;
            padding: 12px 45px 12px 15px;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
            background: white;
        }

        .search-input-group input:focus {
            border-color: #6c757d;
            outline: none;
            box-shadow: 0 0 0 3px rgba(108, 117, 125, 0.1);
        }

        .search-input-group .search-icon {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
            pointer-events: none;
        }

        .role-filter-group select {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            font-size: 14px;
            background: white;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .role-filter-group select:focus {
            border-color: #6c757d;
            outline: none;
            box-shadow: 0 0 0 3px rgba(108, 117, 125, 0.1);
        }

        .clear-search-btn {
            background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
            height: fit-content;
        }

        .clear-search-btn:hover {
            background: linear-gradient(135deg, #495057 0%, #343a40 100%);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(108, 117, 125, 0.3);
        }

        .search-results-info {
            margin-top: 15px;
            padding: 10px 15px;
            background: rgba(108, 117, 125, 0.1);
            border-radius: 8px;
            font-size: 13px;
            color: #495057;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .search-results-info.no-results {
            background: rgba(220, 53, 69, 0.1);
            color: #dc3545;
            border: 1px solid rgba(220, 53, 69, 0.2);
        }

        .search-results-info.has-results {
            background: rgba(40, 167, 69, 0.1);
            color: #28a745;
            border: 1px solid rgba(40, 167, 69, 0.2);
        }

        /* Destacar usuarios en resultados de búsqueda */
        .user-card.search-match {
            border: 2px solid #28a745;
            box-shadow: 0 4px 16px rgba(40, 167, 69, 0.2);
            background: linear-gradient(135deg, #f8fff9 0%, #e8f5e9 100%);
        }

        .user-card.search-match .user-name {
            color: #1e7e34;
        }

        /* Responsive para búsqueda */
        @media (max-width: 768px) {
            .search-filters {
                grid-template-columns: 1fr;
                gap: 12px;
            }
            
            .clear-search-btn {
                justify-self: center;
                width: fit-content;
            }
        }
        /* ESTILOS PARA INDICADOR DE LÍMITES DE RESERVAS */
        .reservation-limits-panel {
            background: linear-gradient(135deg, #f8f9fa 0%, #e3f2fd 100%);
            border: 2px solid #2196f3;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 25px;
            position: relative;
            overflow: hidden;
        }

        .reservation-limits-panel::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #2196f3, #1976d2, #0d47a1);
            animation: shimmer 2s infinite;
        }

        @keyframes shimmer {
            0% { transform: translateX(-100%); }
            100% { transform: translateX(100%); }
        }

        .limits-header {
            color: #1976d2;
            font-size: 1.2rem;
            font-weight: 700;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .limits-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-top: 15px;
        }

        .limit-card {
            background: white;
            border-radius: 12px;
            padding: 15px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .limit-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 16px rgba(0,0,0,0.15);
        }

        .limit-card.enlaces {
            border-left: 4px solid #4caf50;
        }

        .limit-card.tablets {
            border-left: 4px solid #ff9800;
        }

        .limit-card.warning {
            border-left: 4px solid #f44336;
            background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
        }

        .limit-card.warning .limit-icon {
            color: #f44336 !important;
        }

        .limit-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 10px;
        }

        .limit-title {
            font-weight: 600;
            color: #2c3e50;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .limit-icon {
            font-size: 1.2rem;
        }

        .limit-icon.enlaces {
            color: #4caf50;
        }

        .limit-icon.tablets {
            color: #ff9800;
        }

        .limit-badge {
            padding: 4px 8px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .limit-badge.available {
            background: #e8f5e8;
            color: #2e7d32;
        }

        .limit-badge.warning {
            background: #fff3e0;
            color: #e65100;
        }

        .limit-badge.danger {
            background: #ffebee;
            color: #c62828;
        }

        .limit-progress {
            margin: 10px 0;
        }

        .limit-progress-bar {
            width: 100%;
            height: 8px;
            background: #e0e0e0;
            border-radius: 4px;
            overflow: hidden;
            margin-bottom: 5px;
        }

        .limit-progress-fill {
            height: 100%;
            border-radius: 4px;
            transition: all 0.3s ease;
        }

        .limit-progress-fill.enlaces {
            background: linear-gradient(90deg, #81c784, #4caf50);
        }

        .limit-progress-fill.tablets {
            background: linear-gradient(90deg, #ffb74d, #ff9800);
        }

        .limit-progress-fill.warning {
            background: linear-gradient(90deg, #ff8a65, #f44336);
        }

        .limit-text {
            font-size: 12px;
            color: #666;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .limit-details {
            font-size: 13px;
            color: #333;
            margin-top: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .limit-remaining {
            font-weight: 700;
            color: #2196f3;
        }

        .admin-unlimited-badge {
            background: linear-gradient(45deg, #ffd700, #ffed4e);
            color: #333;
            padding: 8px 16px;
            border-radius: 25px;
            font-weight: 700;
            text-align: center;
            border: 2px solid #d4af37;
            box-shadow: 0 4px 12px rgba(255, 215, 0, 0.3);
            animation: goldGlow 2s infinite alternate;
        }

        @keyframes goldGlow {
            0% { box-shadow: 0 4px 12px rgba(255, 215, 0, 0.3); }
            100% { box-shadow: 0 6px 20px rgba(255, 215, 0, 0.5); }
        }

        .limits-info-text {
            margin-top: 15px;
            padding: 12px;
            background: rgba(255, 255, 255, 0.7);
            border-radius: 10px;
            font-size: 12px;
            color: #555;
            border-left: 3px solid #2196f3;
        }

        /* ESTILOS PARA MODAL DE CAMBIO DE CONTRASEÑA */
        .password-change-section {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 25px;
            border-radius: 12px;
            margin-bottom: 30px;
            border: 2px solid #667eea;
        }

        .password-change-section h4 {
            color: #667eea;
            margin-bottom: 20px;
            font-size: 1.2rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .password-strength-indicator {
            margin-top: 8px;
            height: 4px;
            background: #e0e0e0;
            border-radius: 2px;
            overflow: hidden;
            transition: all 0.3s ease;
        }

        .password-strength-fill {
            height: 100%;
            border-radius: 2px;
            transition: all 0.3s ease;
        }

        .password-strength-weak { background: #f44336; width: 25%; }
        .password-strength-fair { background: #ff9800; width: 50%; }
        .password-strength-good { background: #2196f3; width: 75%; }
        .password-strength-strong { background: #4caf50; width: 100%; }

        .password-requirements {
            margin-top: 10px;
            font-size: 12px;
            color: #666;
        }

        .password-requirement {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 4px;
        }

        .password-requirement.met {
            color: #4caf50;
        }

        .password-requirement.unmet {
            color: #f44336;
        }

        .toggle-password {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #666;
            cursor: pointer;
            padding: 5px;
            transition: color 0.2s ease;
        }

        .toggle-password:hover {
            color: #333;
        }

        .password-input-group {
            position: relative;
        }

        .password-input-group input {
            padding-right: 45px;
        }

        /* Animación para feedback de contraseña cambiada */
        .password-success-animation {
            background: linear-gradient(135deg, #e8f5e8 0%, #f1f8e9 100%);
            border-color: #4caf50;
            animation: successPulse 2s ease-in-out;
        }

        @keyframes successPulse {
            0%, 100% { 
                transform: scale(1);
                box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
            }
            50% { 
                transform: scale(1.02);
                box-shadow: 0 4px 16px rgba(76, 175, 80, 0.4);
            }
        }

        /* NUEVOS ESTILOS PARA CANCELACIÓN DE USUARIOS */
        
        /* Indicador de reserva propia */
        .time-slot.own-reservation {
            border-left: 4px solid #2196f3;
            background: linear-gradient(135deg, #e3f2fd 0%, #f0f8ff 100%);
            position: relative;
        }

        .time-slot.own-reservation::before {
            content: "👤 Mi Reserva";
            position: absolute;
            top: -10px;
            right: 10px;
            background: #2196f3;
            color: white;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            box-shadow: 0 2px 8px rgba(33, 150, 243, 0.3);
            z-index: 5;
        }

        /* Estado de cancelación pendiente */
        .cancellation-pending {
            opacity: 0.7;
            position: relative;
            transition: all 0.3s ease;
            pointer-events: none;
        }

        .cancellation-pending::after {
            content: "Cancelando...";
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(244, 67, 54, 0.95);
            color: white;
            padding: 8px 16px;
            border-radius: 6px;
            font-size: 12px;
            font-weight: 600;
            z-index: 10;
            box-shadow: 0 4px 12px rgba(244, 67, 54, 0.3);
            animation: pulse 2s infinite;
        }

        /* Animación de pulso para el indicador de cancelación */
        @keyframes pulse {
            0% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
            50% { opacity: 0.8; transform: translate(-50%, -50%) scale(1.05); }
            100% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
        }

        /* Botones de cancelación mejorados */
        .btn.btn-warning {
            background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
            border: none;
            color: white;
            font-weight: 600;
            padding: 8px 16px;
            border-radius: 8px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            box-shadow: 0 2px 8px rgba(255, 152, 0, 0.2);
            position: relative;
            overflow: hidden;
        }

        .btn.btn-warning::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s;
        }

        .btn.btn-warning:hover::before {
            left: 100%;
        }

        .btn.btn-warning:hover {
            background: linear-gradient(135deg, #f57c00 0%, #e65100 100%);
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(255, 152, 0, 0.4);
        }

        /* Botón para cancelar reserva propia */
        .btn.btn-cancel-own {
            background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
            border: none;
            color: white;
            font-weight: 600;
            padding: 8px 16px;
            border-radius: 8px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            box-shadow: 0 2px 8px rgba(255, 112, 67, 0.2);
            position: relative;
            overflow: hidden;
        }

        .btn.btn-cancel-own:hover {
            background: linear-gradient(135deg, #ff5722 0%, #d84315 100%);
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(255, 112, 67, 0.4);
        }

        /* Mensajes informativos mejorados */
        .info-message {
            background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
            border: 1px solid #ff9800;
            border-left: 4px solid #ff9800;
            color: #e65100;
            padding: 12px;
            border-radius: 8px;
            margin-top: 10px;
            font-size: 12px;
            display: flex;
            align-items: flex-start;
            gap: 10px;
            flex-direction: column;
            box-shadow: 0 2px 8px rgba(255, 152, 0, 0.1);
            animation: slideInUp 0.3s ease-out;
        }

        .info-message.success {
            background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c8 100%);
            border-color: #4caf50;
            color: #2e7d32;
        }

        .info-message.error {
            background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
            border-color: #f44336;
            color: #c62828;
        }

        @keyframes slideInUp {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .info-message i {
            color: inherit;
            font-size: 16px;
            margin-top: 2px;
        }

        .info-message span {
            font-weight: 600;
            margin-bottom: 4px;
            color: inherit;
        }

        .info-message small {
            line-height: 1.4;
            opacity: 0.9;
            color: inherit;
        }

        /* Estilos para horarios restringidos */
        .time-slot.restricted {
            border-left-color: #f44336;
            background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
            cursor: not-allowed;
        }

        .time-slot.restricted .status-pill.restricted {
            background-color: #ff9800;
            color: white;
        }

        .time-slot.restricted .reservation-details {
            color: #e65100;
        }

        /* Estilos para restricción de acceso */
        .restricted-access-notice {
            background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
            border: 2px solid #ff9800;
            border-radius: 12px;
            padding: 25px;
            text-align: center;
            margin: 20px 0;
        }

        .restricted-access-notice h4 {
            color: #e65100;
            margin-bottom: 15px;
            font-size: 1.3rem;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .restricted-access-notice p {
            color: #bf360c;
            font-size: 1rem;
            margin-bottom: 0;
        }

        .admin-tab-btn.restricted {
            opacity: 0.5;
            cursor: not-allowed;
            background: #f5f5f5;
            color: #999;
        }

        .admin-tab-btn.restricted:hover {
            background: #f5f5f5;
            color: #999;
            transform: none;
        }

        .admin-with-limits-badge {
            background: linear-gradient(45deg, #ff9800, #f57c00);
            color: white;
            padding: 4px 8px;
            border-radius: 8px;
            font-size: 11px;
            font-weight: bold;
            margin-left: 8px;
            border: 1px solid #e65100;
            box-shadow: 0 2px 4px rgba(255, 152, 0, 0.3);
        }

        .super-admin-badge {
            background: linear-gradient(45deg, #ffd700, #ffed4e);
            color: #333;
            padding: 4px 8px;
            border-radius: 8px;
            font-size: 11px;
            font-weight: bold;
            margin-left: 8px;
            border: 1px solid #d4af37;
            box-shadow: 0 2px 4px rgba(255, 215, 0, 0.3);
        }

        /* Mejorar la visualización de acciones */
        .action-buttons {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 12px;
            align-items: center;
        }

        .action-buttons .btn {
            font-size: 12px;
            padding: 6px 12px;
            min-height: 32px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        /* Indicador de estado mejorado */
        .reservation-status-indicator {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            margin-top: 8px;
            padding: 6px 10px;
            border-radius: 8px;
            font-size: 11px;
            font-weight: 600;
        }

        .reservation-status-indicator.pending {
            background: rgba(255, 152, 0, 0.1);
            color: #f57c00;
            border: 1px solid rgba(255, 152, 0, 0.3);
        }

        .reservation-status-indicator.confirmed {
            background: rgba(76, 175, 80, 0.1);
            color: #2e7d32;
            border: 1px solid rgba(76, 175, 80, 0.3);
        }

        .reservation-status-indicator.no-show {
            background: rgba(244, 67, 54, 0.1);
            color: #c62828;
            border: 1px solid rgba(244, 67, 54, 0.3);
        }

        .own-reservation-indicator {
            background: linear-gradient(45deg, #2196f3, #1976d2);
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 10px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 4px;
            margin-bottom: 8px;
            box-shadow: 0 2px 6px rgba(33, 150, 243, 0.3);
        }

        /* NUEVOS ESTILOS PARA ALERTAS DE LÍMITES */
        .limit-reached-alert {
            background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
            border: 2px solid #f44336;
            border-radius: 12px;
            padding: 20px;
            margin: 15px 0;
            color: #c62828;
            text-align: center;
            animation: limitAlert 3s ease-in-out;
        }

        @keyframes limitAlert {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.02); }
        }

        .limit-reached-alert .alert-icon {
            font-size: 2rem;
            margin-bottom: 10px;
            color: #f44336;
        }

        .limit-reached-alert h4 {
            margin-bottom: 10px;
            font-weight: 700;
        }

        /* Responsive para dispositivos móviles */
        @media (max-width: 768px) {
            .limits-grid {
                grid-template-columns: 1fr;
                gap: 15px;
            }
            
            .action-buttons {
                flex-direction: column;
                gap: 6px;
            }
            
            .btn {
                font-size: 12px;
                padding: 8px 12px;
                width: 100%;
                justify-content: center;
            }
            
            .info-message {
                font-size: 11px;
                padding: 10px;
            }
            
            .time-slot.own-reservation::before {
                top: -8px;
                right: 8px;
                font-size: 10px;
                padding: 3px 8px;
            }

            .reservation-limits-panel {
                padding: 15px;
            }

            .limits-info-text {
                padding: 10px;
                font-size: 11px;
            }
        }



/* ESTILOS MEJORADOS PARA TÍTULOS - MÁS GRANDES Y COLORIDOS */
.compact-title {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    padding: 15px 10px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 15px;
    border: 2px solid #e3f2fd;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.title-line {
    display: flex;
    align-items: center;
    gap: 12px;
    text-align: center;
}

.title-main {
    font-size: 1.4rem; /* Aumentado de 1.1rem */
    font-weight: 800; /* Más grueso */
    text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
    letter-spacing: 0.5px;
}

.title-sub {
    font-size: 1.1rem; /* Aumentado de 0.9rem */
    font-weight: 600; /* Más grueso */
    opacity: 0.9;
}

.title-main i {
    font-size: 1.6rem; /* Iconos más grandes */
    filter: drop-shadow(1px 1px 2px rgba(0,0,0,0.2));
    animation: gentlePulse 3s infinite ease-in-out;
}

@keyframes gentlePulse {
    0%, 100% { transform: scale(1); }
    50% { transform: scale(1.05); }
}

/* Colores específicos para cada estado */
.title-today .title-main { color: #ff6b00; }
.title-today .title-sub { color: #28a745; }
.title-today .title-main i { color: #ffc107; }

.title-tomorrow .title-main { color: #17a2b8; }
.title-tomorrow .title-sub { color: #28a745; }
.title-tomorrow .title-main i { color: #6f42c1; }

.title-weekend .title-main { color: #dc3545; }
.title-weekend .title-sub { color: #e83e8c; }
.title-weekend .title-main i { color: #dc3545; }

.title-future .title-main { color: #2c3e50; }
.title-future .title-sub { color: #6c757d; }
.title-future .title-main i { color: #667eea; }

/* Efectos hover para interactividad */
.compact-title:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0,0,0,0.15);
    transition: all 0.3s ease;
}

/* Responsive para móviles */
@media (max-width: 768px) {
    .compact-title {
        gap: 6px;
        padding: 12px 8px;
        border-radius: 12px;
    }
    
    .title-main {
        font-size: 1.3rem;
    }
    
    .title-sub {
        font-size: 1rem;
    }
    
    .title-main i {
        font-size: 1.5rem;
    }
    
    .title-line {
        gap: 10px;
    }
}

@media (max-width: 480px) {
    .compact-title {
        gap: 4px;
        padding: 10px 6px;
    }
    
    .title-main {
        font-size: 1.2rem;
    }
    
    .title-sub {
        font-size: 0.95rem;
    }
    
    .title-main i {
        font-size: 1.4rem;
    }
    
    .title-line {
        gap: 8px;
    }
}

/* Animación de entrada suave */
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.compact-title {
    animation: fadeInUp 0.5s ease-out;
}

        /* =========================================
           GESTIÓN DE HORARIOS POR DÍA (ADMIN)
           ========================================= */

        .schedule-config-panel {
            background: linear-gradient(135deg, #f8f9fa 0%, #eef2ff 100%);
            border: 2px solid #667eea;
            border-radius: 15px;
            padding: 28px;
        }

        .schedule-config-panel h4 {
            color: #4338ca;
            font-size: 1.15rem;
            font-weight: 700;
            margin-bottom: 6px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .schedule-config-panel p.subtitle {
            color: #6b7280;
            font-size: 0.88rem;
            margin-bottom: 22px;
            line-height: 1.5;
        }

        /* Tabla de horarios */
        .schedule-table-wrapper {
            overflow-x: auto;
            border-radius: 12px;
            box-shadow: 0 4px 14px rgba(102, 126, 234, 0.13);
        }

        .schedule-config-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            font-size: 0.88rem;
            min-width: 600px;
        }

        .schedule-config-table thead th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 13px 16px;
            text-align: center;
            font-weight: 600;
            letter-spacing: 0.3px;
            font-size: 0.85rem;
        }

        .schedule-config-table thead th:first-child {
            text-align: left;
            border-radius: 12px 0 0 0;
            min-width: 160px;
        }

        .schedule-config-table thead th:last-child {
            border-radius: 0 12px 0 0;
        }

        .schedule-config-table tbody tr {
            border-bottom: 1px solid #e5e7eb;
            transition: background 0.15s ease;
        }

        .schedule-config-table tbody tr:last-child {
            border-bottom: none;
        }

        .schedule-config-table tbody tr:hover {
            background: #f5f3ff;
        }

        .schedule-config-table tbody td {
            padding: 12px 16px;
            text-align: center;
            vertical-align: middle;
        }

        .schedule-config-table tbody td:first-child {
            text-align: left;
            font-weight: 600;
            color: #374151;
            white-space: nowrap;
        }

        /* Toggle switch */
        .toggle-day-btn {
            position: relative;
            display: inline-flex;
            width: 50px;
            height: 26px;
            cursor: pointer;
        }

        .toggle-day-btn input {
            opacity: 0;
            width: 0;
            height: 0;
            position: absolute;
        }

        .toggle-slider {
            position: absolute;
            inset: 0;
            background: #d1d5db;
            border-radius: 26px;
            transition: background 0.25s ease;
        }

        .toggle-slider::before {
            content: '';
            position: absolute;
            width: 20px;
            height: 20px;
            left: 3px;
            top: 3px;
            background: white;
            border-radius: 50%;
            transition: transform 0.25s ease;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
        }

        .toggle-day-btn input:checked + .toggle-slider {
            background: #22c55e;
        }

        .toggle-day-btn input:checked + .toggle-slider::before {
            transform: translateX(24px);
        }

        .toggle-day-btn input:disabled + .toggle-slider {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* Celda de estado del slot */
        .slot-status-cell {
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            gap: 4px;
        }

        .slot-update-info {
            font-size: 0.72rem;
            color: #9ca3af;
            max-width: 90px;
            text-align: center;
            line-height: 1.2;
        }

        /* Barra de guardado */
        .schedule-save-bar {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 20px;
            padding: 14px 18px;
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 12px;
            gap: 16px;
            flex-wrap: wrap;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        }

        .schedule-save-bar .changes-badge {
            background: #fef3c7;
            color: #92400e;
            border: 1px solid #fcd34d;
            border-radius: 20px;
            padding: 5px 14px;
            font-size: 0.83rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 7px;
        }

        .schedule-save-bar .changes-badge.no-changes {
            background: #f0fdf4;
            color: #166534;
            border-color: #86efac;
        }

        /* Botones del panel de horarios */
        .btn-save-schedule {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            color: white;
            border: none;
            padding: 10px 22px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.9rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s ease;
            font-family: 'Inter', sans-serif;
        }

        .btn-save-schedule:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(34, 197, 94, 0.35);
        }

        .btn-save-schedule:disabled {
            opacity: 0.55;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .btn-reload-schedule {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 10px 18px;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.9rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s ease;
            font-family: 'Inter', sans-serif;
        }

        .btn-reload-schedule:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(102, 126, 234, 0.35);
        }

        /* Leyenda de colores del panel */
        .schedule-legend {
            display: flex;
            align-items: center;
            gap: 20px;
            flex-wrap: wrap;
            margin-bottom: 16px;
            padding: 10px 14px;
            background: white;
            border-radius: 8px;
            border: 1px solid #e5e7eb;
            font-size: 0.82rem;
            color: #6b7280;
        }

        .schedule-legend-item {
            display: flex;
            align-items: center;
            gap: 6px;
            font-weight: 600;
        }

        .legend-dot {
            width: 12px;
            height: 12px;
            border-radius: 50%;
        }

        .legend-dot.active   { background: #22c55e; }
        .legend-dot.inactive { background: #d1d5db; }

        /* Responsive para tabla de horarios */
        /* Acciones por fila */
        .slot-name-cell {
            display: flex;
            align-items: center;
            gap: 7px;
        }

        .slot-icon {
            color: #667eea;
            flex-shrink: 0;
        }

        .slot-time-text {
            font-weight: 600;
            color: #1f2937;
        }

        .slot-day-count {
            font-size: 0.74rem;
            color: #9ca3af;
            margin-left: 2px;
        }

        .slot-action-btns {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }

        .slot-btn {
            width: 32px;
            height: 32px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 0.8rem;
            transition: all 0.18s ease;
        }

        .slot-btn-edit {
            background: rgba(102, 126, 234, 0.12);
            color: #667eea;
        }

        .slot-btn-edit:hover {
            background: #667eea;
            color: white;
            transform: scale(1.1);
            box-shadow: 0 3px 10px rgba(102, 126, 234, 0.4);
        }

        .slot-btn-delete {
            background: rgba(239, 68, 68, 0.1);
            color: #ef4444;
        }

        .slot-btn-delete:hover {
            background: #ef4444;
            color: white;
            transform: scale(1.1);
            box-shadow: 0 3px 10px rgba(239, 68, 68, 0.35);
        }

        /* Encabezado del panel con botón añadir */
        .schedule-panel-header {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            gap: 16px;
            margin-bottom: 8px;
            flex-wrap: wrap;
        }

        .btn-add-slot {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 10px;
            font-weight: 700;
            font-size: 0.88rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s ease;
            white-space: nowrap;
            flex-shrink: 0;
            font-family: 'Inter', sans-serif;
        }

        .btn-add-slot:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 18px rgba(34, 197, 94, 0.4);
        }

        /* ---- MODALES DE HORARIO ---- */
        .slot-modal-overlay {
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(4px);
            z-index: 11000;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            visibility: hidden;
            transition: all 0.25s ease;
        }

        .slot-modal-overlay.show {
            opacity: 1;
            visibility: visible;
        }

        .slot-modal {
            background: white;
            border-radius: 18px;
            width: 90%;
            max-width: 460px;
            box-shadow: 0 25px 60px rgba(0, 0, 0, 0.25);
            transform: scale(0.9) translateY(-20px);
            transition: transform 0.25s cubic-bezier(0.34, 1.56, 0.64, 1);
            overflow: hidden;
        }

        .slot-modal-overlay.show .slot-modal {
            transform: scale(1) translateY(0);
        }

        .slot-modal-sm {
            max-width: 380px;
        }

        .slot-modal-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 20px 24px 16px;
            border-bottom: 2px solid #f3f4f6;
        }

        .slot-modal-header h3 {
            font-size: 1.1rem;
            font-weight: 700;
            color: #1f2937;
            display: flex;
            align-items: center;
            gap: 10px;
            margin: 0;
        }

        .slot-modal-header h3 i {
            color: #667eea;
        }

        .slot-modal-header-danger h3 i {
            color: #ef4444;
        }

        .slot-modal-close {
            background: #f3f4f6;
            border: none;
            width: 32px;
            height: 32px;
            border-radius: 8px;
            cursor: pointer;
            color: #6b7280;
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.15s;
        }

        .slot-modal-close:hover {
            background: #e5e7eb;
            color: #374151;
        }

        .slot-modal-body {
            padding: 20px 24px;
        }

        .slot-modal-field {
            margin-bottom: 18px;
        }

        .slot-modal-field label {
            display: block;
            font-weight: 600;
            color: #374151;
            margin-bottom: 8px;
            font-size: 0.9rem;
        }

        .slot-modal-field input[type="text"] {
            width: 100%;
            padding: 12px 14px;
            border: 2px solid #e5e7eb;
            border-radius: 10px;
            font-size: 1rem;
            font-family: 'Inter', sans-serif;
            transition: all 0.2s;
            color: #1f2937;
        }

        .slot-modal-field input[type="text"]:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15);
        }

        .slot-input-error {
            margin-top: 6px;
            font-size: 0.82rem;
            color: #ef4444;
            display: flex;
            align-items: center;
            gap: 5px;
            font-weight: 600;
        }

        .slot-input-hint {
            margin-top: 6px;
            font-size: 0.81rem;
            color: #6b7280;
        }

        /* Time pickers side by side */
        .slot-time-pickers {
            display: flex;
            align-items: flex-end;
            gap: 12px;
            margin-bottom: 4px;
        }

        .slot-time-picker-group {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 7px;
        }

        .slot-time-picker-group label {
            font-size: 0.83rem;
            font-weight: 600;
            color: #374151;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .slot-time-picker-group label i {
            color: #667eea;
            font-size: 0.8rem;
        }

        .slot-time-picker-group input[type="time"] {
            width: 100%;
            padding: 11px 13px;
            border: 2px solid #e5e7eb;
            border-radius: 10px;
            font-size: 1.05rem;
            font-family: 'Inter', sans-serif;
            color: #1f2937;
            font-weight: 600;
            transition: all 0.2s;
            cursor: pointer;
            background: #fafafa;
        }

        .slot-time-picker-group input[type="time"]:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15);
            background: white;
        }

        .slot-time-picker-group input[type="time"]::-webkit-calendar-picker-indicator {
            cursor: pointer;
            color: #667eea;
            opacity: 0.8;
            font-size: 1rem;
        }

        .slot-time-picker-arrow {
            color: #9ca3af;
            font-size: 0.9rem;
            padding-bottom: 13px;
            flex-shrink: 0;
        }

        /* Preview badge */
        .slot-time-preview {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-top: 10px;
            padding: 9px 14px;
            background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
            border: 1.5px solid #86efac;
            border-radius: 9px;
            font-size: 0.88rem;
            color: #166534;
        }

        .slot-time-preview i {
            color: #22c55e;
        }

        /* Días del nuevo horario */
        .slot-days-grid {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .slot-day-check {
            display: flex;
            align-items: center;
            gap: 6px;
            cursor: pointer;
            padding: 6px 12px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            transition: all 0.15s;
            user-select: none;
        }

        .slot-day-check:has(input:checked) {
            border-color: #22c55e;
            background: #f0fdf4;
        }

        .slot-day-check input {
            accent-color: #22c55e;
            width: 15px;
            height: 15px;
        }

        .slot-day-label {
            font-size: 0.83rem;
            font-weight: 600;
            color: #374151;
        }

        .slot-modal-footer {
            padding: 14px 24px 20px;
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            border-top: 1px solid #f3f4f6;
        }

        .slot-modal-btn {
            padding: 10px 20px;
            border: none;
            border-radius: 9px;
            font-weight: 600;
            font-size: 0.88rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 7px;
            transition: all 0.2s;
            font-family: 'Inter', sans-serif;
        }

        .slot-modal-btn-cancel {
            background: #f3f4f6;
            color: #6b7280;
        }

        .slot-modal-btn-cancel:hover {
            background: #e5e7eb;
            color: #374151;
        }

        .slot-modal-btn-save {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .slot-modal-btn-save:hover:not(:disabled) {
            transform: translateY(-1px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .slot-modal-btn-save:disabled {
            opacity: 0.55;
            cursor: not-allowed;
        }

        .slot-modal-btn-danger {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
        }

        .slot-modal-btn-danger:hover:not(:disabled) {
            transform: translateY(-1px);
            box-shadow: 0 5px 15px rgba(239, 68, 68, 0.4);
        }

        .slot-modal-btn-danger:disabled {
            opacity: 0.55;
            cursor: not-allowed;
        }

        /* Confirm delete modal */
        .delete-slot-name {
            background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
            border: 2px solid #fca5a5;
            border-radius: 10px;
            padding: 12px 16px;
            font-size: 1.05rem;
            font-weight: 700;
            color: #991b1b;
            text-align: center;
            margin-bottom: 14px;
        }

        .delete-warning {
            background: #fffbeb;
            border: 1px solid #fcd34d;
            border-radius: 8px;
            padding: 10px 14px;
            font-size: 0.83rem;
            color: #92400e;
            display: flex;
            align-items: flex-start;
            gap: 8px;
            line-height: 1.5;
        }

        .delete-warning i {
            flex-shrink: 0;
            margin-top: 2px;
            color: #f59e0b;
        }
    </style>
    
</head>
<body>
    <div class="container">
        <!-- TOAST CONTAINER -->
        <div id="toastContainer" class="toast-container"></div>
        
        <!-- MODAL PARA EDITAR USUARIO -->
        <div id="editUserModal" class="modal-overlay">
            <div class="modal">
                <div class="modal-header">
                    <h3 class="modal-title">Editar Usuario</h3>
                    <button class="modal-close" onclick="closeEditUserModal()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="editUsername">Usuario:</label>
                        <input type="text" id="editUsername" readonly style="background: #f8f9fa;">
                    </div>
                    <div class="form-group">
                        <label for="editUserFullName">Nombre Completo:</label>
                        <input type="text" id="editUserFullName" placeholder="Nombre completo del usuario">
                    </div>
                    <div class="form-group">
                        <label for="editUserRole">Rol:</label>
                        <select id="editUserRole">
                            <option value="user">Usuario</option>
                            <option value="admin">Administrador</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="editUserPassword">Nueva Contraseña (opcional):</label>
                        <input type="password" id="editUserPassword" placeholder="Dejar vacío para mantener la actual">
                    </div>
                    <div style="text-align: center; margin-top: 20px;">
                        <button class="btn btn-success" onclick="updateUser()">
                            <i class="fas fa-save"></i> Guardar Cambios
                        </button>
                        <button class="btn" onclick="closeEditUserModal()" style="margin-left: 10px;">
                            <i class="fas fa-times"></i> Cancelar
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- MODAL PARA CAMBIO DE CONTRASEÑA -->
        <div id="changePasswordModal" class="modal-overlay">
            <div class="modal">
                <div class="modal-header">
                    <h3 class="modal-title">
                        <i class="fas fa-key" style="color: #667eea;"></i> 
                        Cambiar Contraseña
                    </h3>
                    <button class="modal-close" onclick="closeChangePasswordModal()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="currentPassword">Contraseña Actual:</label>
                        <div class="password-input-group">
                            <input type="password" id="currentPassword" placeholder="Ingrese su contraseña actual" autocomplete="current-password">
                            <button type="button" class="toggle-password" onclick="togglePasswordVisibility('currentPassword')">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="newPassword">Nueva Contraseña:</label>
                        <div class="password-input-group">
                            <input type="password" id="newPassword" placeholder="Ingrese su nueva contraseña" autocomplete="new-password" oninput="checkPasswordStrength()">
                            <button type="button" class="toggle-password" onclick="togglePasswordVisibility('newPassword')">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                        
                        <!-- Indicador de fortaleza de contraseña -->
                        <div class="password-strength-indicator">
                            <div class="password-strength-fill" id="passwordStrengthFill"></div>
                        </div>
                        
                        <!-- Requisitos de contraseña -->
                        <div class="password-requirements">
                            <div class="password-requirement" id="req-length">
                                <i class="fas fa-times-circle"></i>
                                <span>Al menos 4 caracteres</span>
                            </div>
                            <div class="password-requirement" id="req-letters">
                                <i class="fas fa-times-circle"></i>
                                <span>Contiene letras</span>
                            </div>
                            <div class="password-requirement" id="req-numbers">
                                <i class="fas fa-times-circle"></i>
                                <span>Contiene números (recomendado)</span>
                            </div>
                            <div class="password-requirement" id="req-special">
                                <i class="fas fa-times-circle"></i>
                                <span>Contiene símbolos especiales (recomendado)</span>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="confirmPassword">Confirmar Nueva Contraseña:</label>
                        <div class="password-input-group">
                            <input type="password" id="confirmPassword" placeholder="Confirme su nueva contraseña" autocomplete="new-password" oninput="checkPasswordMatch()">
                            <button type="button" class="toggle-password" onclick="togglePasswordVisibility('confirmPassword')">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                        <div id="passwordMatchIndicator" style="margin-top: 8px; font-size: 12px;"></div>
                    </div>

                    <div style="text-align: center; margin-top: 25px;">
                        <button class="btn btn-success" id="changePasswordBtn" onclick="changePassword()" disabled>
                            <i class="fas fa-key"></i> Cambiar Contraseña
                        </button>
                        <button class="btn" onclick="closeChangePasswordModal()" style="margin-left: 10px;">
                            <i class="fas fa-times"></i> Cancelar
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- HEADER -->
        <div class="header">
            <h1>💻 Sala de Enlaces y Tablets 📱</h1>
            <img src="../img/ElCobre.png" alt="Logo de la Plataforma Didáctica" class="mx-auto w-32 h-32 md:w-30 md:h-30 rounded-full shadow-md object-cover border-4 border-blue-200">
        </div>

        <!-- LOGIN SECTION -->
        <div id="loginSection" class="login-section">
            <h3>Inicia Sesión</h3>
            
            <div id="loginAlerts"></div>
            
            <div class="form-group">
                <label for="username">Usuario:</label>
                <input type="text" id="username" placeholder="Ingrese su usuario" autocomplete="username">
            </div>
            
            <div class="form-group">
                <label for="password">Contraseña:</label>
                <input type="password" id="password" placeholder="Ingrese su contraseña" autocomplete="current-password">
            </div>
            
            <button class="btn" onclick="login()" id="loginBtn">
                <i class="fas fa-sign-in-alt"></i> Ingresar
            </button>
        </div>

        <!-- MAIN SECTION -->
        <div id="mainSection" class="main-section">
            <!-- USER INFO -->
            <div class="user-info">
                <div>
                    <strong>Bienvenido: <span id="currentUser"></span></strong>
                    <span id="userRole" class="status-badge"></span>
                    <span id="superAdminBadge" class="super-admin-badge" style="display: none;">
                        <i class="fas fa-crown"></i> SÚPER ADMIN
                    </span>
                </div>
                <div>
                    <!-- NUEVO: Botón para cambiar contraseña -->
                    <button class="btn btn-info" onclick="openChangePasswordModal()" style="margin-right: 10px;">
                        <i class="fas fa-key"></i> Cambiar Contraseña
                    </button>
                    <button class="btn btn-danger" onclick="logout()">
                        <i class="fas fa-sign-out-alt"></i> Cerrar Sesión
                    </button>
                </div>
            </div>

            <div id="alerts"></div>

            <!-- ADMIN PANEL -->
            <div id="adminPanel" class="admin-panel hidden">
                <h3 style="color: #2c3e50; margin-bottom: 20px;">
                    <i class="fas fa-cog"></i> Panel de Administración
                </h3>
                
                <!-- PESTAÑAS DE ADMIN -->
                <div class="admin-tabs">
                    <button class="admin-tab-btn active" onclick="switchAdminTab('reports')">
                        <i class="fas fa-chart-bar" color="red"></i> Reportes
                    </button>
                    <button class="admin-tab-btn" id="usersTabBtn" onclick="switchAdminTab('users')">
                        <i class="fas fa-users"></i> Gestión de Usuarios
                    </button>
                    <button class="admin-tab-btn" onclick="switchAdminTab('registry')">
                        <i class="fas fa-list-alt"></i> Registro de Reservas
                    </button>
                    <button class="admin-tab-btn" id="scheduleTabBtn" onclick="switchAdminTab('schedule')">
                        <i class="fas fa-calendar-alt"></i> Gestión de Horarios
                    </button>
                </div>

                <!-- PESTAÑA DE REPORTES -->
                <div id="adminTabReports" class="admin-tab-content active">
                    <div style="text-align: center; margin-bottom: 20px;">
                        <button class="btn btn-info" onclick="generateReport()">
                            <i class="fas fa-download "></i> Generar Reporte PDF
                        </button>
                    </div>
                    <div class="form-group">
                        <label for="reportMonth">Mes del reporte:</label>
                        <div class="date-input-wrapper">
                            <input type="month" id="reportMonth">
                        </div>
                    </div>
                </div>

                <!-- PESTAÑA DE GESTIÓN DE USUARIOS -->
                <div id="adminTabUsers" class="admin-tab-content">
                    <!-- CONTENIDO DINÁMICO: Se llenará según el usuario -->
                    <div id="userManagementContent">
                        <!-- Aquí se insertará el contenido apropiado -->
                    </div>
                </div>
                                <!-- PESTAÑA DE REGISTRO DE RESERVAS -->
                <div id="adminTabRegistry" class="admin-tab-content">
                    <div style="text-align: center; margin-bottom: 20px;">
                        <h4 style="color: #2c3e50; margin-bottom: 15px;">
                            <i class="fas fa-list-alt"></i> Registro Completo de Reservas
                        </h4>
                        <p style="color: #666; margin-bottom: 20px;">
                            Accede al sistema completo de registro y seguimiento de todas las reservas.
                        </p>
                        <button class="btn btn-primary" onclick="openRegistroReservas()">
                            <i class="fas fa-external-link-alt"></i> Abrir Registro de Reservas
                        </button>
                    </div>
                </div>

                <!-- PESTAÑA DE GESTIÓN DE HORARIOS -->
                <div id="adminTabSchedule" class="admin-tab-content">
                    <div id="scheduleConfigContainer">
                        <div style="text-align:center; padding: 30px;">
                            <i class="fas fa-spinner fa-spin" style="font-size:2rem; color:#667eea;"></i>
                            <p style="color:#666; margin-top:10px;">Cargando configuración de horarios...</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- PANEL DE LÍMITES DE RESERVAS -->
            <div id="reservationLimitsPanel" class="reservation-limits-panel" style="display: none;">
                <div class="limits-header">
                    <i class="fas fa-chart-pie"></i>
                    Límites de Reservas Mensuales
                </div>
                <div id="limitsContent">
                    <!-- Contenido dinámico -->
                </div>
            </div>

            <!-- RESERVATION FORM -->
            <div class="reservation-form">
                <h3 style="color: #2c3e50; margin-bottom: 20px; text-align: center;">
                    <i class="fas fa-calendar-plus"></i> Agendar Reserva
                </h3>
                
                <!-- RESOURCE SELECTOR -->
                <div class="resource-selector">
                    <button class="resource-btn active" id="btnSalaEnlaces" onclick="selectResource('sala_enlaces')">
                        🖥️ Sala de Enlaces
                    </button>
                    <button class="resource-btn" id="btnTablets" onclick="selectResource('tablets')">
                        📱 Tablets
                    </button>
                </div>

                <!-- SELECTED TIME INDICATOR -->
                <div id="selectedTimeIndicator" class="selected-time-indicator empty">
                    <i class="fas fa-clock"></i> Selecciona hasta 2 horarios haciendo clic en los disponibles abajo
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="course">Curso:</label>
                        <select id="course">
                            <option value="">Seleccione un curso</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="subject">Asignatura:</label>
                        <input type="text" id="subject" placeholder="Ej: Matemáticas, Lenguaje, Historia, etc.">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="date">Fecha (solo días laborables):</label>
                        <div class="date-input-wrapper">
                            <input type="date" id="date">
                        </div>
                        <small style="color: #666; font-size: 12px; margin-top: 5px; display: block;">
                            <i class="fas fa-info-circle"></i> Solo se pueden agendar reservas de lunes a viernes
                        </small>
                    </div>
                    <div class="form-group">
                        <label>Docente:</label>
                        <div style="background: #f8f9fa; padding: 15px; border-radius: 10px; border: 2px solid #e1e8ed; color: #2c3e50; font-weight: 600; font-size: 16px;">
                            <i class="fas fa-user" style="color: #667eea; margin-right: 8px;"></i> 
                            <span id="currentTeacherName">Cargando...</span>
                        </div>
                    </div>
                </div>
                
                <div style="text-align: center;">
                    <button type="button" class="btn btn-success" onclick="makeReservation()" id="reserveBtn">
                        <i class="fas fa-check"></i> Confirmar Reserva
                    </button>
                </div>
            </div>

            <!-- SCHEDULE SECTION -->
            <div class="schedule-section">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h3 id="scheduleTitle">
                        <i class="fas fa-calendar-day"></i> Horarios de Hoy - Haz clic para seleccionar
                    </h3>
                    <button class="btn btn-info" onclick="reloadScheduleData()" title="Recargar horarios" style="padding: 10px 15px;">
                        <i class="fas fa-refresh"></i> Recargar
                    </button>
                </div>
                
                <div class="resource-selector">
                    <button class="resource-btn active" id="btnSalaEnlaces2" onclick="selectResource('sala_enlaces')">
                        🖥️ Sala de Enlaces
                    </button>
                    <button class="resource-btn" id="btnTablets2" onclick="selectResource('tablets')">
                        📱 Tablets
                    </button>
                </div>
                
                <div id="scheduleGrid" class="schedule-grid">
                    <div class="loading">
                        <i class="fas fa-spinner fa-spin"></i> Cargando horarios...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // ===== CONFIGURACIÓN =====
        const API_URL = './api2.php';
        let currentUser = null;
        let currentResource = 'sala_enlaces';
        let selectedTimeSlots = [];
        let courses = [];
        let timeSlots = [];
        let reservations = [];
        let logoBase64 = null;

        // NUEVAS VARIABLES PARA LÍMITES
        let userLimits = null;
        let limitsLoaded = false;
        // VARIABLES PARA BÚSQUEDA DE USUARIOS (ya están definidas pero las mantengo para referencia)
        //let allUsers = [];
       // let filteredUsers = [];
        //let currentSearchTerm = '';
        //let currentRoleFilter = 'all';

        // ===== CONSTANTE PARA SÚPER ADMINISTRADOR =====
        const SUPER_ADMIN_USERNAME = 'Claudio Salvatierra 🤪';
        const SUPER_ADMIN_ALTERNATIVES = ['claudio', 'Claudio', 'CLAUDIO'];

        // ===== VARIABLES PARA BÚSQUEDA DE USUARIOS =====
        let allUsers = [];
        let filteredUsers = [];
        let currentSearchTerm = '';
        let currentRoleFilter = 'all';

        // ===== FUNCIÓN MEJORADA PARA VERIFICAR SI ES SÚPER ADMIN =====
        function isSuperAdmin() {
            if (!currentUser) {
                console.log('🔍 isSuperAdmin: No hay usuario logueado');
                return false;
            }
            
            const isAdmin = currentUser.role === 'admin';
            const usernameMatch = SUPER_ADMIN_ALTERNATIVES.includes(currentUser.username) || 
                                  currentUser.username === SUPER_ADMIN_USERNAME ||
                                  currentUser.name === SUPER_ADMIN_USERNAME ||
                                  SUPER_ADMIN_ALTERNATIVES.includes(currentUser.name);
            
            console.log('🔍 Verificación de Súper Admin:', {
                username: currentUser.username,
                name: currentUser.name,
                role: currentUser.role,
                isAdmin: isAdmin,
                usernameMatch: usernameMatch,
                result: isAdmin && usernameMatch
            });
            
            return isAdmin && usernameMatch;
        }

        // ===== NUEVA FUNCIÓN PARA VERIFICAR SI ES SÚPER ADMINISTRADOR (SOLO CLAUDIO) =====
        function isSuperAdminClaudio() {
            if (!currentUser) {
                return false;
            }
            
            const usernameMatch = SUPER_ADMIN_ALTERNATIVES.includes(currentUser.username) || 
                                  currentUser.username === SUPER_ADMIN_USERNAME ||
                                  currentUser.name === SUPER_ADMIN_USERNAME ||
                                  SUPER_ADMIN_ALTERNATIVES.includes(currentUser.name);
            
            console.log('👑 Verificación de Súper Admin Claudio:', {
                username: currentUser.username,
                name: currentUser.name,
                usernameMatch: usernameMatch,
                result: usernameMatch
            });
            
            return usernameMatch;
        }

        // ===== FUNCIÓN PARA VERIFICAR ACCESO A GESTIÓN DE USUARIOS =====
        function hasUserManagementAccess() {
            const access = isSuperAdmin();
            console.log('🔍 Acceso a gestión de usuarios:', access);
            return access;
        }

        // ===== FUNCIÓN PARA MOSTRAR/OCULTAR ELEMENTOS SEGÚN PERMISOS =====
        function setupAdminInterface() {
            const usersTabBtn = document.getElementById('usersTabBtn');
            const superAdminBadge = document.getElementById('superAdminBadge');
            
            const scheduleTabBtn = document.getElementById('scheduleTabBtn');

            if (isSuperAdmin()) {
                usersTabBtn.classList.remove('restricted');
                usersTabBtn.onclick = () => switchAdminTab('users');
                superAdminBadge.style.display = 'inline-block';

                scheduleTabBtn.classList.remove('restricted');
                scheduleTabBtn.onclick = () => switchAdminTab('schedule');

                console.log('🔓 Acceso completo concedido a súper administrador:', currentUser.username);

            } else if (currentUser && currentUser.role === 'admin') {
                usersTabBtn.classList.add('restricted');
                usersTabBtn.onclick = showAccessDenied;
                superAdminBadge.style.display = 'none';

                scheduleTabBtn.classList.add('restricted');
                scheduleTabBtn.onclick = showScheduleAccessDenied;

                console.log('🔒 Acceso restringido para administrador:', currentUser.username);

            } else {
                superAdminBadge.style.display = 'none';
            }
        }

        // ===== FUNCIÓN PARA MOSTRAR MENSAJE DE ACCESO DENEGADO =====
        function showAccessDenied() {
            showToast(
                `💀 Acceso Denegado: Solo "${SUPER_ADMIN_USERNAME}" puede gestionar usuarios por razones de seguridad.`, 
                'warning', 
                
            );
            
            console.warn('🚫 Intento de acceso denegado a gestión de usuarios:', currentUser.username);
        }

        function showScheduleAccessDenied() {
            showToast(
                `🔒 Acceso Denegado: Solo "${SUPER_ADMIN_USERNAME}" puede gestionar los horarios del sistema.`,
                'warning'
            );
            console.warn('🚫 Intento de acceso denegado a gestión de horarios:', currentUser.username);
        }

        // ===== NUEVAS FUNCIONES PARA LÍMITES DE RESERVAS =====

        /**
         * Función para cargar y mostrar los límites del usuario
         */
        async function loadUserLimits() {
            if (!currentUser || !currentUser.name) {
                console.log('🔍 No se puede cargar límites: usuario no válido');
                return;
            }

            try {
                const dateInput = document.getElementById('date');
                const selectedDate = dateInput.value || new Date().toISOString().split('T')[0];

                console.log('📊 Cargando límites para:', currentUser.name, 'fecha:', selectedDate, 'rol:', currentUser.role);

                const response = await apiRequest('get_user_limits', 'GET', {
                    user_name: currentUser.name,
                    date: selectedDate,
                    user_role: currentUser.role
                });

                userLimits = response.data;
                limitsLoaded = true;

                console.log('📊 Límites cargados:', userLimits);
                
                // Debug adicional para verificar límites
                if (userLimits && userLimits.limits) {
                    console.log('🔍 Enlaces - puede reservar:', userLimits.limits.sala_enlaces.can_reserve, 
                               'actual:', userLimits.limits.sala_enlaces.current_count,
                               'máximo:', userLimits.limits.sala_enlaces.max_allowed);
                    console.log('🔍 Tablets - puede reservar:', userLimits.limits.tablets.can_reserve,
                               'actual:', userLimits.limits.tablets.current_count, 
                               'máximo:', userLimits.limits.tablets.max_allowed);
                }
                
                updateLimitsDisplay();
                updateReserveButtonWithLimits();

            } catch (error) {
                console.error('❌ Error al cargar límites del usuario:', error);
                showToast('Error al cargar límites de reservas: ' + error.message, 'error');
            }
        }

        /**
         * Función para actualizar la visualización de límites
         */
        function updateLimitsDisplay() {
            if (!userLimits || !currentUser) {
                hideUserLimitsPanel();
                return;
            }

            const limitsPanel = document.getElementById('reservationLimitsPanel');
            const limitsContent = document.getElementById('limitsContent');

            // Verificar si es súper administrador usando la respuesta del backend
            if (userLimits.is_super_admin === true) {
                // Para el súper administrador Claudio, mostrar un mensaje especial
                limitsContent.innerHTML = `
                    <div class="admin-unlimited-badge">
                        <i class="fas fa-crown"></i>
                        Sin límites - Súper Administrador Claudio
                        <i class="fas fa-infinity"></i>
                    </div>
                `;
                limitsPanel.style.display = 'block';
                console.log('👑 Mostrando panel de súper admin para:', currentUser.name);
                return;
            }

            // Para todos los demás (usuarios normales y administradores normales), mostrar límites
            const enlaces = userLimits.limits.sala_enlaces;
            const tablets = userLimits.limits.tablets;

            const roleText = currentUser.role === 'admin' ? ' (Administrador con límites)' : '';

            console.log('📊 Mostrando límites normales para:', currentUser.name, roleText);
            console.log('📊 Enlaces:', enlaces.current_count + '/' + enlaces.max_allowed);
            console.log('📊 Tablets:', tablets.current_count + '/' + tablets.max_allowed);

            limitsContent.innerHTML = `
                <div class="limits-grid">
                    ${generateLimitCard('sala_enlaces', enlaces, '🖥️', 'Enlaces')}
                    ${generateLimitCard('tablets', tablets, '📱', 'Tablets')}
                </div>
                <div class="limits-info-text">
                    <i class="fas fa-info-circle"></i>
                    <strong>Información${roleText}:</strong> Cada mes puedes hacer máximo 4 reservas por recurso. 
                    Los cupos se liberan cuando un administrador confirma o cancela tus reservas.
                    <br><br>
                    <strong>Resumen del mes:</strong> 
                    ${userLimits.monthly_summary.total_pending} pendientes, 
                    ${userLimits.monthly_summary.total_confirmed} confirmadas, 
                    ${userLimits.monthly_summary.total_cancelled} canceladas.
                    <br><br>
                    <small style="color: #666;">
                        ℹ️ Solo el súper administrador Claudio tiene acceso ilimitado.
                    </small>
                </div>
            `;

            limitsPanel.style.display = 'block';
        }

        /**
         * Función para generar tarjeta de límite individual
         */
        function generateLimitCard(resourceType, limitData, icon, title) {
            const isWarning = limitData.remaining <= 1;
            const isDanger = limitData.remaining === 0;
            
            let cardClass = resourceType;
            let badgeClass = 'available';
            let badgeText = 'Disponible';
            
            if (isDanger) {
                cardClass += ' warning';
                badgeClass = 'danger';
                badgeText = 'Límite Alcanzado';
            } else if (isWarning) {
                badgeClass = 'warning';
                badgeText = 'Último Cupo';
            }

            const progressPercentage = (limitData.current_count / limitData.max_allowed) * 100;

            return `
                <div class="limit-card ${cardClass}">
                    <div class="limit-header">
                        <div class="limit-title">
                            <i class="limit-icon ${resourceType}">${icon}</i>
                            ${title}
                        </div>
                        <div class="limit-badge ${badgeClass}">
                            ${badgeText}
                        </div>
                    </div>
                    <div class="limit-progress">
                        <div class="limit-progress-bar">
                            <div class="limit-progress-fill ${isDanger ? 'warning' : resourceType}" 
                                 style="width: ${progressPercentage}%"></div>
                        </div>
                        <div class="limit-text">
                            <span>Usadas: ${limitData.current_count}/${limitData.max_allowed}</span>
                            <span class="limit-remaining">Restantes: ${limitData.remaining}</span>
                        </div>
                    </div>
                    <div class="limit-details">
                        <span>Estado: ${limitData.current_count === 0 ? 'Sin reservas' : 
                                      limitData.remaining === 0 ? 'Límite alcanzado' : 
                                      limitData.remaining === 1 ? 'Último cupo' : 'Disponible'}</span>
                        <span style="font-size: 11px; color: #666;">
                            ${limitData.reason === 'within_limit' ? '✅ Puede reservar' : '❌ Límite alcanzado'}
                        </span>
                    </div>
                </div>
            `;
        }

        /**
         * Función para ocultar el panel de límites
         */
        function hideUserLimitsPanel() {
            const limitsPanel = document.getElementById('reservationLimitsPanel');
            limitsPanel.style.display = 'none';
        }

        /**
         * Función para actualizar el botón de reservar considerando límites
         */
        function updateReserveButtonWithLimits() {
            const reserveBtn = document.getElementById('reserveBtn');
            
            // Validación básica de horarios seleccionados
            if (selectedTimeSlots.length === 0) {
                reserveBtn.disabled = true;
                reserveBtn.innerHTML = '<i class="fas fa-clock"></i> Selecciona al menos 1 horario primero';
                return;
            }

            // Solo el súper administrador Claudio no tiene límites
            if (!userLimits || isSuperAdminClaudio()) {
                reserveBtn.disabled = false;
                const countText = selectedTimeSlots.length === 1 ? '1 reserva' : '2 reservas';
                const adminText = isSuperAdminClaudio() ? ' (Sin límites)' : '';
                reserveBtn.innerHTML = `<i class="fas fa-check"></i> Confirmar ${countText}${adminText}`;
                return;
            }

            // Verificar límites para todos los demás (usuarios normales y administradores normales)
            const currentResourceLimits = userLimits.limits[currentResource];
            
            if (!currentResourceLimits.can_reserve) {
                reserveBtn.disabled = true;
                reserveBtn.innerHTML = '<i class="fas fa-ban"></i> Límite de reservas alcanzado';
                reserveBtn.style.background = 'linear-gradient(135deg, #f44336 0%, #d32f2f 100%)';
                return;
            }

            // Verificar si al hacer las reservas seleccionadas se excedería el límite
            const wouldExceedLimit = selectedTimeSlots.length > currentResourceLimits.remaining;
            
            if (wouldExceedLimit) {
                reserveBtn.disabled = true;
                reserveBtn.innerHTML = `<i class="fas fa-exclamation-triangle"></i> Solo ${currentResourceLimits.remaining} cupo${currentResourceLimits.remaining === 1 ? '' : 's'} restante${currentResourceLimits.remaining === 1 ? '' : 's'}`;
                reserveBtn.style.background = 'linear-gradient(135deg, #ff9800 0%, #f57c00 100%)';
                return;
            }

            // Todo está bien, permitir la reserva
            reserveBtn.disabled = false;
            reserveBtn.style.background = ''; // Resetear estilo
            const countText = selectedTimeSlots.length === 1 ? '1 reserva' : '2 reservas';
            const remainingAfter = currentResourceLimits.remaining - selectedTimeSlots.length;
            reserveBtn.innerHTML = `<i class="fas fa-check"></i> Confirmar ${countText} (${remainingAfter} restante${remainingAfter === 1 ? '' : 's'})`;
        }

        /**
         * Función para verificar límites antes de hacer reserva
         */
        function checkLimitsBeforeReservation() {
            // Verificar si es súper administrador usando la respuesta del backend
            if (!userLimits || (userLimits && userLimits.is_super_admin === true)) {
                console.log('👑 Sin límites para súper admin:', currentUser.name);
                return true; // Sin límites para Claudio
            }

            const currentResourceLimits = userLimits.limits[currentResource];
            
            console.log('📊 Verificando límites antes de reserva:', {
                usuario: currentUser.name,
                recurso: currentResource,
                puede_reservar: currentResourceLimits.can_reserve,
                actual: currentResourceLimits.current_count,
                maximo: currentResourceLimits.max_allowed,
                restantes: currentResourceLimits.remaining
            });
            
            if (!currentResourceLimits.can_reserve) {
                const resourceName = currentResource === 'tablets' ? 'Tablets' : 'Sala de Enlaces';
                const roleText = currentUser.role === 'admin' ? ' (Administrador con límites)' : '';
                showToast(
                    `❌ LÍMITE DE RESERVAS ALCANZADO${roleText}\n\n` +
                    `Ya tienes ${currentResourceLimits.current_count} de ${currentResourceLimits.max_allowed} reservas para ${resourceName} este mes.\n\n` +
                    `💡 Para liberar cupos, un administrador debe confirmar o cancelar tus reservas pendientes.\n\n` +
                    `ℹ️ Solo el súper administrador Claudio tiene acceso ilimitado.`,
                    'error',
                    10000
                );
                return false;
            }

            if (selectedTimeSlots.length > currentResourceLimits.remaining) {
                const resourceName = currentResource === 'tablets' ? 'Tablets' : 'Sala de Enlaces';
                const roleText = currentUser.role === 'admin' ? ' (Administrador con límites)' : '';
                showToast(
                    `⚠️ CUPOS INSUFICIENTES${roleText}\n\n` +
                    `Solo tienes ${currentResourceLimits.remaining} cupo${currentResourceLimits.remaining === 1 ? '' : 's'} restante${currentResourceLimits.remaining === 1 ? '' : 's'} para ${resourceName}.\n\n` +
                    `Has seleccionado ${selectedTimeSlots.length} horario${selectedTimeSlots.length === 1 ? '' : 's'}. Por favor, selecciona solo ${currentResourceLimits.remaining}.\n\n` +
                    `ℹ️ Solo el súper administrador Claudio tiene acceso ilimitado.`,
                    'warning',
                    8000
                );
                return false;
            }

            return true;
        }

        // ===== GESTIÓN DE HORARIOS POR DÍA =====
        
        let scheduleConfigData = null;
        let scheduleConfigChanges = {};
        const DAY_NAMES = { 1: 'Lunes', 2: 'Martes', 3: 'Miércoles', 4: 'Jueves', 5: 'Viernes' };

        async function loadScheduleConfig() {
            if (!currentUser || currentUser.role !== 'admin') return;
            if (!isSuperAdmin()) { showScheduleAccessDenied(); return; }
            const container = document.getElementById('scheduleConfigContainer');
            container.innerHTML = '<div style="text-align:center;padding:40px;"><i class="fas fa-spinner fa-spin" style="font-size:2.2rem;color:#667eea;"></i><p style="color:#666;margin-top:12px;">Cargando configuración de horarios...</p></div>';
            scheduleConfigChanges = {};
            try {
                const resp = await apiRequest('get_schedule_config', 'GET', { admin_name: currentUser.name });
                scheduleConfigData = resp.data;
                renderScheduleConfigPanel();
            } catch (e) {
                container.innerHTML = '<div style="text-align:center;padding:30px;color:#dc2626;"><i class="fas fa-exclamation-triangle" style="font-size:2rem;margin-bottom:10px;display:block;"></i><strong>Error al cargar horarios:</strong> ' + e.message + '<br><button class="btn btn-info" onclick="loadScheduleConfig()" style="margin-top:14px;"><i class="fas fa-redo"></i> Reintentar</button></div>';
            }
        }

        function renderScheduleConfigPanel() {
            const container = document.getElementById('scheduleConfigContainer');
            if (!scheduleConfigData) { container.innerHTML = '<p>Sin datos</p>'; return; }
            const { schedule } = scheduleConfigData;
            const days = [1, 2, 3, 4, 5];

            let tableRows = schedule.map(slot => {
                let cells = days.map(d => {
                    const info = slot.por_dia[d];
                    const key = slot.id + '_' + d;
                    const isActive = key in scheduleConfigChanges ? scheduleConfigChanges[key] : info.activo;
                    const updInfo = info.updated_by ? '<span class="slot-update-info">' + info.updated_by + '<br>' + (info.updated_at||'').substring(0,10) + '</span>' : '';
                    return '<td><div class="slot-status-cell"><label class="toggle-day-btn" title="' + DAY_NAMES[d] + ': ' + (isActive ? 'Activo' : 'Inactivo') + '"><input type="checkbox" ' + (isActive ? 'checked' : '') + ' onchange="onScheduleToggle(' + slot.id + ', ' + d + ', this.checked)"><span class="toggle-slider"></span></label>' + updInfo + '</div></td>';
                }).join('');

                const activeCount = days.filter(d => {
                    const key = slot.id + '_' + d;
                    return key in scheduleConfigChanges ? scheduleConfigChanges[key] : slot.por_dia[d].activo;
                }).length;

                return '<tr data-slot-id="' + slot.id + '"><td><div class="slot-name-cell"><i class="fas fa-clock slot-icon"></i><span class="slot-time-text">' + slot.horario + '</span><span class="slot-day-count">(' + activeCount + '/5 días)</span></div></td>' + cells + '<td><div class="slot-action-btns"><button class="slot-btn slot-btn-edit" onclick="openEditSlotModal(' + slot.id + ', \'' + slot.horario + '\')" title="Editar horario"><i class="fas fa-pencil-alt"></i></button><button class="slot-btn slot-btn-delete" onclick="confirmDeleteSlot(' + slot.id + ', \'' + slot.horario + '\')" title="Eliminar horario"><i class="fas fa-trash-alt"></i></button></div></td></tr>';
            }).join('');

            const changesCount = Object.keys(scheduleConfigChanges).length;
            const dayHeaders = days.map(d => '<th><i class="fas fa-calendar-day"></i><br>' + DAY_NAMES[d] + '</th>').join('');
            const dayChecks = [1,2,3,4,5].map(d => '<label class="slot-day-check"><input type="checkbox" id="newSlotDay_' + d + '" checked><span class="slot-day-label">' + DAY_NAMES[d] + '</span></label>').join('');

            container.innerHTML =
                '<div class="schedule-config-panel">' +
                  '<div class="schedule-panel-header">' +
                    '<div>' +
                      '<h4><i class="fas fa-calendar-alt"></i> Configuración de Horarios por Día</h4>' +
                      '<p class="subtitle">Activa o desactiva horarios por día. Edita o elimina con los botones de cada fila, o añade nuevos con el botón verde.</p>' +
                    '</div>' +
                    '<button class="btn-add-slot" onclick="openAddSlotModal()"><i class="fas fa-plus"></i> Añadir Horario</button>' +
                  '</div>' +
                  '<div class="schedule-legend">' +
                    '<span style="font-weight:700;color:#374151;">Leyenda:</span>' +
                    '<span class="schedule-legend-item"><span class="legend-dot active"></span> Activo</span>' +
                    '<span class="schedule-legend-item"><span class="legend-dot inactive"></span> Desactivado</span>' +
                    '<span style="color:#9ca3af;font-size:0.8rem;margin-left:auto;"><i class="fas fa-info-circle"></i> Los cambios de toggle aplican al guardar</span>' +
                  '</div>' +
                  '<div class="schedule-table-wrapper">' +
                    '<table class="schedule-config-table">' +
                      '<thead><tr><th style="text-align:left;">Horario</th>' + dayHeaders + '<th>Acciones</th></tr></thead>' +
                      '<tbody>' + tableRows + '</tbody>' +
                    '</table>' +
                  '</div>' +
                  '<div class="schedule-save-bar">' +
                    '<div class="changes-badge ' + (changesCount === 0 ? 'no-changes' : '') + '">' +
                      (changesCount === 0 ? '<i class="fas fa-check-circle"></i> Sin cambios de toggle pendientes' : '<i class="fas fa-edit"></i> ' + changesCount + ' cambio' + (changesCount !== 1 ? 's' : '') + ' sin guardar') +
                    '</div>' +
                    '<div style="display:flex;gap:10px;flex-wrap:wrap;">' +
                      '<button class="btn-reload-schedule" onclick="loadScheduleConfig()"><i class="fas fa-sync-alt"></i> Recargar</button>' +
                      '<button class="btn-save-schedule" id="btnSaveSchedule" onclick="saveScheduleConfig()" ' + (changesCount === 0 ? 'disabled' : '') + '><i class="fas fa-save"></i> Guardar Cambios</button>' +
                    '</div>' +
                  '</div>' +
                '</div>' +
                '<div id="slotModal" class="slot-modal-overlay" onclick="closeSlotModal(event)">' +
                  '<div class="slot-modal">' +
                    '<div class="slot-modal-header">' +
                      '<h3 id="slotModalTitle"><i class="fas fa-clock"></i> Horario</h3>' +
                      '<button class="slot-modal-close" onclick="closeSlotModalDirect()"><i class="fas fa-times"></i></button>' +
                    '</div>' +
                    '<div class="slot-modal-body">' +
                      '<div class="slot-modal-field">' +
                        '<div class="slot-time-pickers">' +
                          '<div class="slot-time-picker-group">' +
                            '<label for="slotTimeStart"><i class="fas fa-hourglass-start"></i> Hora inicio</label>' +
                            '<input type="time" id="slotTimeStart" oninput="onSlotTimePick()">' +
                          '</div>' +
                          '<div class="slot-time-picker-arrow"><i class="fas fa-arrow-right"></i></div>' +
                          '<div class="slot-time-picker-group">' +
                            '<label for="slotTimeEnd"><i class="fas fa-hourglass-end"></i> Hora término</label>' +
                            '<input type="time" id="slotTimeEnd" oninput="onSlotTimePick()">' +
                          '</div>' +
                        '</div>' +
                        '<div id="slotTimePreview" class="slot-time-preview" style="display:none;"></div>' +
                        '<div id="slotInputError" class="slot-input-error" style="display:none;"></div>' +
                      '</div>' +
                      '<div id="slotModalDaysToggle" style="display:none;">' +
                        '<label style="font-weight:600;color:#374151;margin-bottom:10px;display:block;"><i class="fas fa-calendar-week"></i> Días activos para este horario</label>' +
                        '<div class="slot-days-grid">' + dayChecks + '</div>' +
                      '</div>' +
                    '</div>' +
                    '<div class="slot-modal-footer">' +
                      '<button class="slot-modal-btn slot-modal-btn-cancel" onclick="closeSlotModalDirect()"><i class="fas fa-times"></i> Cancelar</button>' +
                      '<button class="slot-modal-btn slot-modal-btn-save" id="slotModalSaveBtn" onclick="saveSlotModal()"><i class="fas fa-save"></i> Guardar</button>' +
                    '</div>' +
                  '</div>' +
                '</div>' +
                '<div id="deleteSlotModal" class="slot-modal-overlay" onclick="closeDeleteModal(event)">' +
                  '<div class="slot-modal slot-modal-sm">' +
                    '<div class="slot-modal-header slot-modal-header-danger">' +
                      '<h3><i class="fas fa-exclamation-triangle"></i> Confirmar Eliminación</h3>' +
                      '<button class="slot-modal-close" onclick="closeDeleteModalDirect()"><i class="fas fa-times"></i></button>' +
                    '</div>' +
                    '<div class="slot-modal-body">' +
                      '<p style="color:#374151;font-size:0.95rem;line-height:1.6;margin-bottom:8px;">¿Seguro que deseas eliminar el horario:</p>' +
                      '<div class="delete-slot-name" id="deleteSlotName"></div>' +
                      '<div class="delete-warning"><i class="fas fa-info-circle"></i> El horario dejará de aparecer en el calendario. Las reservas históricas no se borran.</div>' +
                    '</div>' +
                    '<div class="slot-modal-footer">' +
                      '<button class="slot-modal-btn slot-modal-btn-cancel" onclick="closeDeleteModalDirect()"><i class="fas fa-times"></i> Cancelar</button>' +
                      '<button class="slot-modal-btn slot-modal-btn-danger" id="confirmDeleteBtn" onclick="executeDeleteSlot()"><i class="fas fa-trash-alt"></i> Eliminar</button>' +
                    '</div>' +
                  '</div>' +
                '</div>';
        }

        function onScheduleToggle(horarioId, dia, checked) {
            const key = horarioId + '_' + dia;
            const original = scheduleConfigData.schedule.find(s => s.id === horarioId)?.por_dia[dia]?.activo;
            if (checked === original) delete scheduleConfigChanges[key];
            else scheduleConfigChanges[key] = checked;
            refreshScheduleSaveBar();
        }

        function refreshScheduleSaveBar() {
            const days = [1,2,3,4,5];
            scheduleConfigData.schedule.forEach(slot => {
                const activeCount = days.filter(d => {
                    const key = slot.id + '_' + d;
                    return key in scheduleConfigChanges ? scheduleConfigChanges[key] : slot.por_dia[d].activo;
                }).length;
                document.querySelectorAll('.schedule-config-table tbody tr').forEach(row => {
                    if (parseInt(row.dataset.slotId) === slot.id) {
                        const badge = row.querySelector('.slot-day-count');
                        if (badge) badge.textContent = '(' + activeCount + '/5 días)';
                    }
                });
            });
            const changesCount = Object.keys(scheduleConfigChanges).length;
            const badge = document.querySelector('.schedule-save-bar .changes-badge');
            const btn = document.getElementById('btnSaveSchedule');
            if (badge) {
                badge.className = 'changes-badge ' + (changesCount === 0 ? 'no-changes' : '');
                badge.innerHTML = changesCount === 0
                    ? '<i class="fas fa-check-circle"></i> Sin cambios de toggle pendientes'
                    : '<i class="fas fa-edit"></i> ' + changesCount + ' cambio' + (changesCount !== 1 ? 's' : '') + ' sin guardar';
            }
            if (btn) btn.disabled = (changesCount === 0);
        }

        async function saveScheduleConfig() {
            if (Object.keys(scheduleConfigChanges).length === 0) return;
            const updates = Object.entries(scheduleConfigChanges).map(([key, activo]) => {
                const [horario_id, dia_semana] = key.split('_').map(Number);
                return { horario_id, dia_semana, activo };
            });
            const btn = document.getElementById('btnSaveSchedule');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Guardando...';
            try {
                await apiRequest('update_schedule_config', 'POST', { admin_name: currentUser.name, updates });
                showToast('✅ ' + updates.length + ' cambio' + (updates.length !== 1 ? 's' : '') + ' guardado' + (updates.length !== 1 ? 's' : '') + ' correctamente.', 'success', 5000);
                scheduleConfigChanges = {};
                await loadScheduleConfig();
                await loadSchedule();
            } catch (e) {
                showToast('❌ Error al guardar: ' + e.message, 'error', 7000);
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-save"></i> Guardar Cambios';
            }
        }

        let slotModalMode = 'add';
        let slotModalEditId = null;

        function openAddSlotModal() {
            slotModalMode = 'add';
            slotModalEditId = null;
            document.getElementById('slotModalTitle').innerHTML = '<i class="fas fa-plus-circle"></i> Añadir Nuevo Horario';
            document.getElementById('slotTimeStart').value = '';
            document.getElementById('slotTimeEnd').value = '';
            document.getElementById('slotTimePreview').style.display = 'none';
            document.getElementById('slotInputError').style.display = 'none';
            document.getElementById('slotModalDaysToggle').style.display = 'block';
            [1,2,3,4,5].forEach(d => { const cb = document.getElementById('newSlotDay_' + d); if (cb) cb.checked = true; });
            const btn = document.getElementById('slotModalSaveBtn');
            btn.innerHTML = '<i class="fas fa-plus"></i> Añadir';
            btn.className = 'slot-modal-btn slot-modal-btn-save';
            btn.disabled = false;
            document.getElementById('slotModal').classList.add('show');
            setTimeout(() => document.getElementById('slotTimeStart').focus(), 150);
        }

        function openEditSlotModal(id, horario) {
            slotModalMode = 'edit';
            slotModalEditId = id;
            document.getElementById('slotModalTitle').innerHTML = '<i class="fas fa-pencil-alt"></i> Editar Horario';
            const parts = horario.split(' - ');
            document.getElementById('slotTimeStart').value = parts[0] ? parts[0].trim() : '';
            document.getElementById('slotTimeEnd').value = parts[1] ? parts[1].trim() : '';
            onSlotTimePick();
            document.getElementById('slotInputError').style.display = 'none';
            document.getElementById('slotModalDaysToggle').style.display = 'none';
            const btn = document.getElementById('slotModalSaveBtn');
            btn.innerHTML = '<i class="fas fa-save"></i> Guardar Cambio';
            btn.className = 'slot-modal-btn slot-modal-btn-save';
            btn.disabled = false;
            document.getElementById('slotModal').classList.add('show');
            setTimeout(() => document.getElementById('slotTimeStart').focus(), 150);
        }

        function closeSlotModal(e) { if (e.target.id === 'slotModal') closeSlotModalDirect(); }
        function closeSlotModalDirect() { document.getElementById('slotModal').classList.remove('show'); }

        function onSlotTimePick() {
            const start = document.getElementById('slotTimeStart').value;
            const end   = document.getElementById('slotTimeEnd').value;
            const preview = document.getElementById('slotTimePreview');
            const errorEl = document.getElementById('slotInputError');
            if (start && end) {
                if (end <= start) {
                    errorEl.textContent = 'La hora de término debe ser mayor que la de inicio.';
                    errorEl.style.display = 'block';
                    preview.style.display = 'none';
                } else {
                    errorEl.style.display = 'none';
                    preview.innerHTML = '<i class="fas fa-check-circle"></i> Horario: <strong>' + start + ' - ' + end + '</strong>';
                    preview.style.display = 'flex';
                }
            } else {
                preview.style.display = 'none';
                errorEl.style.display = 'none';
            }
        }

        async function saveSlotModal() {
            const start = document.getElementById('slotTimeStart').value;
            const end   = document.getElementById('slotTimeEnd').value;
            const errorEl = document.getElementById('slotInputError');
            if (!start || !end) { errorEl.textContent = 'Debes seleccionar hora de inicio y término.'; errorEl.style.display = 'block'; return; }
            if (end <= start) { errorEl.textContent = 'La hora de término debe ser mayor que la de inicio.'; errorEl.style.display = 'block'; return; }
            const horario = start + ' - ' + end;
            const btn = document.getElementById('slotModalSaveBtn');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Guardando...';
            try {
                if (slotModalMode === 'add') {
                    await apiRequest('add_time_slot', 'POST', { admin_name: currentUser.name, horario });
                    showToast('✅ Horario "' + horario + '" añadido correctamente.', 'success', 5000);
                } else {
                    await apiRequest('edit_time_slot', 'POST', { admin_name: currentUser.name, horario_id: slotModalEditId, horario });
                    showToast('✅ Horario actualizado a "' + horario + '".', 'success', 5000);
                }
                closeSlotModalDirect();
                await loadScheduleConfig();
                await loadSchedule();
            } catch (e) {
                btn.disabled = false;
                btn.innerHTML = slotModalMode === 'add' ? '<i class="fas fa-plus"></i> Añadir' : '<i class="fas fa-save"></i> Guardar Cambio';
                errorEl.textContent = e.message;
                errorEl.style.display = 'block';
            }
        }

        let deleteSlotId = null;
        let deleteSlotHorario = '';

        function confirmDeleteSlot(id, horario) {
            deleteSlotId = id;
            deleteSlotHorario = horario;
            document.getElementById('deleteSlotName').textContent = horario;
            const btn = document.getElementById('confirmDeleteBtn');
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-trash-alt"></i> Eliminar';
            document.getElementById('deleteSlotModal').classList.add('show');
        }
        function closeDeleteModal(e) { if (e.target.id === 'deleteSlotModal') closeDeleteModalDirect(); }
        function closeDeleteModalDirect() { document.getElementById('deleteSlotModal').classList.remove('show'); }

        async function executeDeleteSlot() {
            const btn = document.getElementById('confirmDeleteBtn');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Eliminando...';
            try {
                await apiRequest('delete_time_slot', 'POST', { admin_name: currentUser.name, horario_id: deleteSlotId, force: true });
                showToast('🗑️ Horario "' + deleteSlotHorario + '" eliminado correctamente.', 'success', 5000);
                closeDeleteModalDirect();
                await loadScheduleConfig();
                await loadSchedule();
            } catch (e) {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-trash-alt"></i> Eliminar';
                showToast('❌ Error al eliminar: ' + e.message, 'error', 7000);
            }
        }

        // ===== FIN GESTIÓN DE HORARIOS =====



        function openRegistroReservas() {
            if (!currentUser || currentUser.role !== 'admin') {
                showToast('Solo los administradores pueden acceder al registro de reservas', 'error');
                return;
            }

            try {
                // Crear datos de autenticación para pasar a la nueva ventana
                const authData = {
                    user: currentUser,
                    timestamp: new Date().getTime(),
                    action: 'open_registro'
                };
                
                // Almacenar temporalmente en sessionStorage para compartir entre ventanas
                sessionStorage.setItem('authData', JSON.stringify(authData));
                
                // Abrir ventana con parámetros de autenticación
                const registroWindow = window.open(
                    `registro-reservas.html?auth=temp&user=${encodeURIComponent(currentUser.username)}&role=${currentUser.role}&time=${authData.timestamp}`, 
                    'registroReservas', 
                    'width=1400,height=900,scrollbars=yes,resizable=yes,location=yes,menubar=yes,toolbar=yes'
                );
                
                if (!registroWindow) {
                    showToast('No se pudo abrir ventana nueva. Verifica el bloqueador de ventanas emergentes.', 'warning');
                    return;
                }
                
                // Enviar datos de autenticación cuando la ventana se cargue
                const sendAuthData = () => {
                    try {
                        registroWindow.postMessage({
                            type: 'authenticate',
                            authData: authData
                        }, '*');
                        showToast('Abriendo Registro de Reservas con sesión autenticada...', 'success', 3000);
                    } catch (e) {
                        console.warn('No se pudo enviar datos de autenticación:', e);
                    }
                };

                // Intentar enviar datos después de un breve delay
                setTimeout(sendAuthData, 1000);
                
                // También intentar cuando la ventana cargue completamente
                registroWindow.onload = sendAuthData;
                
            } catch (error) {
                console.error('Error al abrir registro:', error);
                showToast('Error al abrir registro de reservas: ' + error.message, 'error');
            }
        }

        // ===== FUNCIÓN PARA FORMATEAR FECHA/HORA EN ZONA HORARIA DE CHILE =====
        function formatChileDateTime(dateTimeString) {
            if (!dateTimeString) return '';
            
            try {
                const date = new Date(dateTimeString);
                
                if (isNaN(date.getTime())) {
                    console.warn('⚠️ Fecha inválida recibida:', dateTimeString);
                    return 'Fecha inválida';
                }
                
                const chileTime = date.toLocaleString('es-CL', {
                    timeZone: 'America/Santiago',
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                    hour12: false
                });
                
                return chileTime;
                
            } catch (error) {
                console.error('❌ Error al formatear fecha para Chile:', error);
                return 'Error en fecha';
            }
        }

        // ===== FUNCIÓN AUXILIAR PARA OBTENER HORA ACTUAL DE CHILE =====
        function getCurrentChileTime() {
            const now = new Date();
            return now.toLocaleString('es-CL', {
                timeZone: 'America/Santiago',
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
               // second: '2-digit',
                hour12: false
            });
        }

        // ===== FUNCIONES PARA VERIFICAR SI ES RESERVA PROPIA =====
        function isUserOwnReservation(reservation) {
            if (!currentUser || !reservation) {
                return false;
            }
            
            // Verificar tanto por user_name como por reserved_by
            const isReservedByUser = reservation.reserved_by === currentUser.name;
            const isUserNameMatch = reservation.user_name === currentUser.name;
            
            return isReservedByUser || isUserNameMatch;
        }

        function canUserCancelReservation(reservation) {
            if (!currentUser || !reservation) {
                return false;
            }
            
            const isAdmin = currentUser.role === 'admin';
            const isOwnReservation = isUserOwnReservation(reservation);
            const isPending = reservation.attendance === null || reservation.attendance === undefined;
            
            // Los administradores pueden cancelar cualquier reserva en cualquier estado
            if (isAdmin) {
                return true;
            }
            
            // Los docentes solo pueden cancelar sus propias reservas que estén pendientes
            if (isOwnReservation && isPending) {
                return true;
            }
            
            return false;
        }

        // ===== FUNCIÓN PARA GENERAR BOTONES DE ACCIÓN MEJORADA =====
        function generateActionButtons(reservation) {
            if (!currentUser || !reservation) {
                return '';
            }
            
            const isAdmin = currentUser.role === 'admin';
            const isOwnReservation = isUserOwnReservation(reservation);
            const canCancel = canUserCancelReservation(reservation);
            const isPending = reservation.attendance === null || reservation.attendance === undefined;
            
            let buttons = '';
            
            // BOTONES DE CANCELACIÓN
            if (canCancel) {
                if (isAdmin) {
                    // Administradores - pueden cancelar cualquier reserva
                    buttons += `
                        <button class="btn btn-danger" onclick="cancelReservation(${reservation.id})" title="Cancelar reserva (Administrador)">
                            <i class="fas fa-trash"></i> Cancelar Reserva
                        </button>`;
                } else if (isOwnReservation && isPending) {
                    // Docentes - solo pueden cancelar sus reservas pendientes
                    buttons += `
                        <button class="btn btn-cancel-own" onclick="cancelOwnReservation(${reservation.id})" title="Cancelar mi reserva">
                            <i class="fas fa-times-circle"></i> Cancelar mi reserva
                        </button>`;
                }
            } else if (isOwnReservation && !isPending) {
                // Mostrar mensaje informativo para reservas propias ya confirmadas
                const statusText = reservation.attendance == 1 ? 'con asistencia confirmada' : 'marcada como ausente';
                buttons += `
                    <div class="info-message">
                        <i class="fas fa-info-circle"></i>
                        <span>No se puede cancelar - Reserva ${statusText}</span>
                        <small>Solo administradores pueden cancelar reservas con estado confirmado</small>
                    </div>`;
            }
            
            // BOTONES DE ASISTENCIA (solo para administradores)
            if (isAdmin) {
                buttons += generateAttendanceButtons(reservation);
            }
            
            // Si hay botones, envolverlos en un div
            if (buttons) {
                return `<div class="action-buttons">${buttons}</div>`;
            }
            
            return '';
        }

        // ===== FUNCIÓN PARA GENERAR INDICADOR DE ESTADO DE RESERVA =====
        function getReservationStatusIndicator(reservation) {
            if (!reservation) return '';
            
            const isOwn = isUserOwnReservation(reservation);
            
            let statusClass, statusIcon, statusText;
            
            if (reservation.attendance == 1) {
                statusClass = 'confirmed';
                statusIcon = 'fas fa-check-circle';
                statusText = 'Asistencia Confirmada';
            } else if (reservation.attendance == 0) {
                statusClass = 'no-show';
                statusIcon = 'fas fa-times-circle';
                statusText = 'Marcado como Ausente';
            } else {
                statusClass = 'pending';
                statusIcon = 'fas fa-clock';
                statusText = 'Pendiente de Confirmación';
            }
            
            let indicator = `
                <div class="reservation-status-indicator ${statusClass}">
                    <i class="${statusIcon}"></i>
                    ${statusText}
                </div>
            `;
            
            if (isOwn) {
                indicator = `
                    <div class="own-reservation-indicator">
                        <i class="fas fa-user"></i>
                        Mi Reserva
                    </div>
                    ${indicator}
                `;
            }
            
            return indicator;
        }

        // ===== FUNCIÓN PARA FORMATEAR FECHA PARA MOSTRAR =====
        function formatDateForDisplay(dateString) {
            try {
                if (!dateString) return 'Fecha no disponible';
                
                const date = new Date(dateString + 'T00:00:00');
                return date.toLocaleDateString('es-CL', {
                    weekday: 'long',
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                });
            } catch (error) {
                console.warn('Error al formatear fecha:', error);
                return dateString;
            }
        }




        // ===== FUNCIÓN PRINCIPAL PARA CANCELAR RESERVA PROPIA (MEJORADA) =====
        async function cancelOwnReservation(reservationId) {
            try {
                // Verificar que el usuario esté logueado
                if (!currentUser || !currentUser.name) {
                    showToast('Error de sesión. Por favor, cierre sesión e inicie sesión nuevamente.', 'error');
                    setTimeout(() => logout(), 3000);
                    return;
                }

                // Mostrar indicador de carga inmediatamente
                const timeSlotElement = document.querySelector(`[data-reservation-id="${reservationId}"]`);
                if (timeSlotElement) {
                    timeSlotElement.classList.add('cancellation-pending');
                }

                // Obtener detalles actualizados de la reserva para verificar estado
                console.log(`🔍 Verificando estado actual de la reserva ${reservationId}`);
                
                const detailsResponse = await apiRequest('get_reservation_details', 'GET', { id: reservationId });
                const reservation = detailsResponse.data;
                
                if (!reservation) {
                    showToast('La reserva no fue encontrada. Es posible que ya haya sido cancelada.', 'warning');
                    await loadSchedule(); // Recargar para mostrar estado actual
                    return;
                }
                
                // Verificar que es del usuario actual
                if (!isUserOwnReservation(reservation)) {
                    showToast('No tiene permisos para cancelar esta reserva. Solo puede cancelar sus propias reservas.', 'error');
                    return;
                }
                
                // Verificar que está pendiente
                if (reservation.attendance !== null && reservation.attendance !== undefined) {
                    const attendanceStatus = reservation.attendance == 1 ? 'confirmada (asistió)' : 'confirmada (no asistió)';
                    showToast(`No puede cancelar esta reserva porque ya tiene asistencia ${attendanceStatus}. Solo los administradores pueden cancelar reservas confirmadas.`, 'warning', 8000);
                    await loadSchedule(); // Recargar para mostrar estado actual
                    return;
                }
                
                // Formatear fecha para mostrar
                const formattedDate = formatDateForDisplay(reservation.reservation_date);
                const resourceName = reservation.resource_type === 'tablets' ? 'Tablets' : 'Sala de Enlaces';
                
                // Confirmación personalizada y detallada
                const confirmMessage = `¿Está seguro que desea cancelar su reserva?\n\n` +
                                      `📅 Fecha: ${formattedDate}\n` +
                                      `⏰ Horario: ${reservation.time_slot}\n` +
                                      `💻 Recurso: ${resourceName}\n` +
                                      `📚 Asignatura: ${reservation.purpose}\n` +
                                      `🏫 Curso: ${reservation.course}\n\n` +
                                      `✅ Esta acción liberará el horario para que otros docentes puedan reservarlo.\n\n` +
                                      `⚠️ Una vez cancelada, no podrá deshacer esta acción.`;
                
                if (!confirm(confirmMessage)) {
                    // Remover indicador de carga si el usuario cancela
                    if (timeSlotElement) {
                        timeSlotElement.classList.remove('cancellation-pending');
                    }
                    return;
                }

                console.log(`🔄 Usuario ${currentUser.name} cancelando su propia reserva ${reservationId}`);
                
                showToast('Cancelando su reserva...', 'info', 3000);
                
                // Llamar al endpoint específico para cancelación de usuarios
                const response = await apiRequest('cancel_own_reservation', 'DELETE', { 
                    id: reservationId,
                    user_name: currentUser.name
                });
                
                // Recargar horarios y límites para mostrar el cambio
                await loadSchedule();
                await loadUserLimits(); // NUEVO: Recargar límites después de cancelar
                
                // Mostrar mensaje de éxito con detalles
                const successMessage = `✅ Su reserva de ${resourceName} para el ${formattedDate} a las ${reservation.time_slot} ha sido cancelada exitosamente.\n\n🎯 El horario ya está disponible para que otros docentes puedan reservarlo.`;
                
                showToast(successMessage, 'success', 6000);
                
                // Log para auditoría
                console.log(`✅ Reserva ${reservationId} cancelada exitosamente por usuario ${currentUser.name}`);
                
            } catch (error) {
                console.error('❌ Error al cancelar reserva propia:', error);
                
                // Remover indicador de carga
                const timeSlotElement = document.querySelector(`[data-reservation-id="${reservationId}"]`);
                if (timeSlotElement) {
                    timeSlotElement.classList.remove('cancellation-pending');
                }
                
                // Determinar mensaje de error específico
                let errorMessage = 'Error al cancelar su reserva: ' + error.message;
                
                if (error.message.includes('confirmada') || error.message.includes('asistencia')) {
                    errorMessage = 'No puede cancelar esta reserva porque ya tiene confirmación de asistencia. Solo los administradores pueden cancelar reservas confirmadas.';
                } else if (error.message.includes('permiso') || error.message.includes('autorizado')) {
                    errorMessage = 'No tiene permisos para cancelar esta reserva. Solo puede cancelar sus propias reservas pendientes.';
                } else if (error.message.includes('encontrada')) {
                    errorMessage = 'La reserva no fue encontrada. Es posible que ya haya sido cancelada por un administrador.';
                } else if (error.message.includes('sesión') || error.message.includes('identificar')) {
                    errorMessage = 'Error de sesión. Por favor, cierre sesión e inicie sesión nuevamente.';
                    setTimeout(() => logout(), 3000);
                }
                
                showToast(errorMessage, 'error');
                
                // Recargar para mostrar estado actual
                await loadSchedule();
            }
        }

        // ===== FUNCIÓN MEJORADA PARA CREAR ELEMENTOS DE HORARIO CON EVENT DELEGATION =====
        function createTimeSlotElement(timeSlot, reservation) {
            const div = document.createElement('div');
            
            const resourceIcon = currentResource === 'tablets' ? '📱' : '🖥️';
            const resourceName = currentResource === 'tablets' ? 'Tablets' : 'Sala de Enlaces';
            
            let status, statusClass, statusText, clickable = false;

            // Verificar si es reserva propia
            const isOwnReservation = reservation && isUserOwnReservation(reservation);

            if (!reservation) {
                status = 'available';
                statusClass = 'available clickable-available'; // AGREGAR CLASE CLICKABLE
                statusText = 'Disponible';
                clickable = true;
            } else {
                if (reservation.attendance == 1) {
                    status = 'confirmed';
                    statusClass = 'confirmed';
                    statusText = 'Asistió';
                } else if (reservation.attendance == 0) {
                    status = 'no-show';
                    statusClass = 'no-show';
                    statusText = 'No asistió';
                } else {
                    status = 'reserved';
                    statusClass = 'reserved';
                    statusText = 'Reservado';
                }
            }
            
            // Agregar clases especiales para reservas propias
            if (isOwnReservation) {
                statusClass += ' own-reservation';
            }
            
            if (reservation) {
                div.setAttribute('data-reservation-id', reservation.id);
                div.setAttribute('data-reservation-slot', timeSlot);
            } else {
                div.setAttribute('data-time-slot', timeSlot);
            }
            
            div.setAttribute('data-resource-type', currentResource);
            
            if (selectedTimeSlots.includes(timeSlot) && clickable) {
                statusClass += ' selected';
                statusText = 'Seleccionado';
            }
            
            div.className = `time-slot ${statusClass}`;
            
            // Hacer el elemento clickable si está disponible
            if (clickable) {
                div.style.cursor = 'pointer';
            }
            
            // Construir el contenido HTML
            div.innerHTML = `
                <div class="time-header">
                    <div class="time-text">${timeSlot}</div>
                    <div class="status-pill ${selectedTimeSlots.includes(timeSlot) && clickable ? 'selected' : status}">
                        ${resourceIcon} ${statusText}
                    </div>
                </div>
                
                ${reservation ? `
                    <div class="reservation-details">
                        <strong>Recurso:</strong> ${resourceIcon} ${resourceName}<br>
                        <strong>Docente:</strong> ${reservation.user_name}<br>
                        <strong>Curso:</strong> ${reservation.course}<br>
                        <strong>Asignatura:</strong> ${reservation.purpose}<br>
                        <strong>Reservado por:</strong> ${reservation.reserved_by}
                    </div>
                    
                    ${getReservationStatusIndicator(reservation)}
                    
                    ${generateActionButtons(reservation)}
                ` : `
                    <div class="reservation-details">
                        <strong>${resourceIcon} ${resourceName}</strong><br>
                        <span style="color: #4caf50;">
                            <i class="fas fa-check-circle"></i> Disponible para reservar
                        </span>
                        ${clickable ? '<br><br><span style="color: #667eea; font-weight: 600;"><i class="fas fa-hand-pointer"></i> Haz clic para seleccionar/deseleccionar este horario</span>' : ''}
                    </div>
                `}
            `;
            
            return div;
        }

        function setupEventDelegation() {
            const scheduleGrid = document.getElementById('scheduleGrid');
            
            if (!scheduleGrid) return;
            
            // Limpiar event listeners anteriores
            const newScheduleGrid = scheduleGrid.cloneNode(true);
            scheduleGrid.parentNode.replaceChild(newScheduleGrid, scheduleGrid);
            
            const currentScheduleGrid = document.getElementById('scheduleGrid');
            
            // Event delegation SOLO para seleccionar horarios disponibles
            currentScheduleGrid.addEventListener('click', function(event) {
                const timeSlotElement = event.target.closest('.time-slot');
                
                if (!timeSlotElement) return;
                
                if (timeSlotElement.classList.contains('clickable-available') && 
                    !timeSlotElement.classList.contains('restricted')) {
                    
                    event.preventDefault();
                    event.stopPropagation();
                    
                    const timeSlot = timeSlotElement.getAttribute('data-time-slot');
                    if (timeSlot) {
                        selectTimeSlot(timeSlot);
                    }
                }
            });
            
            // ❌ COMENTAR TODO EL RESTO DEL EVENT DELEGATION PARA BOTONES
            // Los botones usarán sus onclick directo en el HTML
        }


        // ===== FUNCIÓN AUXILIAR PARA EXTRAER ID DE RESERVA =====
        function extractReservationIdFromButton(button) {
            if (!button) return null;
            
            // Buscar en el onclick attribute
            const onclickAttr = button.getAttribute('onclick');
            if (onclickAttr) {
                const match = onclickAttr.match(/(confirmAttendance|markNoShow|resetAttendance|cancelOwnReservation|cancelReservation)\((\d+)\)/);
                if (match && match[2]) {
                    return parseInt(match[2]);
                }
            }
            
            // Buscar en el elemento padre (time-slot)
            const timeSlotElement = button.closest('.time-slot');
            if (timeSlotElement) {
                return timeSlotElement.getAttribute('data-reservation-id');
            }
            
            return null;
        }



        // ===== FUNCIÓN PARA GENERAR BOTONES DE ASISTENCIA =====
        function generateAttendanceButtons(reservation) {
            if (!currentUser || currentUser.role !== 'admin') {
                return '';
            }

            if (reservation.attendance == 1) {
                return `
                    <button class="btn btn-warning" onclick="markNoShow(${reservation.id})" title="Cambiar a No Asistió">
                        <i class="fas fa-times"></i> Marcar ausente
                    </button>
                    <button class="btn btn-info" onclick="resetAttendance(${reservation.id})" title="Volver a estado pendiente">
                        <i class="fas fa-undo"></i> Resetear estado
                    </button>`;
            } else if (reservation.attendance == 0) {
                return `
                    <button class="btn btn-success" onclick="confirmAttendance(${reservation.id})" title="Cambiar a Asistió">
                        <i class="fas fa-check"></i> Marcar presente
                    </button>
                    <button class="btn btn-info" onclick="resetAttendance(${reservation.id})" title="Volver a estado pendiente">
                        <i class="fas fa-undo"></i> Resetear estado
                    </button>`;
            } else {
                return `
                    <button class="btn btn-success" onclick="confirmAttendance(${reservation.id})" title="Confirmar asistencia">
                        <i class="fas fa-check"></i> Confirmar asistencia
                    </button>
                    <button class="btn btn-secondary" onclick="markNoShow(${reservation.id})" title="Marcar como ausente">
                        <i class="fas fa-times"></i> No asistió
                    </button>`;
            }
        }

        // ===== FUNCIÓN PARA RESETEAR ESTADO DE ASISTENCIA =====
        async function resetAttendance(reservationId) {
            if (!currentUser || currentUser.role !== 'admin') {
                showToast('Solo los administradores pueden resetear el estado de asistencia', 'error');
                return;
            }

            const confirmMessage = `¿Está seguro que desea resetear el estado de asistencia a "Pendiente"?\n\n` +
                                  `✅ Esto permitirá que el docente pueda cancelar su propia reserva nuevamente.\n\n` +
                                  `⚠️ Esta acción quedará registrada en el sistema.`;
            
            if (!confirm(confirmMessage)) {
                return;
            }

            try {
                console.log(`🔄 Administrador ${currentUser.name} reseteando estado de asistencia para reserva ${reservationId}`);
                
                showToast('Reseteando estado de asistencia...', 'info', 3000);
                
                await apiRequest('reset_attendance', 'PUT', {
                    id: reservationId,
                    admin_name: currentUser.name
                });

                await loadSchedule();
                await loadUserLimits(); // NUEVO: Recargar límites después de resetear
                
                const chileTime = getCurrentChileTime();
                showToast(`✅ Estado de asistencia reseteado a "Pendiente".\n\nEl docente ya puede cancelar su reserva si lo desea.\n\nHora: ${chileTime} (Hora Chile)`, 'success', 6000);
                
            } catch (error) {
                console.error('❌ Error al resetear asistencia:', error);
                showToast('Error al resetear estado de asistencia: ' + error.message, 'error');
            }
        }

        // ===== FUNCIONES PARA CANCELACIÓN ADMINISTRATIVA =====
        async function cancelReservation(reservationId) {
            try {
                // Verificar que es administrador
                if (!currentUser || currentUser.role !== 'admin') {
                    showToast('Solo los administradores pueden usar esta función de cancelación', 'error');
                    return;
                }

                // Obtener detalles de la reserva para mostrar información completa
                const response = await apiRequest('get_reservation_details', 'GET', { id: reservationId });
                const reservation = response.data;
                
                if (!reservation) {
                    showToast('La reserva no fue encontrada', 'error');
                    return;
                }
                
                const attendanceStatus = reservation.attendance == 1 ? 'ASISTIÓ' : 
                                       reservation.attendance == 0 ? 'NO ASISTIÓ' : 'PENDIENTE';
                
                const formattedDate = formatDateForDisplay(reservation.reservation_date);
                const resourceName = reservation.resource_type === 'tablets' ? 'Tablets' : 'Sala de Enlaces';
                
                const confirmMessage = `🔒 CANCELACIÓN ADMINISTRATIVA 🔒\n\n` +
                                      `¿Está seguro que desea cancelar esta reserva?\n\n` +
                                      `👤 Docente: ${reservation.user_name}\n` +
                                      `📅 Fecha: ${formattedDate}\n` +
                                      `⏰ Horario: ${reservation.time_slot}\n` +
                                      `💻 Recurso: ${resourceName}\n` +
                                      `📚 Asignatura: ${reservation.purpose}\n` +
                                      `🏫 Curso: ${reservation.course}\n` +
                                      `📊 Estado: ${attendanceStatus}\n` +
                                      `👨‍💼 Reservado por: ${reservation.reserved_by}\n\n` +
                                      `⚠️ Esta acción quedará registrada en el sistema como cancelación administrativa.`;
                
                if (!confirm(confirmMessage)) {
                    return;
                }

                console.log(`🔄 Administrador ${currentUser.name} cancelando reserva ${reservationId}`);
                
                showToast('Cancelando reserva...', 'info', 3000);
                
                await apiRequest('cancel_reservation', 'DELETE', { 
                    id: reservationId,
                    admin_name: currentUser.name
                });
                
                await loadSchedule();
                await loadUserLimits(); // NUEVO: Recargar límites después de cancelar
                
                showToast(`✅ Reserva cancelada exitosamente por administrador.\n\nDocente afectado: ${reservation.user_name}\nFecha: ${formattedDate}\nHorario: ${reservation.time_slot}`, 'success', 8000);
                
            } catch (error) {
                console.error('❌ Error al cancelar reserva (admin):', error);
                showToast('Error al cancelar reserva: ' + error.message, 'error');
                
                // Recargar para mostrar estado actual
                await loadSchedule();
            }
        }

        // ===== FUNCIONES DE ASISTENCIA MEJORADAS =====
        async function confirmAttendance(reservationId) {
            try {
                console.log(`🔄 Confirmando asistencia para reserva ${reservationId}`);
                
                const chileTime = getCurrentChileTime();
                console.log(`⏰ Confirmando asistencia a las ${chileTime} (Hora Chile)`);
                
                await apiRequest('update_attendance', 'PUT', {
                    id: reservationId,
                    attendance: 1
                });

                // Recargar solo los datos necesarios en lugar de toda la página
                await loadSchedule();
                await loadUserLimits();
                showToast(`Asistencia confirmada a las ${chileTime} (Hora Chile)`, 'success', 6000);
                
            } catch (error) {
                console.error('❌ Error al confirmar asistencia:', error);
                showToast('Error al confirmar asistencia: ' + error.message, 'error');
            }
        }

        async function markNoShow(reservationId) {
            if (!confirm('¿Está seguro que desea marcar como "No asistió"?')) {
                return;
            }

            try {
                console.log(`🔄 Marcando como no asistió para reserva ${reservationId}`);
                
                const chileTime = getCurrentChileTime();
                console.log(`⏰ Marcando no asistencia a las ${chileTime} (Hora Chile)`);
                
                await apiRequest('update_attendance', 'PUT', {
                    id: reservationId,
                    attendance: 0
                });

                await loadSchedule();
                await loadUserLimits();
                showToast(`Marcado como "No asistió" a las ${chileTime} (Hora Chile)`, 'success', 6000);
                
            } catch (error) {
                console.error('❌ Error al marcar como no asistió:', error);
                showToast('Error al marcar como no asistió: ' + error.message, 'error');
            }
        }

        

        // ===== SISTEMA DE TOAST NOTIFICATIONS CENTRALES =====
        function showToast(message, type = 'info', duration = 5000) {
            const toastContainer = document.getElementById('toastContainer');
            
            const icons = {
                success: 'fas fa-check-circle',
                error: 'fas fa-exclamation-triangle',
                warning: 'fas fa-exclamation-circle',
                info: 'fas fa-info-circle'
            };

            // Crear overlay para toasts críticos (errores y warnings importantes)
            let overlay = null;
            if (type === 'error' || (type === 'warning' && duration > 6000)) {
                overlay = document.createElement('div');
                overlay.className = 'toast-overlay';
                overlay.id = 'toast-overlay-' + Date.now();
                document.body.appendChild(overlay);
                
                setTimeout(() => overlay.classList.add('show'), 10);
            }

            // Crear elemento toast
            const toast = document.createElement('div');
            toast.className = `toast toast-${type}`;
            
            // ID único para el toast
            const toastId = 'toast-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
            toast.id = toastId;

            // Contenido del toast con mensaje centrado y más prominente
            toast.innerHTML = `
                <i class="${icons[type]} toast-icon"></i>
                <div class="toast-content">${message}</div>
                <button class="toast-close" onclick="closeToast('${toastId}', '${overlay?.id || ''}')">
                    <i class="fas fa-times"></i>
                </button>
                <div class="toast-progress"></div>
            `;

            // Agregar al contenedor
            toastContainer.appendChild(toast);

            // Mostrar toast con animación desde arriba
            setTimeout(() => {
                toast.classList.add('show');
            }, 10);

            // Configurar barra de progreso
            const progressBar = toast.querySelector('.toast-progress');
            if (type !== 'error') { // Los errores no se cierran automáticamente
                progressBar.style.width = '100%';
                progressBar.style.transitionDuration = duration + 'ms';
                
                setTimeout(() => {
                    progressBar.style.width = '0%';
                }, 50);

                // Auto-cerrar después del tiempo especificado
                setTimeout(() => {
                    closeToast(toastId, overlay?.id);
                }, duration);
            } else {
                // Para errores, mantener la barra completa sin animación
                progressBar.style.width = '100%';
                progressBar.style.transition = 'none';
            }

            // Añadir vibración en dispositivos móviles para alertas importantes
            if ((type === 'error' || type === 'warning') && navigator.vibrate) {
                navigator.vibrate([200, 100, 200]);
            }

            return toastId;
        }

        function closeToast(toastId, overlayId = '') {
            const toast = document.getElementById(toastId);
            const overlay = overlayId ? document.getElementById(overlayId) : null;
            
            if (toast) {
                toast.classList.remove('show');
                toast.classList.add('hide');
                
                setTimeout(() => {
                    if (toast.parentNode) {
                        toast.parentNode.removeChild(toast);
                    }
                }, 400);
            }

            if (overlay) {
                overlay.classList.remove('show');
                setTimeout(() => {
                    if (overlay.parentNode) {
                        overlay.parentNode.removeChild(overlay);
                    }
                }, 300);
            }
        }

        function clearAllToasts() {
            const toastContainer = document.getElementById('toastContainer');
            const toasts = toastContainer.querySelectorAll('.toast');
            
            toasts.forEach(toast => {
                closeToast(toast.id);
            });

            // Limpiar overlays
            const overlays = document.querySelectorAll('.toast-overlay');
            overlays.forEach(overlay => {
                if (overlay.parentNode) {
                    overlay.parentNode.removeChild(overlay);
                }
            });
        }

        // ===== FUNCIONES DE UTILIDAD Y API =====
        async function apiRequest(action, method = 'GET', data = null) {
            try {
                console.log(`🔄 API Request: ${action} (${method})`);
                
                const options = {
                    method: method,
                    headers: { 'Content-Type': 'application/json' }
                };

                if (data && method !== 'GET') {
                    options.body = JSON.stringify(data);
                }

                const url = method === 'GET' && data ? 
                    `${API_URL}?action=${action}&${new URLSearchParams(data).toString()}` : 
                    `${API_URL}?action=${action}`;

                const response = await fetch(url, options);
                const text = await response.text();
                
                let result;
                try {
                    result = JSON.parse(text);
                } catch (e) {
                    console.error('❌ Invalid JSON response:', text);
                    throw new Error('Respuesta inválida del servidor');
                }

                if (!response.ok) {
                    throw new Error(result.message || `Error HTTP ${response.status}`);
                }

                if (!result.success) {
                    throw new Error(result.message || 'Error en la operación');
                }

                console.log(`✅ API Success: ${action}`);
                return result;
            } catch (error) {
                console.error(`❌ API Error (${action}):`, error);
                throw error;
            }
        }

        // ===== FUNCIONES PARA CAMBIO DE CONTRASEÑA =====
        function openChangePasswordModal() {
            if (!currentUser || !currentUser.username) {
                showToast('Error de sesión: No se pudo identificar el usuario. Por favor, cierre sesión e inicie sesión nuevamente.', 'error');
                setTimeout(() => logout(), 3000);
                return;
            }

            console.log('🔑 Abriendo modal de cambio de contraseña para:', currentUser.username);

            document.getElementById('currentPassword').value = '';
            document.getElementById('newPassword').value = '';
            document.getElementById('confirmPassword').value = '';
            
            resetPasswordStrengthIndicator();
            resetPasswordMatchIndicator();
            resetPasswordRequirements();
            
            document.getElementById('changePasswordBtn').disabled = true;
            document.getElementById('changePasswordModal').classList.add('show');
            
            setTimeout(() => {
                document.getElementById('currentPassword').focus();
            }, 100);
        }

        function closeChangePasswordModal() {
            document.getElementById('changePasswordModal').classList.remove('show');
        }

        function togglePasswordVisibility(inputId) {
            const input = document.getElementById(inputId);
            const button = input.nextElementSibling;
            const icon = button.querySelector('i');
            
            if (input.type === 'password') {
                input.type = 'text';
                icon.className = 'fas fa-eye-slash';
            } else {
                input.type = 'password';
                icon.className = 'fas fa-eye';
            }
        }

        function checkPasswordStrength() {
            const password = document.getElementById('newPassword').value;
            const strengthFill = document.getElementById('passwordStrengthFill');
            const requirements = {
                length: password.length >= 4,
                letters: /[a-zA-Z]/.test(password),
                numbers: /\d/.test(password),
                special: /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)
            };

            updatePasswordRequirement('req-length', requirements.length);
            updatePasswordRequirement('req-letters', requirements.letters);
            updatePasswordRequirement('req-numbers', requirements.numbers);
            updatePasswordRequirement('req-special', requirements.special);

            let strength = 0;
            if (requirements.length) strength++;
            if (requirements.letters) strength++;
            if (requirements.numbers) strength++;
            if (requirements.special) strength++;

            strengthFill.className = 'password-strength-fill';
            if (strength === 1) {
                strengthFill.classList.add('password-strength-weak');
            } else if (strength === 2) {
                strengthFill.classList.add('password-strength-fair');
            } else if (strength === 3) {
                strengthFill.classList.add('password-strength-good');
            } else if (strength === 4) {
                strengthFill.classList.add('password-strength-strong');
            }

            checkPasswordMatch();
            
            return requirements.length && requirements.letters;
        }

        function updatePasswordRequirement(elementId, met) {
            const element = document.getElementById(elementId);
            const icon = element.querySelector('i');
            
            if (met) {
                element.className = 'password-requirement met';
                icon.className = 'fas fa-check-circle';
            } else {
                element.className = 'password-requirement unmet';
                icon.className = 'fas fa-times-circle';
            }
        }

        function checkPasswordMatch() {
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            const indicator = document.getElementById('passwordMatchIndicator');
            const changeBtn = document.getElementById('changePasswordBtn');

            if (confirmPassword === '') {
                indicator.innerHTML = '';
                changeBtn.disabled = true;
                return;
            }

            if (newPassword === confirmPassword) {
                indicator.innerHTML = '<i class="fas fa-check-circle" style="color: #4caf50;"></i> <span style="color: #4caf50;">Las contraseñas coinciden</span>';
                
                const meetsRequirements = newPassword.length >= 4 && /[a-zA-Z]/.test(newPassword);
                changeBtn.disabled = !meetsRequirements;
            } else {
                indicator.innerHTML = '<i class="fas fa-times-circle" style="color: #f44336;"></i> <span style="color: #f44336;">Las contraseñas no coinciden</span>';
                changeBtn.disabled = true;
            }
        }

        function resetPasswordStrengthIndicator() {
            const strengthFill = document.getElementById('passwordStrengthFill');
            strengthFill.className = 'password-strength-fill';
        }

        function resetPasswordMatchIndicator() {
            document.getElementById('passwordMatchIndicator').innerHTML = '';
        }

        function resetPasswordRequirements() {
            ['req-length', 'req-letters', 'req-numbers', 'req-special'].forEach(id => {
                updatePasswordRequirement(id, false);
            });
        }

        async function changePassword() {
            const currentPassword = document.getElementById('currentPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            const changeBtn = document.getElementById('changePasswordBtn');

            if (!currentPassword) {
                showToast('Por favor ingrese su contraseña actual', 'warning');
                return;
            }

            if (!newPassword) {
                showToast('Por favor ingrese una nueva contraseña', 'warning');
                return;
            }

            if (newPassword !== confirmPassword) {
                showToast('Las contraseñas no coinciden', 'warning');
                return;
            }

            if (newPassword.length < 4) {
                showToast('La nueva contraseña debe tener al menos 4 caracteres', 'warning');
                return;
            }

            if (currentPassword === newPassword) {
                showToast('La nueva contraseña debe ser diferente a la actual', 'warning');
                return;
            }

            changeBtn.disabled = true;
            changeBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Cambiando contraseña...';

            try {
                if (!currentUser || !currentUser.username) {
                    showToast('Error: No se pudo identificar el usuario. Por favor, cierre sesión e inicie sesión nuevamente.', 'error');
                    setTimeout(() => logout(), 3000);
                    return;
                }

                console.log('🔑 Cambiando contraseña para usuario:', currentUser.username);

                const response = await apiRequest('change_password', 'POST', {
                    username: currentUser.username,
                    current_password: currentPassword,
                    new_password: newPassword
                });

                const modal = document.getElementById('changePasswordModal');
                const modalContent = modal.querySelector('.modal');
                modalContent.classList.add('password-success-animation');

                showToast('¡Contraseña cambiada exitosamente! 🎉', 'success', 4000);

                setTimeout(() => {
                    closeChangePasswordModal();
                    modalContent.classList.remove('password-success-animation');
                }, 2000);

            } catch (error) {
                console.error('❌ Error al cambiar contraseña:', error);
                
                let errorMessage = 'Error al cambiar contraseña';
                if (error.message.includes('contraseña actual') || error.message.includes('incorrecta')) {
                    errorMessage = 'La contraseña actual es incorrecta';
                } else if (error.message.includes('nueva contraseña')) {
                    errorMessage = 'La nueva contraseña no cumple con los requisitos';
                } else if (error.message.includes('identificar') || error.message.includes('usuario')) {
                    errorMessage = 'Error de sesión. Por favor, cierre sesión e inicie sesión nuevamente.';
                    setTimeout(() => logout(), 3000);
                } else {
                    errorMessage = error.message;
                }
                
                showToast(errorMessage, 'error');
                
                if (errorMessage.includes('contraseña actual')) {
                    document.getElementById('currentPassword').value = '';
                    document.getElementById('currentPassword').focus();
                }

            } finally {
                changeBtn.disabled = false;
                changeBtn.innerHTML = '<i class="fas fa-key"></i> Cambiar Contraseña';
                checkPasswordMatch();
            }
        }

        // ===== FUNCIONES BÁSICAS DEL SISTEMA =====
        async function login() {
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value;
            const loginBtn = document.getElementById('loginBtn');

            if (!username || !password) {
                showAlert('Por favor ingrese usuario y contraseña', 'warning', 'loginAlerts');
                return;
            }

            loginBtn.disabled = true;
            loginBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Ingresando...';

            try {
                const response = await apiRequest('login', 'POST', { username, password });
                
                currentUser = response.data.user;
                
                console.log('👤 Usuario logueado:', currentUser);
                if (!currentUser.username) {
                    console.warn('⚠️ El username no está en la respuesta del login');
                }
                
                document.getElementById('loginSection').style.display = 'none';
                document.getElementById('mainSection').classList.add('active');
                
                document.getElementById('currentUser').textContent = currentUser.name;
                const roleElement = document.getElementById('userRole');
                const superAdminBadge = document.getElementById('superAdminBadge');
                
                if (currentUser.role === 'admin') {
                    if (isSuperAdminClaudio()) {
                        roleElement.textContent = 'Súper Administrador';
                        roleElement.className = 'status-badge admin';
                        superAdminBadge.style.display = 'inline-block';
                        superAdminBadge.innerHTML = '<i class="fas fa-crown"></i> SÚPER ADMIN';
                    } else {
                        roleElement.textContent = 'Administrador';
                        roleElement.className = 'status-badge admin';
                        superAdminBadge.style.display = 'inline-block';
                        superAdminBadge.className = 'admin-with-limits-badge';
                        superAdminBadge.innerHTML = '<i class="fas fa-shield-alt"></i> ADMIN CON LÍMITES';
                    }
                } else {
                    roleElement.textContent = 'Usuario';
                    roleElement.className = 'status-badge user';
                    superAdminBadge.style.display = 'none';
                }

                if (currentUser.role === 'admin') {
                    document.getElementById('adminPanel').classList.remove('hidden');
                    setCurrentMonth();
                    setupAdminInterface();
                    
                    const userManagementContent = document.getElementById('userManagementContent');
                    userManagementContent.innerHTML = generateUserManagementContent();
                    
                    if (hasUserManagementAccess()) {
                        await loadUsers();
                    }
                }

                await initializeApp();
                
                let welcomeMessage = `¡Bienvenido ${currentUser.name}!`;
                if (isSuperAdminClaudio()) {
                    welcomeMessage += ' 👑 (Súper Administrador - Sin límites)';
                } else if (currentUser.role === 'admin') {
                    welcomeMessage += ' 🛡️ (Administrador con límites)';
                }
                
                showAlert(welcomeMessage, 'success');
                
            } catch (error) {
                showAlert(error.message, 'error', 'loginAlerts');
                document.getElementById('password').value = '';
            } finally {
                loginBtn.disabled = false;
                loginBtn.innerHTML = '<i class="fas fa-sign-in-alt"></i> Ingresar';
            }
        }

        function logout() {
            currentUser = null;
            selectedTimeSlots = [];
            allUsers = [];
            filteredUsers = [];
            currentSearchTerm = '';
            currentRoleFilter = 'all';
            userLimits = null; // NUEVO: Limpiar límites
            limitsLoaded = false; // NUEVO: Resetear estado de límites
            
            document.getElementById('loginSection').style.display = 'block';
            document.getElementById('mainSection').classList.remove('active');
            document.getElementById('adminPanel').classList.add('hidden');
            document.getElementById('username').value = '';
            document.getElementById('password').value = '';
            clearAllToasts();
            updateSelectedTimeIndicator();
            hideUserLimitsPanel(); // NUEVO: Ocultar panel de límites
            
            if (document.getElementById('searchUsers')) {
                document.getElementById('searchUsers').value = '';
            }
            
            const teacherNameElement = document.getElementById('currentTeacherName');
            if (teacherNameElement) {
                teacherNameElement.textContent = '';
            }
            
            showAlert('Sesión cerrada correctamente', 'success', 'loginAlerts');
        }

        function showAlert(message, type = 'info', container = null) {
            if (container === 'loginAlerts') {
                const alertContainer = document.getElementById(container);
                const icons = {
                    success: 'fas fa-check-circle',
                    error: 'fas fa-exclamation-triangle',
                    warning: 'fas fa-exclamation-circle',
                    info: 'fas fa-info-circle'
                };
                
                const alert = document.createElement('div');
                alert.className = `alert alert-${type}`;
                alert.innerHTML = `<i class="${icons[type]}"></i> ${message}`;
                
                alertContainer.innerHTML = '';
                alertContainer.appendChild(alert);
                
                setTimeout(() => {
                    if (alert.parentNode) {
                        alert.parentNode.removeChild(alert);
                    }
                }, type === 'error' ? 7000 : 5000);
            } else {
                const duration = type === 'error' ? 8000 : type === 'warning' ? 6000 : 5000;
                showToast(message, type, duration);
            }
        }

        function clearAlerts(container = 'alerts') {
            if (container === 'alerts') {
                clearAllToasts();
            } else {
                document.getElementById(container).innerHTML = '';
            }
        }

        function setCurrentMonth() {
            const now = new Date();
            const monthString = now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0');
            document.getElementById('reportMonth').value = monthString;
        }

      
        function setTodayDate() {
            const dateInput = document.getElementById('date');
            
            // Obtener fecha actual en zona horaria de Chile
            const now = new Date();
            const chileTimeString = now.toLocaleString("en-US", {timeZone: "America/Santiago"});
            const chileTime = new Date(chileTimeString);
            
            console.log('🕐 Configurando fecha de hoy');
            console.log('📅 Fecha actual (Chile):', chileTime.toLocaleDateString('es-CL'));
            console.log('📅 Día de la semana:', chileTime.getDay(), getDayName(chileTime.getDay()));
            
            // Verificar si es después de las 22:00 hrs (10:00 PM)
            const currentHour = chileTime.getHours();
            const isAfter10PM = currentHour >= 22;
            
            let targetDate;
            
            if (isAfter10PM) {
                console.log('🌙 Es después de las 22:00 hrs, mostrando horarios para mañana');
                // Si es después de las 22:00, mostrar el día siguiente
                targetDate = new Date(chileTime);
                targetDate.setDate(targetDate.getDate() + 1);
            } else {
                console.log('☀️ Es antes de las 22:00 hrs, mostrando horarios para hoy');
                // Si es antes de las 22:00, mostrar hoy
                targetDate = new Date(chileTime);
            }
            
            // Asegurarnos de que sea un día laborable (lunes a viernes)
            const finalDate = getNextWorkday(targetDate);
            
            // Formatear fecha CORRECTAMENTE para el input (YYYY-MM-DD)
            const year = finalDate.getFullYear();
            const month = String(finalDate.getMonth() + 1).padStart(2, '0');
            const day = String(finalDate.getDate()).padStart(2, '0');
            const finalDateString = `${year}-${month}-${day}`;
            
            dateInput.value = finalDateString;
            
            console.log('📅 Fecha configurada:', {
                horaActual: chileTime.toLocaleString('es-CL'),
                despuésDe22: isAfter10PM,
                fechaObjetivo: targetDate.toLocaleDateString('es-CL'),
                fechaFinal: finalDate.toLocaleDateString('es-CL'),
                fechaInput: finalDateString,
                díaSemana: finalDate.getDay()
            });
            
            // Configurar validación completa
            setupDateValidation(dateInput);
            
            updateScheduleTitle();
        }

       
       function getNextWorkday(date) {
            const newDate = new Date(date);
            let dayOfWeek = newDate.getDay();
            
            console.log('📅 Verificando día laborable:', dayOfWeek, getDayName(dayOfWeek));
            
            // Si es sábado (6) o domingo (0), avanzamos al próximo lunes
            if (dayOfWeek === 6) { // Sábado
                console.log('🎯 Es sábado, avanzando a lunes');
                newDate.setDate(newDate.getDate() + 2); // +2 días = Lunes
            } else if (dayOfWeek === 0) { // Domingo
                console.log('🎯 Es domingo, avanzando a lunes');
                newDate.setDate(newDate.getDate() + 1); // +1 día = Lunes
            } else {
                console.log('✅ Es día hábil (lunes a viernes), manteniendo fecha');
                // No hacer nada, ya es día hábil
            }
            
            console.log('✅ Fecha final para el input:', newDate.toLocaleDateString('es-CL'));
            return newDate;
        }

        // ===== FUNCIÓN PARA NOMBRES DE DÍAS =====
        function getDayName(dayIndex) {
            const days = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'];
            return days[dayIndex];
        }
        
      

        function isWeekend(dateString) {
            const [year, month, day] = dateString.split('-');
            const date = new Date(year, month - 1, day);
            const dayOfWeek = date.getDay();
            return dayOfWeek === 0 || dayOfWeek === 6; // 0 = Domingo, 6 = Sábado
        }

        function isPastDate(dateString) {
            const currentDate = new Date();
            currentDate.setHours(0, 0, 0, 0);
            
            const [year, month, day] = dateString.split('-');
            const selectedDate = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
            selectedDate.setHours(0, 0, 0, 0);
            
            return selectedDate.getTime() < currentDate.getTime();
        }

        function validateDateForUser(dateString) {
            if (!currentUser) return false;
            
            // Si es administrador, puede agendar en cualquier fecha (excepto fines de semana)
            if (currentUser.role === 'admin') {
                return !isWeekend(dateString);
            }
            
            // Si es usuario normal, solo puede agendar desde hoy en adelante y no fines de semana
            return !isWeekend(dateString) && !isPastDate(dateString);
        }

        // ===== FUNCIÓN MEJORADA PARA VALIDACIÓN COMPLETA DEL INPUT DE FECHA =====
        function setupDateValidation(dateInput) {
            // Evento principal de cambio de fecha
            dateInput.addEventListener('change', function() {
                const selectedDate = this.value;
                
                if (!selectedDate) return;

                // Validar fin de semana
                if (isWeekend(selectedDate)) {
                    const [year, month, day] = selectedDate.split('-');
                    const date = new Date(year, month - 1, day);
                    const dayName = date.toLocaleDateString('es-ES', { weekday: 'long' });
                    const capitalizedDay = dayName.charAt(0).toUpperCase() + dayName.slice(1);
                    
                    showToast(`No se pueden agendar reservas los ${capitalizedDay}s. se seleciono el día habíl siguiente.`, 'warning', 6000);
                    
                    // Encontrar el próximo día laborable
                    const nextWorkday = getNextWorkday(date);
                    const nextWorkdayString = nextWorkday.toISOString().split('T')[0];
                    
                    // Establecer el próximo día laborable
                    this.value = nextWorkdayString;
                    handleDateChange();
                    return;
                }

                // Validar fechas pasadas SOLO para usuarios normales
                if (currentUser && currentUser.role !== 'admin' && isPastDate(selectedDate)) {
                    showToast('Los usuarios solo pueden agendar reservas para fechas futuras. Solo los administradores pueden agendar en fechas pasadas.', 'error', 8000);
                    
                    // Establecer fecha de hoy o próximo día laborable
                    const currentDate = new Date();
                    const nextWorkday = getNextWorkday(currentDate);
                    const nextWorkdayString = nextWorkday.toISOString().split('T')[0];
                    this.value = nextWorkdayString;
                    handleDateChange();
                    return;
                }

                // Si llegamos aquí, la fecha es válida
                handleDateChange();
            });

            // Función auxiliar para manejar cambios válidos de fecha
            function handleDateChange() {
                selectedTimeSlots = [];
                updateSelectedTimeIndicator();
                updateReserveButtonWithLimits(); // MODIFICADO: Usar nueva función con límites
                updateScheduleTitle();
                loadSchedule();
                loadUserLimits(); // NUEVO: Cargar límites cuando cambia la fecha
            }

            // Evento adicional para validar entrada manual
            dateInput.addEventListener('blur', function() {
                if (this.value) {
                    // Disparar evento change para validar
                    this.dispatchEvent(new Event('change'));
                }
            });
        }

        // ===== CONFIGURACIÓN DE RESTRICCIONES SEGÚN ROL =====
        function setupUserRoleInterface() {
            if (!currentUser) return;
            
            const dateInput = document.getElementById('date');
            
            if (currentUser.role === 'admin') {
                // Para administradores: NO establecer fecha mínima (pueden seleccionar fechas pasadas)
                dateInput.removeAttribute('min');
                
                // Agregar indicador visual para administradores
                const formGroup = dateInput.closest('.form-group');
                if (formGroup) {
                    // Remover nota anterior si existe
                    const existingNote = formGroup.querySelector('.date-restriction-note, .admin-date-note');
                    if (existingNote) {
                        existingNote.remove();
                    }
                    
                    const adminNote = document.createElement('div');
                    adminNote.className = 'admin-date-note';
                    adminNote.innerHTML = '<i class="fas fa-crown"></i> Como administrador, puedes agendar en fechas pasadas (solo para auditorías o correcciones)';
                    formGroup.appendChild(adminNote);
                }
                
                console.log('🔓 Interfaz configurada para ADMINISTRADOR - Sin restricciones de fecha');
                
            } else {
                // Para usuarios normales: establecer fecha mínima como hoy
                const currentDate = new Date().toISOString().split('T')[0];
                dateInput.min = currentDate;
                
                // Agregar indicador visual para usuarios normales
                const formGroup = dateInput.closest('.form-group');
                if (formGroup) {
                    // Remover nota anterior si existe
                    const existingNote = formGroup.querySelector('.date-restriction-note, .admin-date-note');
                    if (existingNote) {
                        existingNote.remove();
                    }
                    
                    const userNote = document.createElement('div');
                    userNote.className = 'date-restriction-note';
                    userNote.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Solo puedes agendar desde hoy en adelante (fechas futuras)';
                    formGroup.appendChild(userNote);
                }
                
                console.log('👤 Interfaz configurada para USUARIO NORMAL - Con restricciones de fecha');
            }
        }

        // ===== INICIALIZACIÓN PRINCIPAL =====
        async function initializeApp() {
            try {
                console.log('🚀 Iniciando aplicación...');
                
                await loadCourses();
                console.log('✅ Cursos cargados');
                
                await loadTimeSlots();
                console.log('✅ Horarios cargados:', timeSlots.length, 'slots');
                
                setTodayDate();
                console.log('✅ Fecha configurada');
                
                updateTeacherName();
                console.log('✅ Nombre del docente actualizado');

                setupUserRoleInterface();
                console.log('✅ Interfaz configurada según rol');
                
                await loadSchedule();
                console.log('✅ Horarios del día cargados');

                // NUEVO: Cargar límites del usuario
                await loadUserLimits();
                console.log('✅ Límites del usuario cargados');
                
                // CONFIGURAR EVENT DELEGATION INICIAL
                setupEventDelegation();
                console.log('✅ Event delegation configurado');
                
                // FUNCIÓN MEJORADA PARA CARGAR LOGO CON ALTA CALIDAD
                loadLogo().catch(error => {
                    console.warn('⚠️ Error al cargar logo:', error);
                });
                
                console.log('✅ Aplicación inicializada correctamente con sistema de límites para todos excepto Claudio');
                
            } catch (error) {
                console.error('❌ Error al inicializar la aplicación:', error);
                showAlert('Error al inicializar la aplicación: ' + error.message, 'error');
            }
        }

        function updateTeacherName() {
            if (currentUser && currentUser.name) {
                const teacherNameElement = document.getElementById('currentTeacherName');
                if (teacherNameElement) {
                    teacherNameElement.textContent = currentUser.name;
                    console.log('✅ Nombre del docente actualizado:', currentUser.name);
                } else {
                    console.warn('⚠️ Elemento currentTeacherName no encontrado');
                }
            }
        }

        async function loadCourses() {
            try {
                console.log('🔄 Cargando cursos disponibles...');
                const response = await apiRequest('get_courses');
                courses = response.data || [];
                
                const courseSelect = document.getElementById('course');
                courseSelect.innerHTML = '<option value="">Seleccione un curso</option>';
                
                if (courses.length === 0) {
                    console.warn('⚠️ No se encontraron cursos configurados');
                    courseSelect.innerHTML = '<option value="">No hay cursos configurados</option>';
                    return;
                }
                
                courses.forEach(course => {
                    const option = document.createElement('option');
                    option.value = course;
                    option.textContent = course;
                    courseSelect.appendChild(option);
                });
                
                console.log('✅ Cursos cargados exitosamente:', courses.length, 'cursos');
                
            } catch (error) {
                console.error('❌ Error al cargar cursos:', error);
                const courseSelect = document.getElementById('course');
                courseSelect.innerHTML = '<option value="">Error al cargar cursos</option>';
                throw error;
            }
        }

        async function loadTimeSlots() {
            try {
                console.log('🔄 Cargando horarios disponibles...');
                const selectedDate = document.getElementById('date')?.value || '';
                const params = selectedDate ? { date: selectedDate } : {};
                const response = await apiRequest('get_time_slots', 'GET', params);
                timeSlots = response.data || [];
                
                if (timeSlots.length === 0) {
                    console.warn('⚠️ No se encontraron horarios configurados en la base de datos');
                    throw new Error('No hay horarios configurados en el sistema. Contacte al administrador.');
                }
                
                console.log('✅ Horarios cargados exitosamente:', timeSlots);
                return timeSlots;
                
            } catch (error) {
                console.error('❌ Error al cargar horarios:', error);
                timeSlots = [];
                throw error;
            }
        }

        async function loadSchedule() {
            const scheduleGrid = document.getElementById('scheduleGrid');
            const selectedDate = document.getElementById('date').value || new Date().toISOString().split('T')[0];
            
            console.log('🔄 Cargando horarios para fecha:', selectedDate, 'recurso:', currentResource);
            
            updateScheduleTitle();
            
            if (isWeekend(selectedDate)) {
                const [year, month, day] = selectedDate.split('-');
                const date = new Date(year, month - 1, day);
                const dayName = date.getDay() === 0 ? 'Domingo' : 'Sábado';
                
                scheduleGrid.innerHTML = `
                    <div class="alert alert-warning" style="text-align: center; padding: 40px;">
                        <i class="fas fa-calendar-times" style="font-size: 3rem; color: #ff9800; margin-bottom: 15px; display: block;"></i>
                        <h3 style="color: #e65100; margin-bottom: 15px;">Fin de Semana</h3>
                        <p style="color: #666; margin-bottom: 20px;">
                            ${dayName} - No hay clases los fines de semana.<br>
                            Las reservas solo están disponibles de lunes a viernes.
                        </p>
                    </div>`;
                return;
            }
            
            scheduleGrid.innerHTML = '<div class="loading"><i class="fas fa-spinner fa-spin"></i> Cargando horarios...</div>';

            try {
                await loadTimeSlots();
                
                const response = await apiRequest('get_reservations', 'GET', { 
                    date: selectedDate,
                    resource_type: currentResource 
                });
                
                reservations = response.data || [];
                console.log('✅ Reservas cargadas:', reservations.length, 'para', currentResource);
                
                renderSchedule();
                
            } catch (error) {
                console.error('❌ Error al cargar horarios:', error);
                scheduleGrid.innerHTML = `
                    <div class="alert alert-error" style="text-align: center; padding: 40px;">
                        <i class="fas fa-exclamation-triangle" style="font-size: 3rem; color: #f44336; margin-bottom: 15px; display: block;"></i>
                        <h3 style="color: #c62828; margin-bottom: 15px;">Error al cargar horarios</h3>
                        <p style="color: #666; margin-bottom: 20px;">
                            ${error.message}<br>
                            Por favor intenta recargar o contacta al administrador.
                        </p>
                        <button class="btn btn-info" onclick="loadSchedule()" style="margin-top: 10px;">
                            <i class="fas fa-refresh"></i> Reintentar
                        </button>
                    </div>`;
            }
        }

        function renderSchedule() {
            const scheduleGrid = document.getElementById('scheduleGrid');
            scheduleGrid.innerHTML = '';

            console.log('🔄 Renderizando horarios. TimeSlots disponibles:', timeSlots.length);

            if (timeSlots.length === 0) {
                scheduleGrid.innerHTML = `
                    <div class="alert alert-warning" style="text-align: center; padding: 40px;">
                        <i class="fas fa-clock" style="font-size: 3rem; color: #ff9800; margin-bottom: 15px; display: block;"></i>
                        <h3 style="color: #e65100; margin-bottom: 15px;">No hay horarios configurados</h3>
                        <p style="color: #666; margin-bottom: 20px;">
                            No se han encontrado horarios disponibles en el sistema.<br>
                            Por favor contacte al administrador para configurar los horarios de clase.
                        </p>
                        <button class="btn btn-info" onclick="loadTimeSlots().then(() => loadSchedule())" style="margin-top: 10px;">
                            <i class="fas fa-refresh"></i> Recargar horarios
                        </button>
                    </div>`;
                return;
            }

            const reservationMap = {};
            reservations.forEach(reservation => {
                if (reservation.resource_type === currentResource) {
                    reservationMap[reservation.time_slot] = reservation;
                }
            });

            timeSlots.forEach(slot => {
                const reservation = reservationMap[slot];
                const slotElement = createTimeSlotElement(slot, reservation);
                scheduleGrid.appendChild(slotElement);
            });

            // CONFIGURAR EVENT DELEGATION DESPUÉS DE RENDERIZAR
            setupEventDelegation();
            
            console.log('✅ Horarios renderizados exitosamente con sistema de límites');
        }

        // ✅ FUNCIÓN SELECTTIMESLOT SIMPLIFICADA (ya no necesita event parameter)
        function selectTimeSlot(timeSlot) {
            // Verificar si el horario está realmente disponible
            const isReserved = reservations.some(reservation => 
                reservation.resource_type === currentResource && 
                reservation.time_slot === timeSlot
            );
            
            if (isReserved) {
                showToast(`El horario ${timeSlot} ya no está disponible. Los horarios se han actualizado.`, 'warning');
                loadSchedule(); // Recargar para mostrar estado actual
                return;
            }
            
            // Verificar si el horario ya está seleccionado
            const index = selectedTimeSlots.indexOf(timeSlot);
            
            if (index > -1) {
                // Si ya está seleccionado, lo removemos
                selectedTimeSlots.splice(index, 1);
                showToast(`Horario ${timeSlot} deseleccionado`, 'info', 3000);
            } else {
                // Si no está seleccionado, verificamos si podemos agregarlo
                if (selectedTimeSlots.length >= 2) {
                    showToast('Solo puedes seleccionar máximo 2 horarios. Deselecciona uno primero haciendo clic en él.', 'warning');
                    return;
                }
                
                // Verificar límites para todos excepto el súper administrador Claudio
                if (currentUser && userLimits && userLimits.is_super_admin !== true) {
                    const currentResourceLimits = userLimits.limits[currentResource];
                    if (selectedTimeSlots.length + 1 > currentResourceLimits.remaining) {
                        const resourceName = currentResource === 'tablets' ? 'Tablets' : 'Sala de Enlaces';
                        const roleText = currentUser.role === 'admin' ? ' (Administrador con límites)' : '';
                        showToast(`Solo tienes ${currentResourceLimits.remaining} cupo${currentResourceLimits.remaining === 1 ? '' : 's'} restante${currentResourceLimits.remaining === 1 ? '' : 's'} para ${resourceName} este mes${roleText}.`, 'warning', 6000);
                        return;
                    }
                }
                
                // Agregamos el nuevo horario
                selectedTimeSlots.push(timeSlot);
                showToast(`Horario ${timeSlot} seleccionado (${selectedTimeSlots.length}/2)`, 'success', 3000);
            }
            
            updateSelectedTimeIndicator();
            updateReserveButtonWithLimits();
            renderSchedule(); // Esto ahora preservará los event listeners
        }



        function updateSelectedTimeIndicator() {
            const indicator = document.getElementById('selectedTimeIndicator');
            const resourceIcon = currentResource === 'tablets' ? '📱' : '🖥️';
            const resourceName = currentResource === 'tablets' ? 'Tablets' : 'Sala de Enlaces';
            
            if (selectedTimeSlots.length > 0) {
                indicator.className = 'selected-time-indicator';
                
                const slotsText = selectedTimeSlots.join(' y ');
                const countText = selectedTimeSlots.length === 1 ? '1 horario' : '2 horarios';
                
                indicator.innerHTML = `
                    <i class="fas fa-check-circle" style="color: #4caf50;"></i> 
                    <strong>${countText} seleccionado${selectedTimeSlots.length > 1 ? 's' : ''}:</strong> ${slotsText} - ${resourceIcon} ${resourceName}
                    <br>
                    <small style="color: #666; margin-top: 5px; display: block;">
                        ${selectedTimeSlots.length < 2 ? 'Puedes seleccionar 1 horario más' : 'Máximo de 2 horarios alcanzado'}
                    </small>
                    <button onclick="clearSelectedTime()" style="margin-left: 15px; background: none; border: 1px solid #ff6b6b; color: #ff6b6b; padding: 5px 10px; border-radius: 5px; cursor: pointer;">
                        <i class="fas fa-times"></i> Limpiar selección
                    </button>
                `;
            } else {
                indicator.className = 'selected-time-indicator empty';
                indicator.innerHTML = '<i class="fas fa-clock"></i> Selecciona hasta 2 horarios haciendo clic en los disponibles abajo';
            }
        }

        function clearSelectedTime() {
            selectedTimeSlots = [];
            updateSelectedTimeIndicator();
            updateReserveButtonWithLimits(); // MODIFICADO: Usar nueva función con límites
            renderSchedule();
            showToast('Selección de horarios limpiada', 'info', 3000);
        }

        // FUNCIÓN UPDATERESERVEBUTTON REEMPLAZADA POR updateReserveButtonWithLimits (ya definida arriba)

        // ===== FUNCIÓN PARA HACER RESERVAS CON VALIDACIÓN DE LÍMITES =====
        async function makeReservation() {
            const teacherName = currentUser.name;
            const course = document.getElementById('course').value;
            const date = document.getElementById('date').value;
            const subject = document.getElementById('subject').value.trim();
            const reserveBtn = document.getElementById('reserveBtn');

            // Validaciones básicas
            if (!course) {
                showToast('Por favor seleccione un curso', 'warning');
                return;
            }
            if (!date) {
                showToast('Por favor seleccione una fecha', 'warning');
                return;
            }
            if (selectedTimeSlots.length === 0) {
                showToast('Por favor seleccione al menos un horario haciendo clic en uno disponible', 'warning');
                return;
            }
            if (!subject) {
                showToast('Por favor ingrese la asignatura', 'warning');
                return;
            }

            // NUEVA VALIDACIÓN: Verificar límites ANTES de continuar
            if (!checkLimitsBeforeReservation()) {
                return; // La función ya muestra el mensaje de error
            }

            // VALIDACIÓN CRÍTICA: Verificar que la fecha sea válida para el usuario
            if (!validateDateForUser(date)) {
                if (currentUser.role !== 'admin') {
                    if (isWeekend(date)) {
                        showToast('No se pueden agendar reservas los fines de semana. Solo de lunes a viernes.', 'error', 8000);
                    } else if (isPastDate(date)) {
                        showToast('Los usuarios solo pueden agendar reservas para fechas futuras. Si necesitas agendar en una fecha pasada, contacta a un administrador.', 'error', 10000);
                    }
                    return;
                }
            }

            // Validación de fin de semana (aplica para todos los usuarios)
            if (isWeekend(date)) {
                const [year, month, day] = date.split('-');
                const dateObj = new Date(year, month - 1, day);
                const dayName = dateObj.toLocaleDateString('es-ES', { weekday: 'long' });
                const capitalizedDay = dayName.charAt(0).toUpperCase() + dayName.slice(1);
                
                showToast(`No se pueden agendar reservas los ${capitalizedDay}s. El colegio solo tiene clases de lunes a viernes.`, 'error', 8000);
                return;
            }

            // Confirmación especial para administradores en fechas pasadas
            if (currentUser.role === 'admin' && isPastDate(date)) {
                const [year, month, day] = date.split('-');
                const selectedDate = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
                
                const confirmPastDate = confirm(
                    `⚠️ ATENCIÓN ADMINISTRADOR ⚠️\n\n` +
                    `Está intentando agendar una reserva para una fecha pasada:\n` +
                    `${selectedDate.toLocaleDateString('es-ES', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}\n\n` +
                    `Esta acción quedará registrada en el sistema para auditoría.\n\n` +
                    `¿Confirma que desea proceder con esta reserva en fecha pasada?`
                );
                
                if (!confirmPastDate) {
                    showToast('Reserva cancelada por el administrador', 'info');
                    return;
                }
                
                console.warn('🔒 ADMIN PAST DATE RESERVATION:', {
                    admin: currentUser.name,
                    date: date,
                    teacher: teacherName,
                    course: course,
                    timeSlots: selectedTimeSlots,
                    timestamp: new Date().toISOString()
                });
                
                showToast('⚠️ Procediendo con reserva en fecha pasada como administrador', 'warning', 4000);
            }

            reserveBtn.disabled = true;
            reserveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Procesando reservas...';

            // Verificar disponibilidad antes de hacer las reservas
            try {
                // Recargar horarios para verificar disponibilidad actual
                await loadSchedule();
                
                // Verificar que todos los horarios seleccionados siguen disponibles
                const unavailableSlots = [];
                selectedTimeSlots.forEach(timeSlot => {
                    const isReserved = reservations.some(reservation => 
                        reservation.resource_type === currentResource && 
                        reservation.time_slot === timeSlot
                    );
                    if (isReserved) {
                        unavailableSlots.push(timeSlot);
                    }
                });

                if (unavailableSlots.length > 0) {
                    const slotsText = unavailableSlots.join(', ');
                    showToast(`Los siguientes horarios ya no están disponibles: ${slotsText}. Por favor, actualiza tu selección.`, 'warning');
                    
                    // Remover horarios no disponibles de la selección
                    selectedTimeSlots = selectedTimeSlots.filter(slot => !unavailableSlots.includes(slot));
                    updateSelectedTimeIndicator();
                    updateReserveButtonWithLimits();
                    renderSchedule();
                    return;
                }

                // Hacer las reservas secuencialmente (una por una) para evitar conflictos
                const results = [];
                const errors = [];

                for (const timeSlot of selectedTimeSlots) {
                    try {
                        reserveBtn.innerHTML = `<i class="fas fa-spinner fa-spin"></i> Reservando ${timeSlot}...`;
                        
                        console.log('🔄 Enviando reserva:', {
                            user_name: teacherName,
                            course: course,
                            date: date,
                            time_slot: timeSlot,
                            purpose: subject,
                            resource_type: currentResource,
                            reserved_by: currentUser.name,
                            user_role: currentUser.role
                        });
                        
                        const result = await apiRequest('make_reservation', 'POST', {
                            user_name: teacherName,
                            course: course,
                            date: date,
                            time_slot: timeSlot,
                            purpose: subject,
                            resource_type: currentResource,
                            reserved_by: currentUser.name,
                            user_role: currentUser.role
                        });
                        
                        results.push({ timeSlot, success: true, result });
                        console.log(`✅ Reserva exitosa para ${timeSlot}`);
                        
                        // Pequeña pausa entre reservas para evitar conflictos
                        await new Promise(resolve => setTimeout(resolve, 200));
                        
                    } catch (error) {
                        console.error(`❌ Error al reservar ${timeSlot}:`, error);
                        errors.push({ timeSlot, error: error.message });
                    }
                }

                // Procesar resultados
                if (results.length > 0 && errors.length === 0) {
                    // Todas las reservas fueron exitosas
                    const resourceName = currentResource === 'tablets' ? 'Tablets' : 'Sala de Enlaces';
                    const countText = results.length === 1 ? '1 reserva' : `${results.length} reservas`;
                    const slotsText = results.map(r => r.timeSlot).join(', ');
                    
                    let successMessage = `${countText} confirmada${results.length > 1 ? 's' : ''} para ${resourceName} (${slotsText})`;
                    
                    // Agregar nota especial si es fecha pasada y es admin
                    if (currentUser.role === 'admin' && isPastDate(date)) {
                        successMessage += ' - Reserva en fecha pasada realizada por administrador';
                    }
                    
                    showToast(successMessage, 'success');
                    
                    // Limpiar formulario completamente
                    document.getElementById('subject').value = '';
                    selectedTimeSlots = [];
                    updateSelectedTimeIndicator();
                    
                } else if (results.length > 0 && errors.length > 0) {
                    // Algunas reservas exitosas, otras fallaron
                    const successSlots = results.map(r => r.timeSlot).join(', ');
                    const errorSlots = errors.map(e => `${e.timeSlot}: ${e.error}`).join('; ');
                    
                    showToast(`Reservas confirmadas: ${successSlots}. Errores: ${errorSlots}`, 'warning');
                    
                    // Remover solo los horarios exitosos de la selección
                    const successTimeSlots = results.map(r => r.timeSlot);
                    selectedTimeSlots = selectedTimeSlots.filter(slot => !successTimeSlots.includes(slot));
                    updateSelectedTimeIndicator();
                    
                } else {
                    // Todas las reservas fallaron
                    const errorMessages = errors.map(e => `${e.timeSlot}: ${e.error}`).join('; ');
                    showToast(`Error al realizar las reservas: ${errorMessages}`, 'error');
                }

                // Recargar horarios y límites para mostrar el estado actualizado
                await loadSchedule();
                await loadUserLimits(); // NUEVO: Recargar límites después de hacer reservas

            } catch (error) {
                console.error('❌ Error general al procesar reservas:', error);
                showToast('Error al procesar las reservas: ' + error.message, 'error');
            } finally {
                reserveBtn.disabled = false;
                updateReserveButtonWithLimits(); // MODIFICADO: Usar nueva función con límites
            }
        }

        // ===== FUNCIONES AUXILIARES =====
        function selectResource(resource) {
            currentResource = resource;
            selectedTimeSlots = [];
            
            document.getElementById('btnSalaEnlaces').classList.toggle('active', resource === 'sala_enlaces');
            document.getElementById('btnTablets').classList.toggle('active', resource === 'tablets');
            
            document.getElementById('btnSalaEnlaces2').classList.toggle('active', resource === 'sala_enlaces');
            document.getElementById('btnTablets2').classList.toggle('active', resource === 'tablets');
            
            updateSelectedTimeIndicator();
            updateReserveButtonWithLimits(); // MODIFICADO: Usar nueva función con límites
            loadSchedule();
            loadUserLimits(); // NUEVO: Recargar límites cuando cambia recurso
        
            return false; // Agregar al final
         }

       function updateScheduleTitle() {
    const dateInput = document.getElementById('date');
    const titleElement = document.getElementById('scheduleTitle');
    
    if (dateInput && titleElement) {
        const selectedDate = dateInput.value;
        
        let firstLine = '📅 Horarios';
        let secondLine = '👆 Toca para seleccionar';
        let icon = 'fas fa-calendar-alt';
        let gradient = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
        let textShadow = '0 2px 4px rgba(0,0,0,0.3)';
        
        if (selectedDate) {
            const [year, month, day] = selectedDate.split('-');
            const selectedDateObj = new Date(year, month - 1, day);
            
            const now = new Date();
            const currentDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            const tomorrow = new Date(currentDate);
            tomorrow.setDate(currentDate.getDate() + 1);
            
            if (isWeekend(selectedDate)) {
                firstLine = '🚫 Fin de semana';
                secondLine = 'No hay clases';
                icon = 'fas fa-calendar-times';
                gradient = 'linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%)';
            } else if (selectedDateObj.getTime() === currentDate.getTime()) {
                firstLine = '☀️ Hoy';
                secondLine = 'Horarios disponibles';
                icon = 'fas fa-sun';
                gradient = 'linear-gradient(135deg, #ffd89b 0%, #19547b 100%)';
            } else if (selectedDateObj.getTime() === tomorrow.getTime()) {
                firstLine = '🌙 Mañana';
                secondLine = 'Horarios disponibles';
                icon = 'fas fa-moon';
                gradient = 'linear-gradient(135deg, #4da0ff 0%, #0082c8 100%)';
            } else {
                const formattedDate = selectedDateObj.toLocaleDateString('es-CL', {
                    weekday: 'short',
                    day: 'numeric',
                    month: 'short'
                });
                firstLine = `📅 ${formattedDate}`;
                secondLine = 'Horarios disponibles';
                icon = 'fas fa-calendar-day';
                gradient = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
            }
        }
        
        titleElement.innerHTML = `
            <div class="compact-title" style="background: ${gradient}">
                <div class="title-line title-main" style="color: white; text-shadow: ${textShadow}">
                    <i class="${icon}"></i>
                    <span>${firstLine}</span>
                </div>
                <div class="title-line title-sub" style="color: rgba(255,255,255,0.9); text-shadow: ${textShadow}">
                    <span>${secondLine}</span>
                </div>
            </div>
        `;
    }
}
        // ===== FUNCIONES PARA GESTIÓN DE USUARIOS =====
         function generateUserManagementContent() {
            if (!hasUserManagementAccess()) {
                return `
                    <div class="restricted-access-notice">
                        <h4>
                            <i class="fas fa-shield-alt"></i>
                            Acceso Restringido
                        </h4>
                        <p>
                            La gestión de usuarios está restringida únicamente al súper administrador <strong>"${SUPER_ADMIN_USERNAME}"</strong> 
                            por razones de seguridad del sistema.
                        </p>
                        <br>
                        <p style="color: #ff5722; font-weight: bold;">
                            <i class="fas fa-exclamation-triangle"></i>
                            Tu usuario: <strong>"${currentUser?.username || 'Desconocido'}"</strong> no tiene permisos para esta sección.
                        </p>
                    </div>
                `;
            }

            // Contenido completo para súper administrador CON BÚSQUEDA
            return `
                <div class="users-management">
                    
                    <!-- FORMULARIO PARA NUEVO USUARIO -->
                    <div class="user-form-section">
                        <h4><i class="fas fa-user-plus"></i> Registrar Nuevo Usuario</h4>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="newUsername">Usuario:</label>
                                <input type="text" id="newUsername" placeholder="Nombre de usuario único">
                            </div>
                            <div class="form-group">
                                <label for="newUserFullName">Nombre Completo:</label>
                                <input type="text" id="newUserFullName" placeholder="Nombre completo del usuario">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="newUserPassword">Contraseña:</label>
                                <input type="password" id="newUserPassword" placeholder="Contraseña segura">
                            </div>
                            <div class="form-group">
                                <label for="newUserRole">Rol:</label>
                                <select id="newUserRole">
                                    <option value="user">Usuario</option>
                                    <option value="admin">Administrador</option>
                                </select>
                            </div>
                        </div>
                        <div style="text-align: center; margin-bottom: 30px;">
                            <button class="btn btn-success" onclick="createNewUser()">
                                <i class="fas fa-user-plus"></i> Crear Usuario
                            </button>
                        </div>
                    </div>

                    <!-- LISTA DE USUARIOS EXISTENTES CON BÚSQUEDA -->
                    <div class="users-list-section">
                        <h4><i class="fas fa-users"></i> Usuarios Registrados</h4>
                        
                        <!-- SECCIÓN DE BÚSQUEDA DE USUARIOS (MOVIDA AQUÍ) -->
                        <div class="users-search-section">
                            <h4>
                                <i class="fas fa-search"></i> 
                                Buscar Usuarios
                            </h4>
                            <div class="search-filters">
                                <div class="search-input-group">
                                    <input 
                                        type="text" 
                                        id="searchUsers" 
                                        placeholder="Buscar por nombre o usuario..."
                                        oninput="searchUsers()"
                                    >
                                    <i class="fas fa-search search-icon"></i>
                                </div>
                                <div class="role-filter-group">
                                    <select id="roleFilter" onchange="filterUsersByRole()">
                                        <option value="all">Todos los roles</option>
                                        <option value="admin">Solo Administradores</option>
                                        <option value="user">Solo Usuarios</option>
                                    </select>
                                </div>
                                <button class="clear-search-btn" onclick="clearUserSearch()">
                                    <i class="fas fa-eraser"></i>
                                    Limpiar
                                </button>
                            </div>
                            <div id="searchResultsInfo" class="search-results-info" style="display: none;">
                                <i class="fas fa-info-circle"></i>
                                <span id="searchResultsText"></span>
                            </div>
                        </div>
                        
                        <div id="usersList" class="users-list">
                            <div class="loading">
                                <i class="fas fa-spinner fa-spin"></i> Cargando usuarios...
                            </div>
                        </div>
                    </div>

                </div>
            `;
        }

        async function loadUsers() {
            if (!hasUserManagementAccess()) {
                console.warn('🚫 Intento de cargar usuarios sin permisos:', currentUser?.username);
                return;
            }

            const usersList = document.getElementById('usersList');
            if (!usersList) return;

            usersList.innerHTML = '<div class="loading"><i class="fas fa-spinner fa-spin"></i> Cargando usuarios...</div>';

            try {
                const response = await apiRequest('get_users');
                allUsers = response.data || [];
                
                console.log('👥 Usuarios cargados por súper admin:', allUsers.length);
                
                renderUsers();

                // NUEVO: Inicializar búsqueda después de cargar usuarios
                filteredUsers = [...allUsers];
                currentSearchTerm = '';
                currentRoleFilter = 'all';
                
                // Limpiar campos de búsqueda si existen
                const searchInput = document.getElementById('searchUsers');
                const roleFilter = document.getElementById('roleFilter');
                if (searchInput) searchInput.value = '';
                if (roleFilter) roleFilter.value = 'all';

            } catch (error) {
                usersList.innerHTML = `<div class="alert alert-error">Error al cargar usuarios: ${error.message}</div>`;
                console.error('❌ Error al cargar usuarios:', error);
            }
        }

        function renderUsers() {
            // Si no hay filtros activos, mostrar todos los usuarios
            if (!currentSearchTerm && currentRoleFilter === 'all') {
                filteredUsers = [...allUsers];
            }
            
            renderFilteredUsers();
            updateSearchResultsInfo();
        }

        function createUserCard(user) {
            const div = document.createElement('div');
            div.className = `user-card ${user.role}`;
            
            // Agregar indicador especial para el súper administrador
            const superAdminIndicator = user.username === SUPER_ADMIN_USERNAME ? 
                '<span class="super-admin-badge"><i class="fas fa-crown"></i> SÚPER ADMIN</span>' : '';
            
            div.innerHTML = `
                <div class="user-card-header">
                    <div class="user-info">
                        <div class="user-name">
                            ${user.name}
                            <span class="role-badge ${user.role}">${user.role === 'admin' ? 'Administrador' : 'Usuario'}</span>
                            ${superAdminIndicator}
                        </div>
                        <div class="user-details">
                            <i class="fas fa-user"></i> Usuario: ${user.username}
                            ${user.telefono ? `<br><i class="fas fa-phone"></i> Teléfono: ${user.telefono}` : ''}
                        </div>
                    </div>
                    <div class="user-actions">
                        <button class="btn btn-info" onclick="editUser(${user.id})" title="Editar usuario">
                            <i class="fas fa-edit"></i>
                        </button>
                        ${user.username !== currentUser.username ? `
                            <button class="btn btn-danger" onclick="deleteUser(${user.id}, '${user.username}')" title="Eliminar usuario">
                                <i class="fas fa-trash"></i>
                            </button>
                        ` : `
                            <span class="btn" style="background: #6c757d; cursor: not-allowed;" title="No puedes eliminarte a ti mismo">
                                <i class="fas fa-shield-alt"></i>
                            </span>
                        `}
                    </div>
                </div>
            `;

            return div;
        }

        async function createNewUser() {
            if (!hasUserManagementAccess()) {
                showAccessDenied();
                return;
            }

            const username = document.getElementById('newUsername').value.trim();
            const fullName = document.getElementById('newUserFullName').value.trim();
            const password = document.getElementById('newUserPassword').value;
            const role = document.getElementById('newUserRole').value;

            // Validaciones
            if (!username) {
                showToast('Por favor ingrese un nombre de usuario', 'warning');
                return;
            }
            if (!fullName) {
                showToast('Por favor ingrese el nombre completo', 'warning');
                return;
            }
            if (!password) {
                showToast('Por favor ingrese una contraseña', 'warning');
                return;
            }
            if (password.length < 4) {
                showToast('La contraseña debe tener al menos 4 caracteres', 'warning');
                return;
            }

            try {
                await apiRequest('create_user', 'POST', {
                    username: username,
                    name: fullName,
                    password: password,
                    role: role
                });

                // Limpiar formulario
                document.getElementById('newUsername').value = '';
                document.getElementById('newUserFullName').value = '';
                document.getElementById('newUserPassword').value = '';
                document.getElementById('newUserRole').value = 'user';

                showToast(`Usuario ${username} creado exitosamente por súper administrador`, 'success');
                
                // Recargar usuarios
                await loadUsers();

            } catch (error) {
                showToast('Error al crear usuario: ' + error.message, 'error');
            }
        }

        let currentEditingUserId = null;

        async function editUser(userId) {
            if (!hasUserManagementAccess()) {
                showAccessDenied();
                return;
            }

            try {
                const response = await apiRequest('get_user', 'GET', { id: userId });
                const user = response.data;

                currentEditingUserId = userId;
                document.getElementById('editUsername').value = user.username;
                document.getElementById('editUserFullName').value = user.name;
                document.getElementById('editUserRole').value = user.role;
                document.getElementById('editUserPassword').value = '';

                document.getElementById('editUserModal').classList.add('show');
            } catch (error) {
                showToast('Error al cargar datos del usuario: ' + error.message, 'error');
            }
        }

        async function updateUser() {
            if (!hasUserManagementAccess()) {
                showAccessDenied();
                return;
            }

            if (!currentEditingUserId) return;

            const fullName = document.getElementById('editUserFullName').value.trim();
            const role = document.getElementById('editUserRole').value;
            const password = document.getElementById('editUserPassword').value;

            if (!fullName) {
                showToast('Por favor ingrese el nombre completo', 'warning');
                return;
            }

            try {
                const updateData = {
                    id: currentEditingUserId,
                    name: fullName,
                    role: role
                };

                // Solo incluir contraseña si se proporcionó una nueva
                if (password.trim()) {
                    if (password.length < 4) {
                        showToast('La contraseña debe tener al menos 4 caracteres', 'warning');
                        return;
                    }
                    updateData.password = password;
                }

                await apiRequest('update_user', 'PUT', updateData);

                closeEditUserModal();
                showToast('Usuario actualizado exitosamente por súper administrador', 'success');
                await loadUsers();

            } catch (error) {
                showToast('Error al actualizar usuario: ' + error.message, 'error');
            }
        }

        async function deleteUser(userId, username) {
            if (!hasUserManagementAccess()) {
                showAccessDenied();
                return;
            }

            if (!confirm(`¿Está seguro que desea eliminar el usuario "${username}"?`)) {
                return;
            }

            try {
                await apiRequest('delete_user', 'DELETE', { id: userId });
                showToast(`Usuario ${username} eliminado exitosamente por súper administrador`, 'success');
                await loadUsers();

            } catch (error) {
                showToast('Error al eliminar usuario: ' + error.message, 'error');
            }
        }

        function closeEditUserModal() {
            document.getElementById('editUserModal').classList.remove('show');
            currentEditingUserId = null;
        }

        function switchAdminTab(tabName) {
            // Verificar acceso para gestión de usuarios
            if (tabName === 'users' && !hasUserManagementAccess()) {
                showAccessDenied();
                return;
            }

            // Desactivar todas las pestañas
            document.querySelectorAll('.admin-tab-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelectorAll('.admin-tab-content').forEach(content => content.classList.remove('active'));
            
            // Activar la pestaña seleccionada
            document.querySelector(`[onclick*="switchAdminTab('${tabName}')"]`).classList.add('active');
            document.getElementById(`adminTab${tabName.charAt(0).toUpperCase() + tabName.slice(1)}`).classList.add('active');
            
            // Cargar datos si es necesario
            if (tabName === 'users' && hasUserManagementAccess()) {
                const userManagementContent = document.getElementById('userManagementContent');
                userManagementContent.innerHTML = generateUserManagementContent();
                loadUsers();
            }
            
            // Cargar configuración de horarios
            if (tabName === 'schedule') {
                loadScheduleConfig();
            }
        }
        
        // ===== FUNCIONES PARA BÚSQUEDA DE USUARIOS =====

        /**
         * Función principal de búsqueda de usuarios
         */
        function searchUsers() {
            const searchInput = document.getElementById('searchUsers');
            if (!searchInput) return;

            currentSearchTerm = searchInput.value.toLowerCase().trim();
            
            console.log('🔍 Buscando usuarios:', currentSearchTerm);
            
            applyFilters();
        }

        /**
         * Función para filtrar usuarios por rol
         */
        function filterUsersByRole() {
            const roleFilter = document.getElementById('roleFilter');
            if (!roleFilter) return;

            currentRoleFilter = roleFilter.value;
            
            console.log('🎭 Filtrando por rol:', currentRoleFilter);
            
            applyFilters();
        }

        /**
         * Función para aplicar todos los filtros combinados
         */
        function applyFilters() {
            if (!allUsers || allUsers.length === 0) {
                console.warn('⚠️ No hay usuarios cargados para filtrar');
                return;
            }

            // Aplicar filtros combinados
            filteredUsers = allUsers.filter(user => {
                // Filtro por rol
                const roleMatch = currentRoleFilter === 'all' || user.role === currentRoleFilter;
                
                // Filtro por texto de búsqueda
                const searchMatch = currentSearchTerm === '' || 
                    user.name.toLowerCase().includes(currentSearchTerm) ||
                    user.username.toLowerCase().includes(currentSearchTerm);
                
                return roleMatch && searchMatch;
            });

            console.log('🔍 Resultados de búsqueda:', {
                total: allUsers.length,
                filtrados: filteredUsers.length,
                termino: currentSearchTerm,
                rol: currentRoleFilter
            });

            renderFilteredUsers();
            updateSearchResultsInfo();
        }

        /**
         * Función para limpiar la búsqueda
         */
        function clearUserSearch() {
            const searchInput = document.getElementById('searchUsers');
            const roleFilter = document.getElementById('roleFilter');
            
            if (searchInput) searchInput.value = '';
            if (roleFilter) roleFilter.value = 'all';
            
            currentSearchTerm = '';
            currentRoleFilter = 'all';
            
            console.log('🧹 Búsqueda limpiada');
            
            // Mostrar todos los usuarios
            filteredUsers = [...allUsers];
            renderFilteredUsers();
            updateSearchResultsInfo();
            
            showToast('Búsqueda limpiada - Mostrando todos los usuarios', 'info', 3000);
        }

        /**
         * Función para renderizar usuarios filtrados
         */
        function renderFilteredUsers() {
            const usersList = document.getElementById('usersList');
            if (!usersList) return;

            if (filteredUsers.length === 0) {
                if (currentSearchTerm || currentRoleFilter !== 'all') {
                    // No hay resultados para la búsqueda actual
                    usersList.innerHTML = `
                        <div class="alert alert-warning" style="text-align: center; padding: 30px;">
                            <i class="fas fa-search" style="font-size: 2rem; color: #ffc107; margin-bottom: 15px; display: block;"></i>
                            <h4 style="color: #856404; margin-bottom: 15px;">Sin resultados</h4>
                            <p style="color: #666; margin-bottom: 20px;">
                                No se encontraron usuarios que coincidan con los criterios de búsqueda.
                            </p>
                            <button class="btn btn-info" onclick="clearUserSearch()">
                                <i class="fas fa-eraser"></i> Limpiar búsqueda
                            </button>
                        </div>
                    `;
                } else {
                    // No hay usuarios en el sistema
                    usersList.innerHTML = `
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i> No hay usuarios registrados
                        </div>
                    `;
                }
                return;
            }
            
            usersList.innerHTML = '';
            
            filteredUsers.forEach(user => {
                const userCard = createUserCard(user);
                
                // Marcar como resultado de búsqueda si hay filtros activos
                if (currentSearchTerm || currentRoleFilter !== 'all') {
                    userCard.classList.add('search-match');
                }
                
                usersList.appendChild(userCard);
            });

            console.log('✅ Usuarios renderizados con filtros:', filteredUsers.length);
        }

        /**
         * Función para actualizar información de resultados de búsqueda
         */
        function updateSearchResultsInfo() {
            const searchResultsInfo = document.getElementById('searchResultsInfo');
            const searchResultsText = document.getElementById('searchResultsText');
            
            if (!searchResultsInfo || !searchResultsText) return;

            // Determinar si hay filtros activos
            const hasActiveFilters = currentSearchTerm || currentRoleFilter !== 'all';
            
            if (!hasActiveFilters) {
                // Sin filtros - ocultar información
                searchResultsInfo.style.display = 'none';
                return;
            }

            // Mostrar información de resultados
            searchResultsInfo.style.display = 'flex';
            
            // Construir mensaje de resultados
            let message = '';
            const totalUsers = allUsers.length;
            const foundUsers = filteredUsers.length;
            
            if (foundUsers === 0) {
                searchResultsInfo.className = 'search-results-info no-results';
                message = `Sin resultados de ${totalUsers} usuarios`;
            } else if (foundUsers === totalUsers) {
                searchResultsInfo.className = 'search-results-info has-results';
                message = `Mostrando todos los ${totalUsers} usuarios`;
            } else {
                searchResultsInfo.className = 'search-results-info has-results';
                message = `${foundUsers} de ${totalUsers} usuarios encontrados`;
            }
            
            // Agregar detalles de filtros
            const filterDetails = [];
            if (currentSearchTerm) {
                filterDetails.push(`texto: "${currentSearchTerm}"`);
            }
            if (currentRoleFilter !== 'all') {
                const roleText = currentRoleFilter === 'admin' ? 'Administradores' : 'Usuarios';
                filterDetails.push(`rol: ${roleText}`);
            }
            
            if (filterDetails.length > 0) {
                message += ` (${filterDetails.join(', ')})`;
            }
            
            searchResultsText.textContent = message;
        }

        // ===== FUNCIONES PARA REPORTES =====
        async function generateReport() {
            const reportMonth = document.getElementById('reportMonth').value;
            if (!reportMonth) {
                showToast('Por favor seleccione un mes para el reporte', 'warning');
                return;
            }

            try {
                showToast('Generando reporte PDF...', 'info');
                
                const response = await apiRequest('get_monthly_report', 'GET', { month: reportMonth });
                generatePDF(response.data, reportMonth);
                
                showToast('Reporte PDF generado exitosamente', 'success');

            } catch (error) {
                showToast('Error al generar reporte: ' + error.message, 'error');
            }
        }

        // ===== FUNCIÓN MEJORADA PARA CARGAR LOGO CON ALTA CALIDAD =====
        function loadLogo() {
            return new Promise((resolve) => {
                console.log('🎨 Cargando logo del Colegio El Cobre con alta calidad...');
                
                const img = new Image();
                img.crossOrigin = "anonymous";
                
                img.onload = function() {
                    try {
                        // Crear canvas con mayor resolución para mejor calidad en PDF
                        const canvas = document.createElement('canvas');
                        const ctx = canvas.getContext('2d');
                        
                        // Tamaño más grande para mejor calidad en PDF (luego escalamos al renderizar)
                        canvas.width = 240;  // Doble tamaño para retina/alta calidad
                        canvas.height = 240;
                        
                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                        
                        // Calcular escala manteniendo relación de aspecto
                        const scale = Math.min(
                            canvas.width / img.naturalWidth, 
                            canvas.height / img.naturalHeight
                        );
                        
                        const x = (canvas.width - img.naturalWidth * scale) / 2;
                        const y = (canvas.height - img.naturalHeight * scale) / 2;
                        
                        // Configuración de calidad de renderizado
                        ctx.imageSmoothingEnabled = true;
                        ctx.imageSmoothingQuality = 'high';
                        
                        ctx.drawImage(
                            img, 
                            x, y, 
                            img.naturalWidth * scale, 
                            img.naturalHeight * scale
                        );
                        
                        // Convertir a PNG con calidad máxima
                        logoBase64 = canvas.toDataURL('image/png', 1.0);
                        console.log('✅ Logo del Colegio El Cobre cargado con alta calidad');
                        resolve(logoBase64);
                    } catch (error) {
                        console.warn('⚠️ Error al procesar logo:', error);
                        createFallbackLogo().then(resolve);
                    }
                };
                
                img.onerror = function() {
                    console.warn('⚠️ No se pudo cargar img/ElCobre.png, creando logo alternativo');
                    createFallbackLogo().then(resolve);
                };
                
                // Usar ruta absoluta para evitar problemas de carga
                img.src = '../img/ElCobre.png';
            });
        }

        function createFallbackLogo() {
            return new Promise((resolve) => {
                console.log('🔄 Creando logo alternativo del Colegio El Cobre...');
                
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                
                canvas.width = 120;
                canvas.height = 120;
                
                const gradient = ctx.createRadialGradient(60, 60, 20, 60, 60, 55);
                gradient.addColorStop(0, '#87CEEB');
                gradient.addColorStop(1, '#4169E1');
                
                ctx.fillStyle = gradient;
                ctx.beginPath();
                ctx.arc(60, 60, 55, 0, 2 * Math.PI);
                ctx.fill();
                
                ctx.strokeStyle = '#FFD700';
                ctx.lineWidth = 3;
                ctx.beginPath();
                ctx.arc(60, 60, 55, 0, 2 * Math.PI);
                ctx.stroke();
                
                ctx.fillStyle = 'white';
                ctx.font = 'bold 10px Arial';
                ctx.textAlign = 'center';
                ctx.fillText('COLEGIO', 60, 30);
                
                ctx.fillStyle = 'white';
                ctx.beginPath();
                ctx.moveTo(25, 60);
                ctx.lineTo(35, 45);
                ctx.lineTo(50, 55);
                ctx.lineTo(60, 40);
                ctx.lineTo(70, 50);
                ctx.lineTo(85, 45);
                ctx.lineTo(95, 60);
                ctx.lineTo(25, 60);
                ctx.fill();
                
                ctx.fillStyle = '#CD853F';
                ctx.strokeStyle = '#8B4513';
                ctx.lineWidth = 1;
                
                ctx.fillRect(35, 65, 15, 6);
                ctx.strokeRect(35, 65, 15, 6);
                
                ctx.fillRect(42, 71, 15, 6);
                ctx.strokeRect(42, 71, 15, 6);
                
                ctx.fillRect(49, 77, 15, 6);
                ctx.strokeRect(49, 77, 15, 6);
                
                ctx.fillStyle = 'white';
                ctx.font = 'bold 10px Arial';
                ctx.fillText('EL COBRE', 60, 95);
                
                logoBase64 = canvas.toDataURL('image/png', 1.0);
                console.log('✅ Logo alternativo creado exitosamente');
                resolve(logoBase64);
            });
        }

        // ===== FUNCIÓN MEJORADA PARA GENERAR REPORTE PDF CON LOGO =====
        function generatePDF(reportData, reportMonth) {
            const [year, month] = reportMonth.split('-');
            const monthName = new Date(year, month - 1).toLocaleDateString('es-CL', { 
                month: 'long', 
                year: 'numeric',
                timeZone: 'America/Santiago'
            });
            
            const doc = new window.jspdf.jsPDF();
            doc.setFont("helvetica");

            let yPos = 20;

            // AGREGAR LOGO CON ALTA CALIDAD
            if (logoBase64) {
                try {
                    console.log('📊 Agregando logo del Colegio El Cobre al reporte PDF con alta calidad...');
                    
                    // Tamaño del logo en el PDF
                    const logoWidth = 40;
                    const logoHeight = 40;
                    const logoX = 15;
                    
                    // Agregar el logo con calidad mejorada
                    doc.addImage({
                        imageData: logoBase64,
                        format: 'PNG',
                        x: logoX,
                        y: yPos,
                        width: logoWidth,
                        height: logoHeight,
                        // Opciones de calidad
                        compression: 'NONE', // Sin compresión para máxima calidad
                        alias: 'logo_el_cobre'
                    });
                    
                    console.log('✅ Logo agregado exitosamente al reporte PDF con alta calidad');
                    
                    yPos = 25;
                } catch (error) {
                    console.warn('⚠️ Error al agregar logo al PDF:', error);
                    yPos = 20;
                }
            }

            // HEADER DEL DOCUMENTO CON LOGO
            const titleX = logoBase64 ? 60 : 105;
            const titleAlign = logoBase64 ? 'left' : 'center';
            
            doc.setFontSize(18);
            doc.setTextColor(44, 62, 80);
            doc.text('COLEGIO EL COBRE', titleX, yPos, { align: titleAlign });
            yPos += 12;
            
            doc.setFontSize(16);
            doc.text('REPORTE MENSUAL DE USO', titleX, yPos, { align: titleAlign });
            yPos += 10;
            
            doc.setFontSize(14);
            doc.text('Sala de Computación y Tablets', titleX, yPos, { align: titleAlign });
            yPos += 8;
            
            doc.setFontSize(12);
            doc.text(`Período: ${monthName}`, titleX, yPos, { align: titleAlign });
            yPos += 20;

            doc.setDrawColor(102, 126, 234);
            doc.setLineWidth(1);
            doc.line(20, yPos, 190, yPos);
            yPos += 20;

            // ESTADÍSTICAS GENERALES MEJORADAS
            doc.setFontSize(14);
            doc.setTextColor(102, 126, 234);
            doc.text('ESTADÍSTICAS GENERALES:', 20, yPos);
            yPos += 15;

            doc.setFillColor(240, 244, 248);
            doc.rect(15, yPos - 10, 175, 30, 'F');

            doc.setFontSize(10);
            doc.setTextColor(0, 0, 0);
            
            doc.text('Total Reservas:', 20, yPos);
            doc.setFont("helvetica", "bold");
            doc.text(`${reportData.total_reservations}`, 65, yPos);
            doc.setFont("helvetica", "normal");
            
            doc.text('Confirmadas:', 85, yPos);
            doc.setFont("helvetica", "bold");
            doc.text(`${reportData.confirmed_attendance}`, 125, yPos);
            doc.setFont("helvetica", "normal");
            
            doc.text('No Asistieron:', 150, yPos);
            doc.setFont("helvetica", "bold");
            doc.text(`${reportData.no_shows}`, 180, yPos);
            doc.setFont("helvetica", "normal");
            yPos += 15;

            doc.text('Pendientes:', 20, yPos);
            doc.setFont("helvetica", "bold");
            doc.text(`${reportData.pending}`, 65, yPos);
            doc.setFont("helvetica", "normal");
            
            doc.text('Usuarios Únicos:', 85, yPos);
            doc.setFont("helvetica", "bold");
            doc.text(`${reportData.unique_users_count}`, 125, yPos);
            doc.setFont("helvetica", "normal");
            
            doc.text('Tasa Asistencia:', 150, yPos);
            doc.setFont("helvetica", "bold");
            doc.setTextColor(76, 175, 80);
            doc.text(`${reportData.attendance_rate}%`, 180, yPos);
            doc.setTextColor(0, 0, 0);
            doc.setFont("helvetica", "normal");
            yPos += 25;
            
            // DETALLE DE RESERVAS CON PAGINACIÓN
            if (reportData.reservations && reportData.reservations.length > 0) {
                doc.setFontSize(14);
                doc.setTextColor(102, 126, 234);
                doc.text('DETALLE DE RESERVAS:', 20, yPos);
                yPos += 15;

                // HEADER DE TABLA
                doc.setFontSize(9);
                doc.setTextColor(255, 255, 255);
                doc.setFillColor(102, 126, 234);
                doc.rect(15, yPos - 8, 175, 12, 'F');
                
                doc.text('Fecha', 20, yPos);
                doc.text('Horario', 45, yPos);
                doc.text('Usuario', 70, yPos);
                doc.text('Asignatura', 95, yPos);
                doc.text('Curso', 120, yPos);
                doc.text('Recurso', 140, yPos);
                doc.text('Estado', 165, yPos);
                yPos += 10;

                // ORDENAR RESERVAS POR FECHA
                const sortedReservations = reportData.reservations.sort((a, b) => 
                    new Date(a.reservation_date) - new Date(b.reservation_date)
                );

                doc.setTextColor(0, 0, 0);
                sortedReservations.forEach((reservation, index) => {
                    // NUEVA PÁGINA SI ES NECESARIO
                    if (yPos > 270) {
                        doc.addPage();
                        yPos = 30;
                        
                        doc.setFontSize(12);
                        doc.setTextColor(102, 126, 234);
                        doc.text(`Reporte Mensual - ${monthName} (Continuación)`, 105, yPos, { align: 'center' });
                        yPos += 20;
                        
                        // REPETIR HEADER DE TABLA
                        doc.setFontSize(9);
                        doc.setTextColor(255, 255, 255);
                        doc.setFillColor(102, 126, 234);
                        doc.rect(15, yPos - 8, 175, 12, 'F');
                        
                        doc.text('Fecha', 20, yPos);
                        doc.text('Horario', 45, yPos);
                        doc.text('Usuario', 70, yPos);
                        doc.text('Asignatura', 95, yPos);
                        doc.text('Curso', 120, yPos);
                        doc.text('Recurso', 140, yPos);
                        doc.text('Estado', 165, yPos);
                        yPos += 10;
                        doc.setTextColor(0, 0, 0);
                    }

                    // FILA ALTERNADA
                    if (index % 2 === 0) {
                        doc.setFillColor(248, 249, 250);
                        doc.rect(15, yPos - 6, 175, 10, 'F');
                    }

                    doc.setFontSize(8);
                    
                    // FORMATEAR FECHA CON ZONA HORARIA CHILE
                    let chileDate = 'Fecha inválida';

                    if (reservation.reservation_date) {
                        try {
                            // Si la fecha viene como string de fecha simple (YYYY-MM-DD)
                            if (reservation.reservation_date.includes('-') && !reservation.reservation_date.includes('T')) {
                                // Es una fecha simple, usarla directamente
                                const [year, month, day] = reservation.reservation_date.split('-');
                                const localDate = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
                                
                                chileDate = localDate.toLocaleDateString('es-CL', {
                                    day: '2-digit',
                                    month: '2-digit', 
                                    year: 'numeric'
                                });
                            } else {
                                // Es una fecha con hora, extraer solo la fecha
                                const formatted = formatChileDateTime(reservation.reservation_date);
                                if (formatted && formatted !== 'Fecha inválida') {
                                    chileDate = formatted.split(' ')[0]; // Tomar solo la fecha, no la hora
                                } else {
                                    // Fallback
                                    const reservationDate = new Date(reservation.reservation_date);
                                    if (!isNaN(reservationDate.getTime())) {
                                        chileDate = reservationDate.toLocaleDateString('es-CL', {
                                            timeZone: 'America/Santiago',
                                            day: '2-digit',
                                            month: '2-digit',
                                            year: 'numeric'
                                        });
                                    }
                                }
                            }
                        } catch (error) {
                            console.error('Error al formatear fecha de reserva:', error);
                            chileDate = reservation.reservation_date.substring(0, 10); // Fallback
                        }
                    }
                                        
                    doc.text(chileDate, 20, yPos);
                    doc.text(reservation.time_slot || '', 45, yPos);
                    doc.text((reservation.user_name || '').substring(0, 12), 70, yPos);
                    doc.text((reservation.purpose || '').substring(0, 12), 95, yPos);
                    doc.text((reservation.course || '').substring(0, 12), 120, yPos);
                    
                    // TEXTO DE RECURSO
                    let resourceText = 'N/A';
                    if (reservation.resource_type === 'tablets') {
                        resourceText = 'Tablets';
                    } else if (reservation.resource_type === 'sala_enlaces') {
                        resourceText = 'Enlaces';
                    }
                    doc.text(resourceText, 140, yPos);
                    
                    // ESTADO DE ASISTENCIA CON COLORES
                    let attendanceText = 'Pendiente';
                    let attendanceColor = [255, 152, 0];
                    
                    if (reservation.attendance == 1) {
                        attendanceText = 'Asistió';
                        attendanceColor = [76, 175, 80];
                    } else if (reservation.attendance == 0) {
                        attendanceText = 'No asistió';
                        attendanceColor = [244, 67, 54];
                    }
                    
                    doc.setTextColor(...attendanceColor);
                    doc.text(attendanceText, 165, yPos);
                    doc.setTextColor(0, 0, 0);
                    yPos += 10;
                });
            }

            // FOOTER CON ZONA HORARIA DE CHILE Y PAGINACIÓN
            const totalPages = doc.internal.getNumberOfPages();
            for (let i = 1; i <= totalPages; i++) {
                doc.setPage(i);
                doc.setFontSize(8);
                doc.setTextColor(128, 128, 128);
                
                const chileNow = getCurrentChileTime();
                doc.text(`Página ${i} de ${totalPages} - Generado el ${chileNow} HRS`, 105, 285, { align: 'center' });
                doc.text('Sistema de Reservas - Colegio El Cobre', 105, 290, { align: 'center' });
            }

            const fileName = `Reporte_Sala_Computacion_${year}_${month.padStart(2, '0')}.pdf`;
            doc.save(fileName);
        }

        // ===== FUNCIONES DE DEBUG =====
        async function debugDatabaseConnection() {
            try {
                console.log('🔍 Verificando conexión y datos de la base de datos...');
                
                const coursesResponse = await apiRequest('get_courses');
                console.log('Cursos obtenidos:', coursesResponse.data);
                
                const timeSlotsResponse = await apiRequest('get_time_slots');
                console.log('Horarios obtenidos:', timeSlotsResponse.data);
                
                const reservationsResponse = await apiRequest('get_reservations', 'GET', { 
                    date: new Date().toISOString().split('T')[0],
                    resource_type: 'sala_enlaces'
                });
                console.log('Reservas obtenidas:', reservationsResponse.data);
                
                return {
                    courses: coursesResponse.data?.length || 0,
                    timeSlots: timeSlotsResponse.data?.length || 0,
                    reservations: reservationsResponse.data?.length || 0
                };
                
            } catch (error) {
                console.error('❌ Error en debug:', error);
                return { error: error.message };
            }
        }

        async function reloadScheduleData() {
            try {
                showToast('Recargando horarios...', 'info', 3000);
                
                const debugInfo = await debugDatabaseConnection();
                console.log('🔍 Debug info:', debugInfo);
                
                if (debugInfo.error) {
                    throw new Error('Error de conexión: ' + debugInfo.error);
                }
                
                if (debugInfo.timeSlots === 0) {
                    throw new Error('No hay horarios configurados en la base de datos. Contacte al administrador para configurar la tabla "horarios".');
                }
                
                await loadTimeSlots();
                await loadSchedule();
                await loadUserLimits(); // NUEVO: Recargar límites también
                
                showToast(`Horarios recargados: ${debugInfo.timeSlots} horarios disponibles`, 'success', 4000);
                
            } catch (error) {
                console.error('❌ Error al recargar horarios:', error);
                showToast('Error al recargar horarios: ' + error.message, 'error');
            }
        }

        // ===== EVENT LISTENERS Y INICIALIZACIÓN =====
        document.addEventListener('DOMContentLoaded', function() {

        // Prevenir todos los envíos de formulario
            document.addEventListener('submit', function(e) {
                e.preventDefault();
                return false;
            });
            
            // Agregar type="button" a botones sin type
            const buttonsWithoutType = document.querySelectorAll('button:not([type])');
            buttonsWithoutType.forEach(btn => {
                btn.setAttribute('type', 'button');
            });
            console.log('🚀 Sistema de Reservas con Límites de Usuario iniciado');
            console.log('📊 Todos los usuarios (incluidos administradores) tienen límite de 4 reservas por recurso por mes');
            console.log('👑 Solo el súper administrador "Claudio" tiene acceso ilimitado');
            console.log('✅ Los cupos se liberan cuando los administradores confirman o cancelan reservas');
            
            loadLogo().then(() => {
                console.log('✅ Logo cargado y listo para usar en reportes');
            }).catch(error => {
                console.warn('⚠️ Error al cargar logo:', error);
            });
            
            document.getElementById('password').addEventListener('keypress', function(event) {
                if (event.key === 'Enter') {
                    login();
                }

                // Event listeners para búsqueda de usuarios (se configuran cuando se carga la pestaña)
            document.addEventListener('input', function(event) {
                if (event.target && event.target.id === 'searchUsers') {
                        // Búsqueda en tiempo real con debounce
                        clearTimeout(window.searchTimeout);
                        window.searchTimeout = setTimeout(() => {
                            searchUsers();
                        }, 300);
                    }
                });
            });

            document.getElementById('subject').addEventListener('keypress', function(event) {
                if (event.key === 'Enter') {
                    makeReservation();
                }
            });

            // Event listeners para el modal de cambio de contraseña
            document.getElementById('currentPassword').addEventListener('keypress', function(event) {
                if (event.key === 'Enter') {
                    document.getElementById('newPassword').focus();
                }
            });

            document.getElementById('newPassword').addEventListener('keypress', function(event) {
                if (event.key === 'Enter') {
                    document.getElementById('confirmPassword').focus();
                }
            });

            document.getElementById('confirmPassword').addEventListener('keypress', function(event) {
                if (event.key === 'Enter') {
                    changePassword();
                }
            });

            updateReserveButtonWithLimits(); // MODIFICADO: Usar nueva función con límites
        });

        // ===== FUNCIONES GLOBALES PARA DEBUG =====
        window.debugReservationSystem = {
            checkDatabase: debugDatabaseConnection,
            reloadData: reloadScheduleData,
            currentUser: () => currentUser,
            timeSlots: () => timeSlots,
            reservations: () => reservations,
            courses: () => courses,
            userLimits: () => userLimits, // NUEVO: Debug de límites
            forceReload: async () => {
                await initializeApp();
                console.log('🔄 Sistema reinicializado manualmente');
            },
            testChileTimezone: () => {
                const now = new Date();
                
                console.log('🧪 Test de Zona Horaria Chile:');
                console.log('UTC:', now.toISOString());
                console.log('Chile (Santiago):', formatChileDateTime(now.toISOString()));
                console.log('Chile (getCurrentChileTime):', getCurrentChileTime());
                
                const testDate = '2024-12-20 15:30:00';
                console.log(`Test fecha "${testDate}":`, formatChileDateTime(testDate));
                
                return {
                    utc: now.toISOString(),
                    chile: formatChileDateTime(now.toISOString()),
                    current: getCurrentChileTime()
                };
            },
            testAccessControl: () => {
                console.log('🔒 Test de Control de Acceso:');
                console.log('Usuario actual:', currentUser?.username || 'No logueado');
                console.log('Es súper admin:', isSuperAdmin());
                console.log('Tiene acceso a gestión de usuarios:', hasUserManagementAccess());
                console.log('Súper admin configurado:', SUPER_ADMIN_USERNAME);
                
                return {
                    currentUser: currentUser?.username || 'No logueado',
                    isSuperAdmin: isSuperAdmin(),
                    hasUserAccess: hasUserManagementAccess(),
                    superAdminUsername: SUPER_ADMIN_USERNAME
                };
            },
            testLimits: () => { // NUEVO: Debug de límites
                console.log('📊 Test de Límites de Reservas:');
                console.log('Usuario actual:', currentUser?.name || 'No logueado');
                console.log('Es súper admin (gestión usuarios):', isSuperAdmin());
                console.log('Es súper admin Claudio (sin límites):', isSuperAdminClaudio());
                console.log('Límites cargados:', limitsLoaded);
                console.log('Datos de límites:', userLimits);
                
                return {
                    currentUser: currentUser?.name || 'No logueado',
                    role: currentUser?.role || 'No role',
                    isSuperAdmin: isSuperAdmin(),
                    isSuperAdminClaudio: isSuperAdminClaudio(),
                    limitsLoaded: limitsLoaded,
                    userLimits: userLimits
                };
            }
        };
        
        // Responder a solicitudes de autenticación desde ventanas hijas
        window.addEventListener('message', function(event) {
            if (event.data && event.data.type === 'requestAuth' && currentUser) {
                const authData = {
                    user: currentUser,
                    timestamp: new Date().getTime(),
                    action: 'auth_request'
                };
                
                event.source.postMessage({
                    type: 'authenticate',
                    authData: authData
                }, '*');
            }
        });

        console.log('🔧 Funciones de debug disponibles en: window.debugReservationSystem');
        console.log('⏰ Para probar zona horaria: window.debugReservationSystem.testChileTimezone()');
        console.log('🔒 Para probar control de acceso: window.debugReservationSystem.testAccessControl()');
        console.log('📊 Para probar límites: window.debugReservationSystem.testLimits()');
        console.log('👑 NOTA: Solo "Claudio" tiene acceso ilimitado. Otros administradores tienen límites normales.');
    </script>
</body>
</html>