<style>
    .calendar-container {
        background: #fff;
        border-radius: 8px;
        position: relative;
    }

    .calendar-loading {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255, 255, 255, 0.9);
        display: none;
        align-items: center;
        justify-content: center;
        z-index: 100;
        border-radius: 8px;
    }

    .calendar-loading.active {
        display: flex;
    }

    .calendar-loading-spinner {
        width: 50px;
        height: 50px;
        border: 4px solid #e9ecef;
        border-top-color: #5d87ff;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        to { transform: rotate(360deg); }
    }

    .calendar-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1.5rem;
        flex-wrap: wrap;
        gap: 1rem;
    }

    .calendar-nav {
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .calendar-nav .btn {
        width: 40px;
        height: 40px;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 8px;
    }

    .calendar-title {
        font-size: 1.5rem;
        font-weight: 600;
        color: #2a3547;
        margin: 0 1rem;
    }

    .view-selector {
        display: flex;
        gap: 0.5rem;
    }

    .view-selector .btn {
        padding: 0.5rem 1.25rem;
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s;
    }

    .calendar-grid {
        display: grid;
        grid-template-columns: repeat(7, minmax(0, 1fr));
        gap: 1px;
        background: #e9ecef;
        border-radius: 8px;
        overflow: hidden;
    }

    .calendar-day-header {
        background: #f8f9fa;
        padding: 1rem;
        text-align: center;
        font-weight: 600;
        color: #2a3547;
        font-size: 0.875rem;
        text-transform: uppercase;
    }

    .calendar-day {
        background: #fff;
        min-height: 120px;
        padding: 0.75rem;
        position: relative;
        cursor: pointer;
        transition: background 0.2s;
    }

    .calendar-day:hover {
        background: #f8f9fa;
    }

    .calendar-day.other-month {
        background: #fafbfc;
        color: #adb5bd;
    }

    .calendar-day.today {
        background: #e8f4fd;
    }

    .day-number {
        font-weight: 600;
        font-size: 0.875rem;
        color: #2a3547;
        margin-bottom: 0.5rem;
        display: flex;
        align-items: center;
        gap: 0.25rem;
    }

    .calendar-day.other-month .day-number {
        color: #adb5bd;
    }

    .holiday-indicator {
        width: 8px;
        height: 8px;
        background: #fa896b;
        border-radius: 50%;
        display: inline-block;
        cursor: pointer;
        position: relative;
        flex-shrink: 0;
    }

    .holiday-tooltip {
        position: absolute;
        top: -10px;
        left: 20px;
        background: #2a3547;
        color: #fff;
        padding: 0.5rem 0.75rem;
        border-radius: 6px;
        font-size: 0.75rem;
        white-space: nowrap;
        z-index: 1000;
        opacity: 0;
        pointer-events: none;
        transition: opacity 0.2s;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }

    .holiday-tooltip::before {
        content: '';
        position: absolute;
        left: -5px;
        top: 50%;
        transform: translateY(-50%);
        border: 5px solid transparent;
        border-right-color: #2a3547;
    }

    .holiday-indicator:hover .holiday-tooltip {
        opacity: 1;
    }

    /* Tooltip para móvil */
    .holiday-modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0,0,0,0.5);
        z-index: 2000;
        display: none;
        align-items: center;
        justify-content: center;
        padding: 1rem;
    }

    .holiday-modal-overlay.active {
        display: flex;
    }

    .holiday-modal {
        background: #fff;
        padding: 1.5rem;
        border-radius: 12px;
        max-width: 90%;
        box-shadow: 0 10px 25px rgba(0,0,0,0.2);
        animation: slideUp 0.3s ease-out;
    }

    @keyframes slideUp {
        from {
            transform: translateY(20px);
            opacity: 0;
        }
        to {
            transform: translateY(0);
            opacity: 1;
        }
    }

    .holiday-modal-header {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        margin-bottom: 1rem;
        padding-bottom: 0.75rem;
        border-bottom: 2px solid #fa896b;
    }

    .holiday-modal-icon {
        width: 24px;
        height: 24px;
        background: #fa896b;
        border-radius: 50%;
        flex-shrink: 0;
    }

    .holiday-modal-title {
        font-weight: 600;
        font-size: 1rem;
        color: #2a3547;
        margin: 0;
    }

    .holiday-modal-description {
        color: #6c757d;
        font-size: 0.875rem;
        line-height: 1.5;
        margin: 0;
    }

    .holiday-modal-close {
        margin-top: 1rem;
        width: 100%;
        padding: 0.5rem;
        background: #f8f9fa;
        border: none;
        border-radius: 6px;
        color: #2a3547;
        font-weight: 500;
        cursor: pointer;
        transition: background 0.2s;
    }

    .holiday-modal-close:hover {
        background: #e9ecef;
    }

    .calendar-day.today .day-number {
        background: #5d87ff;
        color: #fff;
        width: 28px;
        height: 28px;
        border-radius: 50%;
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }

    .event-item {
        background: #5d87ff;
        color: #fff;
        padding: 0.25rem 0.5rem;
        border-radius: 4px;
        font-size: 0.75rem;
        margin-bottom: 0.25rem;
        white-space: normal;
        word-wrap: break-word;
        cursor: pointer;
        transition: opacity 0.2s;
        line-height: 1.3;
    }

    .event-time {
        font-weight: 600;
        display: block;
        margin-bottom: 0.1rem;
    }

    .event-item:hover {
        opacity: 0.8;
    }

    .event-item.event-primary {
        background: #5d87ff;
    }

    .event-item.event-success {
        background: #13deb9;
    }

    .event-item.event-warning {
        background: #ffae1f;
    }

    .event-item.event-danger {
        background: #fa896b;
    }

    .event-item.event-info {
        background: #539bff;
    }

    /* Vista Mes */
    .month-view {
        display: none;
    }

    .month-view.active {
        display: block;
    }

    /* Vista Semana */
    .week-view {
        display: none;
    }

    .week-view.active {
        display: block;
    }

    .week-grid {
        display: grid;
        grid-template-columns: 80px repeat(7, 1fr);
        gap: 1px;
        background: #e9ecef;
        border-radius: 8px;
        overflow: hidden;
    }

    .week-time {
        background: #f8f9fa;
        padding: 0.5rem;
        text-align: center;
        font-size: 0.75rem;
        color: #6c757d;
        border-right: 1px solid #e9ecef;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .week-day-cell {
        background: #fff;
        min-height: 60px;
        position: relative;
        padding: 0.5rem;
    }

    /* Vista Día */
    .day-view {
        display: none;
    }

    .day-view.active {
        display: block;
    }

    .day-grid {
        display: grid;
        grid-template-columns: 80px 1fr;
        gap: 1px;
        background: #e9ecef;
        border-radius: 8px;
        overflow: hidden;
    }

    /* Modal de evento */
    .event-modal-content {
        padding: 1rem 0;
    }

    .event-detail {
        display: flex;
        align-items: start;
        gap: 1rem;
        margin-bottom: 1rem;
        padding-bottom: 1rem;
        border-bottom: 1px solid #e9ecef;
    }

    .event-detail:last-child {
        border-bottom: none;
        margin-bottom: 0;
    }

    .event-detail i {
        color: #5d87ff;
        font-size: 1.25rem;
        width: 24px;
        text-align: center;
    }

    .event-detail-content {
        flex: 1;
    }

    .event-detail-label {
        font-weight: 600;
        color: #2a3547;
        font-size: 0.875rem;
        margin-bottom: 0.25rem;
    }

    .event-detail-text {
        color: #6c757d;
        font-size: 0.875rem;
    }

    /* Vista Lista Móvil */
    .month-list-view {
        display: none;
    }

    .event-day-card {
        background: #fff;
        border: 1px solid #e9ecef;
        border-radius: 8px;
        padding: 1rem;
        margin-bottom: 1rem;
    }

    .event-day-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;
        padding-bottom: 0.75rem;
        border-bottom: 2px solid #5d87ff;
    }

    .event-day-name {
        font-weight: 600;
        font-size: 1rem;
        color: #2a3547;
    }

    .event-day-date {
        font-size: 0.875rem;
        color: #6c757d;
    }

    .event-list-item {
        background: #f8f9fa;
        padding: 0.75rem;
        border-radius: 6px;
        margin-bottom: 0.5rem;
        cursor: pointer;
        transition: all 0.2s;
        border-left: 4px solid #5d87ff;
    }

    .event-list-item:hover {
        background: #e9ecef;
        transform: translateX(4px);
    }

    .event-list-item.event-primary {
        border-left-color: #5d87ff;
    }

    .event-list-item.event-success {
        border-left-color: #13deb9;
    }

    .event-list-item.event-warning {
        border-left-color: #ffae1f;
    }

    .event-list-item.event-danger {
        border-left-color: #fa896b;
    }

    .event-list-item.event-info {
        border-left-color: #539bff;
    }

    .event-list-time {
        font-weight: 600;
        color: #2a3547;
        font-size: 0.875rem;
        margin-bottom: 0.25rem;
    }

    .event-list-name {
        color: #2a3547;
        font-size: 0.875rem;
    }

    .no-events-message {
        text-align: center;
        padding: 3rem 1rem;
        color: #6c757d;
    }

    .no-events-message i {
        font-size: 3rem;
        color: #adb5bd;
        margin-bottom: 1rem;
    }

    .no-events-message p {
        font-size: 1rem;
        margin: 0;
    }

    /* Responsive */
    @media (max-width: 768px) {
        .holiday-tooltip {
            display: none;
        }

        .month-view .calendar-grid {
            display: none;
        }

        .month-list-view {
            display: block;
        }

        .calendar-title {
            font-size: 1.25rem;
        }

        .view-selector .btn {
            padding: 0.4rem 0.8rem;
            font-size: 0.875rem;
        }

        .week-grid,
        .day-grid {
            grid-template-columns: 60px repeat(7, 1fr);
        }
    }

    @media (max-width: 576px) {
        .calendar-header {
            flex-direction: column;
            align-items: stretch;
        }

        .calendar-nav {
            justify-content: center;
        }

        .view-selector {
            justify-content: center;
        }

        .calendar-day-header {
            font-size: 0.65rem;
        }

        .event-item {
            font-size: 0.5rem;
        }
    }
</style>

<div class="calendar-container">
    <div class="calendar-loading" id="calendarLoading">
        <div class="calendar-loading-spinner"></div>
    </div>
    
    <div class="calendar-header">
        <div class="calendar-nav">
            <button class="btn btn-light" id="prevBtn">
                <i class="ti ti-chevron-left"></i>
            </button>
            <button class="btn btn-primary" id="todayBtn">Hoy</button>
            <button class="btn btn-light" id="nextBtn">
                <i class="ti ti-chevron-right"></i>
            </button>
            <h2 class="calendar-title" id="calendarTitle">Diciembre 2025</h2>
        </div>
        <div class="view-selector">
            <button class="btn btn-dark" id="monthViewBtn" data-view="month">Mes</button>
            <button class="btn btn-outline-dark" id="weekViewBtn" data-view="week">Semana</button>
            <button class="btn btn-outline-dark" id="dayViewBtn" data-view="day">Día</button>
        </div>
    </div>

    <!-- Vista Mes -->
    <div id="monthView" class="month-view active">
        <div class="calendar-grid" id="calendarGrid">
            <!-- Los días se generarán con JavaScript -->
        </div>
        <div class="month-list-view" id="monthListView">
            <!-- Vista en lista para móvil -->
        </div>
    </div>

    <!-- Vista Semana -->
    <div id="weekView" class="week-view">
        <div class="week-grid" id="weekGrid">
            <!-- La vista de semana se generará con JavaScript -->
        </div>
    </div>

    <!-- Vista Día -->
    <div id="dayView" class="day-view">
        <div class="day-grid" id="dayGrid">
            <!-- La vista de día se generará con JavaScript -->
        </div>
    </div>
</div>

<!-- Modal de Día Festivo -->
<div class="holiday-modal-overlay" id="holidayModalOverlay">
    <div class="holiday-modal">
        <div class="holiday-modal-header">
            <div class="holiday-modal-icon"></div>
            <h6 class="holiday-modal-title" id="holidayModalTitle">Día Festivo</h6>
        </div>
        <p class="holiday-modal-description" id="holidayModalDescription"></p>
        <button class="holiday-modal-close" onclick="document.getElementById('holidayModalOverlay').classList.remove('active')">Cerrar</button>
    </div>
</div>

<!-- Modal de Evento -->
<div class="modal fade" id="eventModal" tabindex="-1" aria-labelledby="eventModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="eventModalLabel">Detalles del Evento</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="event-modal-content" id="eventModalContent">
                    <!-- Los detalles se generarán con JavaScript -->
                </div>
            </div>
            <div class="modal-footer">
                <?php if ($eliminar_permiso) { ?>
                <button type="button" class="btn btn-link text-danger" id="btnEliminarEventoModal" data-evento-id="" style="margin-right: auto;">
                    <i class="ti ti-trash"></i> Eliminar
                </button>
                <?php } ?>
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cerrar</button>
                <?php if ($editar_permiso) { ?>
                <button type="button" class="btn btn-primary" id="btnEditarEventoModal" data-evento-id="">
                    <i class="ti ti-edit"></i> Editar
                </button>
                <?php } ?>
            </div>
        </div>
    </div>
</div>

<script>
    // Datos de días festivos
    const diasFestivosJSON = [
        {
            fecha: "2025-01-01",
            descripcion: "Año Nuevo"
        },
        {
            fecha: "2025-05-01",
            descripcion: "Día del Trabajo"
        },
        {
            fecha: "2025-12-25",
            descripcion: "Navidad"
        },
        {
            fecha: "2025-12-31",
            descripcion: "Fin de Año"
        },
        {
            fecha: "2025-09-18",
            descripcion: "Día de la Independencia"
        },
        {
            fecha: "2025-09-19",
            descripcion: "Día de las Glorias del Ejército"
        }
    ];

    // Los eventos se cargarán desde el backend

    class Calendar {
        constructor() {
            this.currentDate = new Date();
            this.currentView = 'month';
            this.eventos = []; // Se cargarán desde el backend
            this.diasFestivos = this.parseDiasFestivos(diasFestivosJSON);
            this.meses = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
                          'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
            this.diasSemana = ['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb', 'Dom'];
            this.diasSemanaCompleto = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado', 'Domingo'];
            this.isLoading = false;

            this.init();
        }

        parseEventos(eventos) {
            return eventos.map(evento => ({
                id: evento.id,
                nombre: evento.nombre,
                fechaInicio: new Date(evento.fecha_inicio),
                fechaFin: new Date(evento.fecha_fin),
                ubicacion: evento.ubicacion || '',
                descripcion: evento.descripcion || '',
                imagen: evento.imagen || '',
                color: evento.color || 'event-primary',
                usuario_id: evento.usuario_id
            }));
        }

        async loadEventos() {
            if (this.isLoading) return;
            
            this.isLoading = true;
            
            // Mostrar spinner de carga
            const loadingElement = document.getElementById('calendarLoading');
            if (loadingElement) {
                loadingElement.classList.add('active');
            }
            
            try {
                // Calcular rango de fechas según la vista actual
                let fechaInicio, fechaFin;
                
                if (this.currentView === 'month') {
                    // Buscar por el rango de fechas realmente mostrado en el calendario (puede incluir días de otros meses)
                    const year = this.currentDate.getFullYear();
                    const month = this.currentDate.getMonth();
                    const firstDayOfMonth = new Date(year, month, 1);
                    let startDay = firstDayOfMonth.getDay() - 1;
                    if (startDay === -1) startDay = 6; // Lunes = 0, Domingo = 6

                    // Primer día visible en el calendario (puede ser del mes anterior)
                    fechaInicio = new Date(year, month, 1 - startDay);
                    fechaInicio.setHours(0, 0, 0, 0);

                    // Último día visible en el calendario (puede ser del mes siguiente)
                    // 6 filas de 7 días = 42 días mostrados
                    fechaFin = new Date(fechaInicio);
                    fechaFin.setDate(fechaFin.getDate() + 41);
                    fechaFin.setHours(23, 59, 59, 999);
                } else if (this.currentView === 'week') {
                    // Rango de la semana
                    const weekStart = this.getWeekStart(this.currentDate);
                    fechaInicio = new Date(weekStart);
                    fechaFin = new Date(weekStart);
                    fechaFin.setDate(fechaFin.getDate() + 6);
                    fechaFin.setHours(23, 59, 59);
                } else if (this.currentView === 'day') {
                    // Rango del día actual
                    fechaInicio = new Date(this.currentDate);
                    fechaInicio.setHours(0, 0, 0, 0);
                    fechaFin = new Date(this.currentDate);
                    fechaFin.setHours(23, 59, 59);
                }
                
                // Formatear fechas para el backend (YYYY-MM-DD HH:MM:SS)
                const formatFecha = (date) => {
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    const hours = String(date.getHours()).padStart(2, '0');
                    const minutes = String(date.getMinutes()).padStart(2, '0');
                    const seconds = String(date.getSeconds()).padStart(2, '0');
                    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                };
                
                const params = new URLSearchParams({
                    fecha_inicio: formatFecha(fechaInicio),
                    fecha_fin: formatFecha(fechaFin)
                });
                
                const response = await fetch(`<?= base_url('eventos/listado') ?>?${params}`);
                const data = await response.json();
                
                if (data.success) {
                    this.eventos = this.parseEventos(data.data || []);
                } else {
                    console.error('Error al cargar eventos:', data.message);
                    this.eventos = [];
                }
            } catch (error) {
                console.error('Error al cargar eventos:', error);
                this.eventos = [];
            } finally {
                this.isLoading = false;
                
                // Ocultar spinner de carga
                if (loadingElement) {
                    loadingElement.classList.remove('active');
                }
            }
        }

        parseDiasFestivos(festivos) {
            return festivos.map(festivo => ({
                ...festivo,
                fecha: new Date(festivo.fecha)
            }));
        }

        getHolidayForDate(date) {
            return this.diasFestivos.find(festivo => {
                return festivo.fecha.getDate() === date.getDate() &&
                       festivo.fecha.getMonth() === date.getMonth() &&
                       festivo.fecha.getFullYear() === date.getFullYear();
            });
        }

        showHolidayModal(descripcion) {
            const overlay = document.getElementById('holidayModalOverlay');
            const description = document.getElementById('holidayModalDescription');
            description.textContent = descripcion;
            overlay.classList.add('active');
        }

        init() {
            this.setupEventListeners();
            this.loadEventos().then(() => {
                this.render();
            });
        }

        setupEventListeners() {
            document.getElementById('prevBtn').addEventListener('click', () => this.navigate(-1));
            document.getElementById('nextBtn').addEventListener('click', () => this.navigate(1));
            document.getElementById('todayBtn').addEventListener('click', () => this.goToToday());

            document.querySelectorAll('.view-selector .btn').forEach(btn => {
                btn.addEventListener('click', (e) => this.changeView(e.target.dataset.view));
            });
        }

        navigate(direction) {
            if (this.currentView === 'month') {
                this.currentDate.setMonth(this.currentDate.getMonth() + direction);
            } else if (this.currentView === 'week') {
                this.currentDate.setDate(this.currentDate.getDate() + (direction * 7));
            } else if (this.currentView === 'day') {
                this.currentDate.setDate(this.currentDate.getDate() + direction);
            }
            this.loadEventos().then(() => {
                this.render();
            });
        }

        goToToday() {
            this.currentDate = new Date();
            this.loadEventos().then(() => {
                this.render();
            });
        }

        changeView(view) {
            this.currentView = view;

            // Actualizar botones
            document.querySelectorAll('.view-selector .btn').forEach(btn => {
                if (btn.dataset.view === view) {
                    btn.classList.remove('btn-outline-dark');
                    btn.classList.add('btn-dark');
                } else {
                    btn.classList.remove('btn-dark');
                    btn.classList.add('btn-outline-dark');
                }
            });

            // Mostrar/ocultar vistas
            document.getElementById('monthView').classList.toggle('active', view === 'month');
            document.getElementById('weekView').classList.toggle('active', view === 'week');
            document.getElementById('dayView').classList.toggle('active', view === 'day');

            this.loadEventos().then(() => {
                this.render();
            });
        }

        render() {
            this.updateTitle();

            if (this.currentView === 'month') {
                this.renderMonthView();
            } else if (this.currentView === 'week') {
                this.renderWeekView();
            } else if (this.currentView === 'day') {
                this.renderDayView();
            }
        }

        updateTitle() {
            const title = document.getElementById('calendarTitle');

            if (this.currentView === 'month') {
                title.textContent = `${this.meses[this.currentDate.getMonth()]} ${this.currentDate.getFullYear()}`;
            } else if (this.currentView === 'week') {
                const weekStart = this.getWeekStart(this.currentDate);
                const weekEnd = new Date(weekStart);
                weekEnd.setDate(weekEnd.getDate() + 6);

                title.textContent = `${weekStart.getDate()} ${this.meses[weekStart.getMonth()]} - ${weekEnd.getDate()} ${this.meses[weekEnd.getMonth()]} ${weekEnd.getFullYear()}`;
            } else if (this.currentView === 'day') {
                const dia = this.diasSemanaCompleto[this.currentDate.getDay() === 0 ? 6 : this.currentDate.getDay() - 1];
                title.textContent = `${dia}, ${this.currentDate.getDate()} de ${this.meses[this.currentDate.getMonth()]} ${this.currentDate.getFullYear()}`;
            }
        }

        renderMonthView() {
            const grid = document.getElementById('calendarGrid');
            grid.innerHTML = '';

            // Cabecera con días de la semana
            this.diasSemana.forEach(dia => {
                const header = document.createElement('div');
                header.className = 'calendar-day-header';
                header.textContent = dia;
                grid.appendChild(header);
            });

            // Obtener primer y último día del mes
            const year = this.currentDate.getFullYear();
            const month = this.currentDate.getMonth();
            const firstDay = new Date(year, month, 1);
            const lastDay = new Date(year, month + 1, 0);

            // Ajustar el primer día (lunes = 0)
            let startDay = firstDay.getDay() - 1;
            if (startDay === -1) startDay = 6;

            // Días del mes anterior
            const prevMonthLastDay = new Date(year, month, 0).getDate();
            for (let i = startDay - 1; i >= 0; i--) {
                const day = prevMonthLastDay - i;
                const cell = this.createDayCell(day, true, new Date(year, month - 1, day));
                grid.appendChild(cell);
            }

            // Días del mes actual
            for (let day = 1; day <= lastDay.getDate(); day++) {
                const date = new Date(year, month, day);
                const cell = this.createDayCell(day, false, date);
                grid.appendChild(cell);
            }

            // Días del mes siguiente
            const remainingCells = 42 - grid.children.length + 7; // 42 = 6 semanas * 7 días
            for (let day = 1; day <= remainingCells; day++) {
                const date = new Date(year, month + 1, day);
                const cell = this.createDayCell(day, true, date);
                grid.appendChild(cell);
            }

            // Renderizar vista lista para móvil
            this.renderMonthListView();
        }

        createDayCell(day, otherMonth, date) {
            const cell = document.createElement('div');
            cell.className = 'calendar-day';

            if (otherMonth) {
                cell.classList.add('other-month');
            }

            if (this.isToday(date)) {
                cell.classList.add('today');
            }

            <?php if ($crear_permiso) { ?>
            // Click en el día para crear evento
            cell.addEventListener('click', (e) => {
                // Evitar que se dispare si se hizo clic en un evento
                if (e.target.closest('.event-item')) {
                    return;
                }
                this.openCreateEventModal(date);
            });
            <?php } ?>

            const dayNumber = document.createElement('div');
            dayNumber.className = 'day-number';

            const dayText = document.createElement('span');
            dayText.textContent = day;
            dayNumber.appendChild(dayText);

            // Verificar si es día festivo
            const holiday = this.getHolidayForDate(date);
            if (holiday && !otherMonth) {
                const indicator = document.createElement('span');
                indicator.className = 'holiday-indicator';

                const tooltip = document.createElement('span');
                tooltip.className = 'holiday-tooltip';
                tooltip.textContent = holiday.descripcion;
                indicator.appendChild(tooltip);

                // Click para móvil
                indicator.addEventListener('click', (e) => {
                    e.stopPropagation();
                    if (window.innerWidth <= 768) {
                        this.showHolidayModal(holiday.descripcion);
                    }
                });

                dayNumber.appendChild(indicator);
            }

            cell.appendChild(dayNumber);

            // Agregar eventos del día
            const dayEvents = this.getEventsForDate(date);
            dayEvents.forEach(evento => {
                const eventEl = document.createElement('div');
                eventEl.className = `event-item ${evento.color}`;

                const timeSpan = document.createElement('span');
                timeSpan.className = 'event-time';
                timeSpan.textContent = this.formatTime(evento.fechaInicio) + ' ';

                const nameSpan = document.createElement('span');
                nameSpan.textContent = evento.nombre;

                eventEl.appendChild(timeSpan);
                eventEl.appendChild(nameSpan);

                eventEl.addEventListener('click', (e) => {
                    e.stopPropagation();
                    this.showEventModal(evento);
                });
                cell.appendChild(eventEl);
            });

            return cell;
        }

        renderWeekView() {
            const grid = document.getElementById('weekGrid');
            grid.innerHTML = '';

            const weekStart = this.getWeekStart(this.currentDate);

            // Celda vacía para la esquina
            const corner = document.createElement('div');
            corner.className = 'calendar-day-header';
            grid.appendChild(corner);

            // Cabecera con días de la semana
            for (let i = 0; i < 7; i++) {
                const date = new Date(weekStart);
                date.setDate(date.getDate() + i);

                const header = document.createElement('div');
                header.className = 'calendar-day-header';
                header.innerHTML = `
                    <div>${this.diasSemana[i]}</div>
                    <div style="font-size: 1.2rem; margin-top: 0.25rem;">${date.getDate()}</div>
                `;
                if (this.isToday(date)) {
                    header.style.background = '#e8f4fd';
                }
                grid.appendChild(header);
            }

            // Horas del día (8 AM - 8 PM)
            for (let hour = 8; hour <= 20; hour++) {
                const timeCell = document.createElement('div');
                timeCell.className = 'week-time';
                timeCell.textContent = `${hour}:00`;
                grid.appendChild(timeCell);

                for (let i = 0; i < 7; i++) {
                    const date = new Date(weekStart);
                    date.setDate(date.getDate() + i);
                    date.setHours(hour, 0, 0, 0);

                    const dayCell = document.createElement('div');
                    dayCell.className = 'week-day-cell';

                    // Click en la celda para crear evento
                    dayCell.addEventListener('click', (e) => {
                        if (!e.target.closest('.event-item')) {
                            this.openCreateEventModal(date, hour);
                        }
                    });

                    // Agregar eventos de esta hora
                    const hourEvents = this.getEventsForHour(date, hour);
                    hourEvents.forEach(evento => {
                        const eventEl = document.createElement('div');
                        eventEl.className = `event-item ${evento.color}`;
                        eventEl.textContent = evento.nombre;
                        eventEl.addEventListener('click', (e) => {
                            e.stopPropagation();
                            this.showEventModal(evento);
                        });
                        dayCell.appendChild(eventEl);
                    });

                    grid.appendChild(dayCell);
                }
            }
        }

        renderDayView() {
            const grid = document.getElementById('dayGrid');
            grid.innerHTML = '';

            // Horas del día
            for (let hour = 0; hour < 24; hour++) {
                const timeCell = document.createElement('div');
                timeCell.className = 'week-time';
                timeCell.textContent = `${hour.toString().padStart(2, '0')}:00`;
                grid.appendChild(timeCell);

                const date = new Date(this.currentDate);
                date.setHours(hour, 0, 0, 0);

                const dayCell = document.createElement('div');
                dayCell.className = 'week-day-cell';
                dayCell.style.minHeight = '80px';

                // Click en la celda para crear evento
                dayCell.addEventListener('click', (e) => {
                    if (!e.target.closest('.event-item')) {
                        this.openCreateEventModal(date, hour);
                    }
                });

                // Agregar eventos de esta hora
                const hourEvents = this.getEventsForHour(date, hour);
                hourEvents.forEach(evento => {
                    const eventEl = document.createElement('div');
                    eventEl.className = `event-item ${evento.color}`;
                    eventEl.textContent = `${this.formatTime(evento.fechaInicio)} - ${evento.nombre}`;
                    eventEl.addEventListener('click', (e) => {
                        e.stopPropagation();
                        this.showEventModal(evento);
                    });
                    dayCell.appendChild(eventEl);
                });

                grid.appendChild(dayCell);
            }
        }

        getWeekStart(date) {
            const d = new Date(date);
            const day = d.getDay();
            const diff = day === 0 ? -6 : 1 - day; // Ajustar para que lunes sea el primer día
            d.setDate(d.getDate() + diff);
            d.setHours(0, 0, 0, 0);
            return d;
        }

        isToday(date) {
            const today = new Date();
            return date.getDate() === today.getDate() &&
                   date.getMonth() === today.getMonth() &&
                   date.getFullYear() === today.getFullYear();
        }

        getEventsForDate(date) {
            return this.eventos.filter(evento => {
                const eventDate = new Date(evento.fechaInicio);
                return eventDate.getDate() === date.getDate() &&
                       eventDate.getMonth() === date.getMonth() &&
                       eventDate.getFullYear() === date.getFullYear();
            });
        }

        getEventsForHour(date, hour) {
            return this.eventos.filter(evento => {
                const eventDate = new Date(evento.fechaInicio);
                return eventDate.getDate() === date.getDate() &&
                       eventDate.getMonth() === date.getMonth() &&
                       eventDate.getFullYear() === date.getFullYear() &&
                       eventDate.getHours() === hour;
            });
        }

        formatTime(date) {
            let hours = date.getHours();
            const minutes = date.getMinutes().toString().padStart(2, '0');
            const ampm = hours >= 12 ? 'PM' : 'AM';
            hours = hours % 12;
            hours = hours ? hours : 12; // 0 se convierte en 12
            return `${hours}:${minutes}${ampm}`;
        }

        formatDate(date) {
            const dayOfWeek = this.diasSemanaCompleto[date.getDay() === 0 ? 6 : date.getDay() - 1];
            return `${dayOfWeek} ${date.getDate()} de ${this.meses[date.getMonth()]} ${date.getFullYear()}`;
        }

        renderMonthListView() {
            const listView = document.getElementById('monthListView');
            listView.innerHTML = '';

            const year = this.currentDate.getFullYear();
            const month = this.currentDate.getMonth();
            const firstDay = new Date(year, month, 1);
            const lastDay = new Date(year, month + 1, 0);

            // Recopilar todos los días con eventos
            const daysWithEvents = [];
            for (let day = 1; day <= lastDay.getDate(); day++) {
                const date = new Date(year, month, day);
                const dayEvents = this.getEventsForDate(date);
                if (dayEvents.length > 0) {
                    daysWithEvents.push({ date, events: dayEvents });
                }
            }

            // Si no hay eventos, mostrar mensaje
            if (daysWithEvents.length === 0) {
                listView.innerHTML = `
                    <div class="no-events-message">
                        <i class="ti ti-calendar-off"></i>
                        <p>No hay eventos agendados para este mes</p>
                    </div>
                `;
                return;
            }

            // Renderizar cada día con eventos
            daysWithEvents.forEach(({ date, events }) => {
                const dayCard = document.createElement('div');
                dayCard.className = 'event-day-card';

                const dayOfWeek = this.diasSemanaCompleto[date.getDay() === 0 ? 6 : date.getDay() - 1];
                const dayNumber = date.getDate();
                const monthName = this.meses[date.getMonth()];
                const yearNum = date.getFullYear();
                const holiday = this.getHolidayForDate(date);

                let headerContent = `
                    <div class="event-day-header">
                        <span class="event-day-name">${dayOfWeek}</span>
                        <span class="event-day-date">${dayNumber} de ${monthName}, ${yearNum}</span>
                    </div>
                `;

                if (holiday) {
                    headerContent += `
                        <div class="event-list-item event-danger" style="border-left-color: #fa896b; cursor: pointer;" onclick="document.getElementById('holidayModalOverlay').classList.add('active'); document.getElementById('holidayModalDescription').textContent = '${holiday.descripcion}';">
                            <div class="event-list-time">Día Festivo</div>
                            <div class="event-list-name">${holiday.descripcion}</div>
                        </div>
                    `;
                }

                dayCard.innerHTML = headerContent;

                events.forEach(evento => {
                    const eventItem = document.createElement('div');
                    eventItem.className = `event-list-item ${evento.color}`;
                    eventItem.innerHTML = `
                        <div class="event-list-time">${this.formatTime(evento.fechaInicio)}</div>
                        <div class="event-list-name">${evento.nombre}</div>
                    `;
                    eventItem.addEventListener('click', () => this.showEventModal(evento));
                    dayCard.appendChild(eventItem);
                });

                listView.appendChild(dayCard);
            });
        }

        showEventModal(evento) {
            const modal = new bootstrap.Modal(document.getElementById('eventModal'));
            const content = document.getElementById('eventModalContent');

            // Guardar datos del evento en los botones
            const btnEditar = document.getElementById('btnEditarEventoModal');
            const btnEliminar = document.getElementById('btnEliminarEventoModal');
            
            if (btnEditar && evento.id) {
                btnEditar.dataset.eventoId = evento.id;
            }
            if (btnEliminar && evento.id) {
                btnEliminar.dataset.eventoId = evento.id;
            }

            // Guardar evento en window para acceso global
            window.eventoActualGlobal = evento;

            let imagenHtml = '';
            if (evento.imagen) {
                imagenHtml = `
                    <div class="event-detail">
                        <i class="ti ti-photo"></i>
                        <div class="event-detail-content">
                            <div class="event-detail-label">Imagen</div>
                            <div class="event-detail-text">
                                <img src="<?= base_url() ?>${evento.imagen}" 
                                     alt="${evento.nombre}" 
                                     style="max-width: 100%; border-radius: 8px; margin-top: 0.5rem;">
                            </div>
                        </div>
                    </div>
                `;
            }

            let descripcionHtml = '';
            if (evento.descripcion) {
                descripcionHtml = `
                    <div class="event-detail">
                        <i class="ti ti-file-description"></i>
                        <div class="event-detail-content">
                            <div class="event-detail-label">Descripción</div>
                            <div class="event-detail-text">${evento.descripcion}</div>
                        </div>
                    </div>
                `;
            }

            content.innerHTML = `
                <div class="event-detail">
                    <i class="ti ti-calendar-event"></i>
                    <div class="event-detail-content">
                        <div class="event-detail-label">Evento</div>
                        <div class="event-detail-text">${evento.nombre}</div>
                    </div>
                </div>
                ${descripcionHtml}
                ${imagenHtml}
                <div class="event-detail">
                    <i class="ti ti-clock"></i>
                    <div class="event-detail-content">
                        <div class="event-detail-label">Inicio</div>
                        <div class="event-detail-text">${this.formatDate(evento.fechaInicio)} - ${this.formatTime(evento.fechaInicio)}</div>
                    </div>
                </div>
                <div class="event-detail">
                    <i class="ti ti-clock-stop"></i>
                    <div class="event-detail-content">
                        <div class="event-detail-label">Fin</div>
                        <div class="event-detail-text">${this.formatDate(evento.fechaFin)} - ${this.formatTime(evento.fechaFin)}</div>
                    </div>
                </div>
                <div class="event-detail">
                    <i class="ti ti-map-pin"></i>
                    <div class="event-detail-content">
                        <div class="event-detail-label">Ubicación</div>
                        <div class="event-detail-text">${evento.ubicacion}</div>
                    </div>
                </div>
            `;

            modal.show();
        }

        openCreateEventModal(date, hour = null) {
            // Formatear fecha y hora para datetime-local input
            const fechaInicio = new Date(date);

            if (hour !== null) {
                // Vista semana o día: usar la hora específica
                fechaInicio.setHours(hour, 0, 0, 0);
            } else {
                // Vista mes: usar hora actual redondeada
                const now = new Date();
                fechaInicio.setHours(now.getHours(), 0, 0, 0);
            }

            // Fecha fin: una hora después
            const fechaFin = new Date(fechaInicio);
            fechaFin.setHours(fechaFin.getHours() + 1);

            // Formatear para input datetime-local (YYYY-MM-DDTHH:mm)
            const formatForInput = (d) => {
                const year = d.getFullYear();
                const month = String(d.getMonth() + 1).padStart(2, '0');
                const day = String(d.getDate()).padStart(2, '0');
                const hours = String(d.getHours()).padStart(2, '0');
                const minutes = String(d.getMinutes()).padStart(2, '0');
                return `${year}-${month}-${day}T${hours}:${minutes}`;
            };

            // Llenar los campos del modal
            document.getElementById('fechaInicio').value = formatForInput(fechaInicio);
            document.getElementById('fechaFin').value = formatForInput(fechaFin);

            // Abrir el modal
            const modal = new bootstrap.Modal(document.getElementById('modalNuevoEvento'));
            modal.show();
        }
    }

    // Inicializar el calendario cuando el DOM esté listo
    document.addEventListener('DOMContentLoaded', function() {
        new Calendar();
    });
</script>