<!DOCTYPE html>
<html lang="es" class="{{ 'dark' if tema == 1 else '' }}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>UTRAU - Agenda Operativa</title>
    
    <!-- Favicon y App Icons -->
    <link rel="apple-touch-icon" sizes="180x180" href="{{ url_for('static', filename='apple-touch-icon.png') }}">
    <link rel="icon" type="image/png" sizes="32x32" href="{{ url_for('static', filename='favicon-32x32.png') }}">
    <link rel="icon" type="image/png" sizes="16x16" href="{{ url_for('static', filename='favicon-16x16.png') }}">
    <link rel="manifest" href="{{ url_for('static', filename='site.webmanifest') }}">
    <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">

    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.14/index.global.min.js'></script>
    <script>
        tailwind.config = { darkMode: 'class', theme: { extend: {} } }
    </script>
    <style>
        body { margin: 0; padding: 0; overflow: hidden; }
        .fc-theme-standard td, .fc-theme-standard th { border-color: rgba(148, 163, 184, 0.2); }
        .fc-col-header-cell { padding: 12px 0 !important; font-size: 12px; text-transform: uppercase; font-weight: 900; }
        .fc-event { border: none !important; border-radius: 6px !important; padding: 2px 4px; box-shadow: 0 1px 2px rgba(0,0,0,0.1); cursor: pointer; transition: transform 0.1s; }
        .fc-day-today { background-color: rgba(59, 130, 246, 0.05) !important; }
        .fc-button-primary { background-color: white !important; color: #334155 !important; border: 1px solid #cbd5e1 !important; font-weight: bold !important; text-transform: capitalize !important; border-radius: 8px !important; transition: all 0.2s !important; }
        .fc-button-primary:hover { background-color: #f1f5f9 !important; }
        .fc-button-active { background-color: #e2e8f0 !important; box-shadow: inset 0 2px 4px rgba(0,0,0,0.05) !important; }
        .dark .fc-button-primary { background-color: #1e293b !important; color: #cbd5e1 !important; border-color: #334155 !important; }
        .dark .fc-button-primary:hover { background-color: #334155 !important; }
        .dark .fc-button-active { background-color: #0f172a !important; }
        .dark .fc-col-header-cell, .dark .fc-daygrid-day-number { color: #94a3b8; }
        #calendar-container { height: calc(100vh - 65px); }

        /* ARREGLOS MOBILE FIRST PARA LA CABECERA DEL CALENDARIO */
        .fc-header-toolbar { flex-direction: column !important; gap: 10px !important; align-items: center !important; margin-bottom: 1rem !important; }
        .fc-toolbar-chunk { display: flex; flex-wrap: wrap; justify-content: center; gap: 5px; width: 100%; }
        .fc-toolbar-title { font-size: 1.1rem !important; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%; }
        @media (min-width: 768px) {
            .fc-header-toolbar { flex-direction: row !important; justify-content: space-between !important; }
            .fc-toolbar-chunk { width: auto; }
            .fc-toolbar-title { font-size: 1.5rem !important; }
        }
    </style>
</head>
<body class="bg-white dark:bg-slate-950 text-slate-900 dark:text-slate-100 transition-colors duration-300">

    <nav class="bg-slate-900 border-b border-slate-800 p-4 flex justify-between items-center shadow-md text-white h-[65px] sticky top-0 z-40">
        <div class="flex items-center space-x-3">
            <span class="font-black text-blue-500">UTRAU <span class="text-slate-400 font-bold hidden sm:inline">| AGENDA</span></span>
        </div>
        <div class="flex items-center space-x-4">
            <span id="loading-indicator" class="hidden text-xs font-bold text-amber-400 uppercase animate-pulse mr-2"><i class="fa-solid fa-rotate animate-spin mr-1"></i> Sync...</span>
            <a href="{{ url_for('index') }}" class="text-xs font-bold uppercase text-slate-400 hover:text-white transition"><i class="fa-solid fa-arrow-left mr-2"></i>Volver</a>
        </div>
    </nav>

    <div id="calendar-container" class="w-full p-2 sm:p-4 bg-slate-50 dark:bg-slate-900 overflow-y-auto">
        <div id="calendar" class="w-full bg-white dark:bg-slate-950 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-800 p-3"></div>
    </div>

    <!-- MODAL NUEVO / EDITAR EVENTO -->
    <div id="modalNuevo" class="fixed inset-0 bg-slate-900/60 z-50 hidden items-center justify-center backdrop-blur-sm p-4">
        <div class="bg-white dark:bg-slate-900 rounded-3xl shadow-2xl w-full max-w-md border border-slate-200 dark:border-slate-800 flex flex-col max-h-[90vh]">
            <div class="p-5 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center bg-slate-50 dark:bg-slate-800/50 rounded-t-3xl">
                <h3 id="modalNuevoTitulo" class="font-black uppercase tracking-tight text-blue-600 dark:text-blue-400"><i class="fa-solid fa-calendar-plus mr-2"></i>Agendar</h3>
                <button onclick="cerrarModal('modalNuevo')" class="text-slate-400 hover:text-red-500 transition"><i class="fa-solid fa-xmark text-xl"></i></button>
            </div>

            <div class="p-6 overflow-y-auto flex-1 space-y-4">
                <input type="hidden" id="ev_id_edit">
                <div id="alertaSemaforo" class="hidden p-3 rounded-lg text-xs font-bold bg-red-100 text-red-700"></div>

                <div>
                    <input type="text" id="ev_titulo" placeholder="Título de la actividad" class="w-full px-4 py-3 text-lg font-black rounded-xl border-2 border-slate-200 dark:border-slate-700 bg-transparent focus:border-blue-500 outline-none">
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-[10px] font-black text-slate-500 mb-1 uppercase">Inicio</label>
                        <input type="datetime-local" id="ev_inicio" class="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-sm font-bold outline-none focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-[10px] font-black text-slate-500 mb-1 uppercase">Fin</label>
                        <input type="datetime-local" id="ev_fin" class="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-sm font-bold outline-none focus:border-blue-500">
                    </div>
                </div>

                <div class="flex items-center space-x-2">
                    <input type="checkbox" id="ev_todo_dia" class="w-4 h-4 accent-blue-600">
                    <label for="ev_todo_dia" class="text-xs font-bold text-slate-600 dark:text-slate-400 cursor-pointer">Jornada completa</label>
                </div>

                <div>
                    <label class="block text-[10px] font-black text-slate-500 mb-1 uppercase">Expediente (Opcional)</label>
                    <select id="ev_conflicto" class="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-sm font-bold outline-none text-red-600">
                        <option value="" class="text-blue-600">-- Personal / Interna (Azul) --</option>
                        {% for c in conflictos %}
                        <option value="{{ c.id_conflicto }}" class="text-black">Exp. #{{ c.id_conflicto }} - {{ c.titulo }}</option>
                        {% endfor %}
                    </select>
                </div>

                <div>
                    <label class="block text-[10px] font-black text-slate-500 mb-1 uppercase">Visibilidad</label>
                    <select id="ev_visibilidad" class="w-full px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-sm font-bold outline-none">
                        <option value="Solo Participantes">Solo Participantes (Resto ve "Ocupado")</option>
                        <option value="Institucional">Público para el sindicato</option>
                        <option value="Privado">Totalmente Privado</option>
                    </select>
                </div>

                <div>
                    <label class="block text-[10px] font-black text-slate-500 mb-1 uppercase">Compañeros Invitados</label>
                    <div class="border border-slate-200 dark:border-slate-700 rounded-lg p-2 max-h-32 overflow-y-auto bg-slate-50 dark:bg-slate-800/50 space-y-1">
                        {% for u in lista_usuarios %}
                        <label class="flex items-center space-x-2 p-1 hover:bg-white dark:hover:bg-slate-700 rounded cursor-pointer transition">
                            <input type="checkbox" value="{{ u.id_usuario }}" class="check-participante w-4 h-4 accent-emerald-500">
                            {% if u.path_foto %}
                            <img src="{{ u.path_foto }}" class="w-5 h-5 rounded-full object-cover">
                            {% else %}
                            <div class="w-5 h-5 rounded-full bg-slate-300 dark:bg-slate-600 text-slate-500 dark:text-slate-300 flex items-center justify-center text-[10px] font-bold">{{ u.nombre_completo[0:1] }}</div>
                            {% endif %}
                            <span class="text-xs font-bold">{{ u.nombre_completo }}</span>
                        </label>
                        {% endfor %}
                    </div>
                </div>

                <div>
                    <textarea id="ev_desc" rows="2" placeholder="Notas adicionales..." class="w-full px-4 py-3 text-sm font-medium rounded-xl border border-slate-200 dark:border-slate-700 bg-transparent focus:border-blue-500 outline-none"></textarea>
                </div>
            </div>

            <div class="p-4 border-t border-slate-100 dark:border-slate-800 flex space-x-2">
                <button type="button" onclick="verificarChoques()" class="w-1/3 bg-slate-200 dark:bg-slate-800 text-slate-700 dark:text-slate-300 font-black py-3 rounded-xl transition uppercase text-[10px] shadow-sm"><i class="fa-solid fa-traffic-light"></i></button>
                <button onclick="guardarEvento()" class="w-2/3 bg-blue-600 hover:bg-blue-700 text-white font-black py-3 rounded-xl transition uppercase tracking-widest text-xs shadow-md">Guardar</button>
            </div>
        </div>
    </div>

    <!-- MODAL VER -->
    <div id="modalVer" class="fixed inset-0 bg-slate-900/60 z-50 hidden items-center justify-center backdrop-blur-sm p-4">
        <div class="bg-white dark:bg-slate-900 rounded-3xl shadow-2xl w-full max-w-md border border-slate-200 dark:border-slate-800 overflow-hidden flex flex-col max-h-[90vh]">
            <div class="p-6 overflow-y-auto">
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <span id="ver_estado_badge" class="px-2 py-1 rounded text-[10px] font-black uppercase tracking-widest"></span>
                        <h3 id="ver_titulo" class="text-xl font-black mt-2 leading-tight"></h3>
                    </div>
                    <button onclick="cerrarModal('modalVer')" class="text-slate-400 hover:text-red-500 mt-1"><i class="fa-solid fa-xmark text-xl"></i></button>
                </div>

                <div class="space-y-3 mb-6">
                    <p class="text-sm font-medium text-slate-600 dark:text-slate-400"><i class="fa-regular fa-clock w-5 text-center text-blue-500"></i> <span id="ver_fecha"></span></p>
                    <p class="text-sm font-medium text-slate-600 dark:text-slate-400"><i class="fa-solid fa-user w-5 text-center text-blue-500"></i> Creador: <span id="ver_creador" class="font-bold"></span></p>
                    <p class="text-sm font-medium text-slate-600 dark:text-slate-400"><i class="fa-solid fa-users w-5 text-center text-blue-500"></i> <span id="ver_participantes" class="font-bold"></span> invitados</p>
                    <div id="caja_descripcion" class="mt-4 p-3 bg-slate-50 dark:bg-slate-800 rounded-lg text-sm hidden">
                        <p id="ver_desc" class="whitespace-pre-line"></p>
                    </div>
                </div>

                <div id="panel_autor" class="pt-4 border-t border-slate-200 dark:border-slate-700 flex space-x-2 hidden mb-4">
                    <button onclick="cargarParaEditar()" class="flex-1 bg-amber-100 text-amber-700 hover:bg-amber-600 hover:text-white font-black py-2 rounded-xl transition text-xs uppercase border border-amber-200 shadow-sm"><i class="fa-solid fa-pen mr-1"></i> Modificar</button>
                </div>

                {% if user_rol >= 3 %}
                <div id="panel_ejecutivo" class="pt-4 border-t border-slate-200 dark:border-slate-700 flex space-x-2 hidden">
                    <input type="hidden" id="ver_id_evento">
                    <button onclick="cambiarEstadoEvento('Fijado')" class="flex-1 bg-emerald-100 text-emerald-700 hover:bg-emerald-600 hover:text-white font-black py-2 rounded-xl transition text-xs uppercase border border-emerald-200 shadow-sm"><i class="fa-solid fa-lock mr-1"></i> Sellar (Fijar)</button>
                </div>
                {% endif %}
            </div>

            <div class="bg-blue-50 dark:bg-blue-900/10 p-3 text-center border-t border-blue-100 mt-auto">
                <button onclick="abrirForo()" id="btn_foro" class="text-[10px] font-black text-blue-600 uppercase tracking-widest w-full"><i class="fa-solid fa-comments mr-2"></i>Foro Privado</button>
            </div>
        </div>
    </div>

    <!-- MODAL FORO / CHAT CON DICTADO -->
    <div id="modalForo" class="fixed inset-0 bg-slate-900/60 z-50 hidden items-center justify-center backdrop-blur-sm p-4">
        <div class="bg-white dark:bg-slate-900 rounded-3xl shadow-2xl w-full max-w-md border border-slate-200 dark:border-slate-800 flex flex-col h-[70vh]">
            <div class="p-5 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center bg-blue-50 dark:bg-blue-900/20 rounded-t-3xl">
                <h3 class="font-black uppercase tracking-tight text-blue-600 dark:text-blue-400"><i class="fa-solid fa-comments mr-2"></i>Foro Privado</h3>
                <button onclick="cerrarModal('modalForo')" class="text-slate-400 hover:text-red-500"><i class="fa-solid fa-xmark text-xl"></i></button>
            </div>
            <div id="cuerpoForo" class="flex-1 overflow-y-auto p-4 space-y-3 bg-slate-50 dark:bg-slate-950">
            </div>
            <div class="p-3 bg-white dark:bg-slate-900 border-t border-slate-200 dark:border-slate-800 rounded-b-3xl">
                <form onsubmit="enviarMensajeForo(event)" class="flex items-center space-x-2">
                    <input type="hidden" id="foro_id_evento">
                    <button type="button" id="btn-dictar-foro" onclick="iniciarDictadoForo()" class="bg-slate-200 dark:bg-slate-800 text-slate-600 dark:text-slate-400 hover:text-red-500 p-3 rounded-xl transition" title="Dictar por voz">
                        <i id="icono-mic-foro" class="fa-solid fa-microphone"></i>
                    </button>
                    <input type="text" id="foro_mensaje" placeholder="Mensaje..." required class="flex-1 px-4 py-2 rounded-xl border border-slate-300 dark:border-slate-700 bg-transparent text-sm outline-none focus:border-blue-500">
                    <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-xl transition"><i class="fa-solid fa-paper-plane"></i></button>
                </form>
            </div>
        </div>
    </div>

    <!-- POP-UP DE NOTIFICACIONES -->
    <div id="modalNotificacion" class="fixed inset-0 bg-red-900/80 z-[100] hidden items-center justify-center backdrop-blur-md p-4 transition-all">
        <div class="bg-white dark:bg-slate-900 rounded-3xl shadow-2xl w-full max-w-sm border-2 border-red-500 flex flex-col overflow-hidden transform scale-100">
            <div class="bg-red-500 p-4 text-center">
                <i class="fa-solid fa-bell text-4xl text-white animate-bounce"></i>
                <h3 class="text-lg font-black text-white uppercase mt-2">Aviso de Agenda</h3>
            </div>
            <div id="listaNotificaciones" class="p-6 text-center space-y-3 max-h-64 overflow-y-auto text-sm font-bold text-slate-700 dark:text-slate-300">
            </div>
            <div class="p-4 bg-slate-50 border-t border-slate-200 text-center">
                <button onclick="marcarNotificacionesLeidas()" class="w-full bg-red-600 text-white font-black py-3 rounded-xl uppercase tracking-wider shadow-md">ENTERADO</button>
            </div>
        </div>
    </div>
    <audio id="audioAlerta" src="https://assets.mixkit.co/active_storage/sfx/2869/2869-preview.mp3" preload="auto"></audio>

    <script>
        const ROL_USUARIO = {{ user_rol }};
        const USER_ID = {{ user_id }};
        let calendario;
        let eventoActual = null;

        // DICTADO POR VOZ EN FORO
        function iniciarDictadoForo() {
            if (!('webkitSpeechRecognition' in window)) {
                alert("Tu navegador no soporta el dictado por voz. Usa Chrome.");
                return;
            }
            const recognition = new webkitSpeechRecognition();
            recognition.lang = 'es-UY';
            const btnMic = document.getElementById('btn-dictar-foro');
            const iconoMic = document.getElementById('icono-mic-foro');
            const input = document.getElementById('foro_mensaje');

            recognition.onstart = function() {
                iconoMic.classList.remove('fa-microphone');
                iconoMic.classList.add('fa-microphone-lines', 'fa-beat-fade');
                btnMic.classList.add('text-red-600');
            };
            recognition.onresult = function(e) {
                input.value += (input.value ? ' ' : '') + e.results[0][0].transcript;
            };
            recognition.onerror = function() { alert("Error en el micrófono."); };
            recognition.onend = function() {
                iconoMic.classList.remove('fa-microphone-lines', 'fa-beat-fade');
                iconoMic.classList.add('fa-microphone');
                btnMic.classList.remove('text-red-600');
                input.focus();
            };
            recognition.start();
        }

        // CARGA INICIAL
        document.addEventListener('DOMContentLoaded', () => {
            fetch('/agenda/notificaciones/pendientes')
            .then(res => res.json())
            .then(data => {
                if (data.length > 0) {
                    let lista = document.getElementById('listaNotificaciones');
                    lista.innerHTML = data.map(n => `<p class="border-b pb-2">${n.mensaje}</p>`).join('');
                    abrirModal('modalNotificacion');
                    document.getElementById('audioAlerta').play().catch(e => console.log('Audio bloqueado'));
                }
            });
        });

        function marcarNotificacionesLeidas() {
            fetch('/agenda/notificaciones/leer', { method: 'POST' }).then(() => cerrarModal('modalNotificacion'));
        }

        document.addEventListener('DOMContentLoaded', function() {
            const calendarEl = document.getElementById('calendar');
            const loadingEl = document.getElementById('loading-indicator');

            calendario = new FullCalendar.Calendar(calendarEl, {
                locale: 'es',
                initialView: window.innerWidth < 768 ? 'listMonth' : 'dayGridMonth',
                headerToolbar: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
                },
                buttonText: { today: 'Hoy', month: 'Mes', week: 'Semana', day: 'Día', list: 'Lista' },
                navLinks: true, editable: false, selectable: (ROL_USUARIO >= 2), selectMirror: true, dayMaxEvents: true,
                events: '/agenda/api/eventos',
                loading: function(isLoading) { isLoading ? loadingEl.classList.remove('hidden') : loadingEl.classList.add('hidden'); },
                
                select: function(info) {
                    if (ROL_USUARIO < 2) return;
                    const formatInput = (dateObj) => {
                        let tzoffset = (new Date()).getTimezoneOffset() * 60000;
                        return (new Date(dateObj - tzoffset)).toISOString().slice(0, 16);
                    };
                    document.getElementById('modalNuevoTitulo').innerHTML = '<i class="fa-solid fa-calendar-plus mr-2"></i>Agendar Evento';
                    document.getElementById('ev_id_edit').value = '';
                    document.getElementById('ev_titulo').value = '';
                    document.getElementById('ev_desc').value = '';
                    document.getElementById('ev_conflicto').value = '';
                    document.querySelectorAll('.check-participante:checked').forEach(c => c.checked = false);
                    document.getElementById('ev_inicio').value = formatInput(info.start);
                    document.getElementById('ev_fin').value = formatInput(info.end);
                    document.getElementById('ev_todo_dia').checked = info.allDay;
                    document.getElementById('alertaSemaforo').classList.add('hidden');
                    abrirModal('modalNuevo');
                },

                eventClick: function(info) {
                    const ev = info.event;
                    const props = ev.extendedProps;
                    eventoActual = ev;
                    if (ev.title === 'Ocupado' && props.visibilidad === 'Privado') return;
                    document.getElementById('ver_titulo').innerText = ev.title;
                    let fechaStr = ev.start.toLocaleDateString('es-UY', { weekday: 'long', month: 'long', day: 'numeric', hour: '2-digit', minute:'2-digit' });
                    if (ev.end && !ev.allDay) fechaStr += " hasta " + ev.end.toLocaleTimeString('es-UY', {hour: '2-digit', minute:'2-digit'});
                    document.getElementById('ver_fecha').innerText = ev.allDay ? "Jornada Completa (" + ev.start.toLocaleDateString() + ")" : fechaStr;
                    document.getElementById('ver_creador').innerText = props.creador;
                    document.getElementById('ver_participantes').innerText = props.participantes;
                    
                    if(props.descripcion) { document.getElementById('ver_desc').innerText = props.descripcion; document.getElementById('caja_descripcion').classList.remove('hidden'); }
                    else { document.getElementById('caja_descripcion').classList.add('hidden'); }
                    
                    let badge = document.getElementById('ver_estado_badge');
                    badge.innerText = props.estado;
                    badge.className = "px-2 py-1 rounded text-[10px] font-black uppercase tracking-widest text-white " + (props.estado === 'Fijado' ? 'bg-emerald-500' : (props.estado === 'Propuesto' ? 'bg-blue-500 animate-pulse' : 'bg-slate-500'));
                    
                    let panelAutor = document.getElementById('panel_autor');
                    if (panelAutor) {
                        if (props.estado === 'Propuesto' && (props.creador_id === USER_ID || ROL_USUARIO >= 3)) panelAutor.classList.remove('hidden');
                        else panelAutor.classList.add('hidden');
                    }
                    
                    let panelEjecutivo = document.getElementById('panel_ejecutivo');
                    if (panelEjecutivo) {
                        if (props.estado === 'Propuesto' && ROL_USUARIO >= 3) { document.getElementById('ver_id_evento').value = ev.id; panelEjecutivo.classList.remove('hidden'); }
                        else panelEjecutivo.classList.add('hidden');
                    }
                    abrirModal('modalVer');
                }
            });
            calendario.render();
        });

        function abrirModal(id) { document.getElementById(id).classList.remove('hidden'); document.getElementById(id).classList.add('flex'); }
        function cerrarModal(id) { document.getElementById(id).classList.add('hidden'); document.getElementById(id).classList.remove('flex'); }

        function verificarChoques() {
            let usuarios = Array.from(document.querySelectorAll('.check-participante:checked')).map(c => c.value);
            let f_inicio = document.getElementById('ev_inicio').value;
            let f_fin = document.getElementById('ev_fin').value;
            let alerta = document.getElementById('alertaSemaforo');

            if (usuarios.length === 0 || !f_inicio || !f_fin) return alert("Seleccioná fechas y al menos un participante.");

            fetch('/agenda/verificar_disponibilidad', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({usuarios: usuarios, fecha_inicio: f_inicio, fecha_fin: f_fin})
            }).then(res => res.json()).then(data => {
                alerta.classList.remove('hidden');
                if (data.ocupados.length > 0) {
                    alerta.classList.replace('bg-emerald-100', 'bg-red-100'); alerta.classList.replace('text-emerald-700', 'text-red-700');
                    alerta.innerHTML = "<strong>Choque:</strong> Ocupados: " + data.ocupados.join(", ");
                } else {
                    alerta.classList.replace('bg-red-100', 'bg-emerald-100'); alerta.classList.replace('text-red-700', 'text-emerald-700');
                    alerta.innerHTML = "<strong>OK:</strong> Todos disponibles.";
                }
            });
        }

        function cargarParaEditar() {
            cerrarModal('modalVer');
            document.getElementById('modalNuevoTitulo').innerHTML = '<i class="fa-solid fa-pen mr-2"></i>Modificar Agenda';
            document.getElementById('ev_id_edit').value = eventoActual.id;
            document.getElementById('ev_titulo').value = eventoActual.title;
            const formatInput = (dateObj) => { if(!dateObj) return ''; let tzoffset = (new Date()).getTimezoneOffset() * 60000; return (new Date(dateObj - tzoffset)).toISOString().slice(0, 16); };
            document.getElementById('ev_inicio').value = formatInput(eventoActual.start);
            document.getElementById('ev_fin').value = formatInput(eventoActual.end);
            document.getElementById('ev_todo_dia').checked = eventoActual.allDay;
            document.getElementById('ev_visibilidad').value = eventoActual.extendedProps.visibilidad;
            document.getElementById('ev_desc').value = eventoActual.extendedProps.descripcion;
            document.getElementById('ev_conflicto').value = eventoActual.extendedProps.id_conflicto || '';
            document.getElementById('alertaSemaforo').classList.add('hidden');
            abrirModal('modalNuevo');
        }

        async function guardarEvento() {
            const id_evento = document.getElementById('ev_id_edit').value;
            const titulo = document.getElementById('ev_titulo').value;
            const start = document.getElementById('ev_inicio').value;
            const end = document.getElementById('ev_fin').value;

            if(!titulo || !start || !end) return alert("Por favor completá Título y Fechas.");

            const payload = {
                id_evento: id_evento, titulo: titulo, start: start, end: end,
                allDay: document.getElementById('ev_todo_dia').checked,
                visibilidad: document.getElementById('ev_visibilidad').value,
                descripcion: document.getElementById('ev_desc').value,
                id_conflicto: document.getElementById('ev_conflicto').value,
                participantes: Array.from(document.querySelectorAll('.check-participante:checked')).map(c => c.value)
            };

            try {
                let res = await fetch('/agenda/api/eventos', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload) });
                let data = await res.json();
                if(data.success) { cerrarModal('modalNuevo'); calendario.refetchEvents(); } 
                else { alert("Error: " + data.error); }
            } catch(e) { alert("Fallo de conexión."); }
        }

        async function cambiarEstadoEvento(nuevo_estado) {
            const id = document.getElementById('ver_id_evento').value;
            if(!id) return;
            if(!confirm(`¿Sellar esta reunión como ${nuevo_estado}?`)) return;

            try {
                let res = await fetch('/agenda/api/eventos/estado', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({id_evento: id, estado: nuevo_estado}) });
                let data = await res.json();
                if(data.success) { cerrarModal('modalVer'); calendario.refetchEvents(); } 
                else { alert("Error: " + data.error); }
            } catch(e) { alert("Fallo de conexión."); }
        }

        function abrirForo() {
            if(!eventoActual) return;
            document.getElementById('foro_id_evento').value = eventoActual.id;
            cerrarModal('modalVer');
            abrirModal('modalForo');
            cargarMensajesForo();
        }

        function cargarMensajesForo() {
            let id_evento = document.getElementById('foro_id_evento').value;
            fetch('/agenda/foro/' + id_evento)
            .then(res => { if(res.status === 403) throw new Error("Acceso Restringido."); return res.json(); })
            .then(data => {
                let html = '';
                data.forEach(m => {
                    html += `<div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 p-3 rounded-2xl shadow-sm">
                        <div class="flex justify-between items-end mb-1">
                            <span class="text-[10px] font-black text-blue-600 dark:text-blue-400 uppercase">@${m.alias}</span>
                            <span class="text-[9px] font-bold text-slate-400">${m.fecha_fmt}</span>
                        </div>
                        <p class="text-sm text-slate-700 dark:text-slate-300 font-medium">${m.mensaje}</p>
                    </div>`;
                });
                document.getElementById('cuerpoForo').innerHTML = html || '<p class="text-center text-xs text-slate-400 mt-10">No hay mensajes. Rompé el hielo.</p>';
                let divCuerpo = document.getElementById('cuerpoForo'); divCuerpo.scrollTop = divCuerpo.scrollHeight;
            }).catch(err => { document.getElementById('cuerpoForo').innerHTML = `<p class="text-center text-red-500 font-bold mt-10">${err.message}</p>`; });
        }

        function enviarMensajeForo(e) {
            e.preventDefault();
            let id_evento = document.getElementById('foro_id_evento').value;
            let msj = document.getElementById('foro_mensaje').value;
            if(!msj) return;
            let fdObj = new FormData(); fdObj.append('mensaje', msj);
            fetch('/agenda/foro/' + id_evento, { method: 'POST', body: fdObj })
            .then(res => res.json()).then(data => { document.getElementById('foro_mensaje').value = ''; cargarMensajesForo(); });
        }
    </script>
</body>
</html>