<!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 - Expediente #{{ conflicto.id_conflicto }}</title>
    <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">
    <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
    <script>
        tailwind.config = { darkMode: 'class', theme: { extend: {} } }
    </script>
</head>
<body class="bg-slate-100 dark:bg-slate-950 text-slate-900 dark:text-slate-100 transition-colors duration-300 min-h-screen pb-10">
    
    <nav class="bg-slate-900 border-b border-slate-800 p-4 flex justify-between items-center shadow-md text-white sticky top-0 z-40">
        <div class="flex items-center space-x-3">
            <span class="font-black text-red-500">EXPEDIENTE <span class="text-slate-400 font-bold hidden sm:inline">| #{{ '%05d' % conflicto.id_conflicto }}</span></span>
        </div>
        <a href="{{ url_for('conflictos.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>
    </nav>

    <div class="max-w-7xl mx-auto px-6 mt-4">
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    {% if category == 'success' %}
                        <div class="bg-emerald-100 dark:bg-emerald-900/30 border border-emerald-500 text-emerald-700 dark:text-emerald-400 px-4 py-3 rounded-xl flex items-center mb-4 shadow-sm">
                            <i class="fa-solid fa-circle-check mr-3 text-lg"></i><span class="text-sm font-bold">{{ message }}</span>
                        </div>
                    {% elif category == 'error' %}
                        <div class="bg-red-100 dark:bg-red-900/30 border border-red-500 text-red-700 dark:text-red-400 px-4 py-3 rounded-xl flex items-center mb-4 shadow-sm">
                            <i class="fa-solid fa-triangle-exclamation mr-3 text-lg"></i><span class="text-sm font-bold">{{ message }}</span>
                        </div>
                    {% endif %}
                {% endfor %}
            {% endif %}
        {% endwith %}
    </div>

    <main class="p-6 max-w-7xl mx-auto grid grid-cols-1 xl:grid-cols-3 gap-6 items-start">
        
        <!-- COLUMNA IZQUIERDA: BITÁCORA Y CHAT -->
        <div class="xl:col-span-2 flex flex-col h-[75vh]">
            <div class="mb-4">
                <div class="flex items-center space-x-3 mb-1">
                    <span class="px-2 py-1 text-[10px] font-black uppercase tracking-widest rounded text-white {% if conflicto.estado == 'Activo' %}bg-red-500{% else %}bg-slate-500{% endif %}">
                        {{ conflicto.estado }}
                    </span>
                    <span class="text-[10px] font-black uppercase text-slate-500 tracking-widest"><i class="fa-solid fa-building mr-1"></i>{{ conflicto.empresa_nombre }}</span>
                </div>
                <h1 class="text-3xl font-black leading-tight tracking-tight">{{ conflicto.titulo }}</h1>
            </div>

            <!-- CAJA DE BITÁCORA (Orden WhatsApp) -->
            <div class="flex-1 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-t-2xl shadow-sm overflow-y-auto p-4 space-y-4 flex flex-col-reverse">
                {% for b in bitacora %}
                <div class="flex space-x-3 {% if b.id_usuario == user_id %}flex-row-reverse space-x-reverse{% endif %}">
                    {% if b.autor_foto %}
                        <img src="{{ b.autor_foto }}" class="w-8 h-8 rounded-full object-cover border border-slate-200 dark:border-slate-700 mt-1">
                    {% else %}
                        <div class="w-8 h-8 rounded-full bg-slate-200 dark:bg-slate-800 flex items-center justify-center text-[10px] font-black text-slate-500 mt-1">{{ b.autor[0:1] }}</div>
                    {% endif %}
                    
                    <div class="max-w-[85%] {% if b.id_usuario == user_id %}bg-blue-50 dark:bg-blue-900/20 border border-blue-100 dark:border-blue-800/30{% else %}bg-slate-50 dark:bg-slate-800/50 border border-slate-100 dark:border-slate-700{% endif %} rounded-2xl p-3 shadow-sm">
                        <div class="flex justify-between items-end mb-1 space-x-4">
                            <span class="text-[10px] font-black text-slate-700 dark:text-slate-300 uppercase">@{{ b.autor }}</span>
                            <span class="text-[9px] font-bold text-slate-400">{{ b.timestamp.strftime('%d/%m %H:%M') }}</span>
                        </div>
                        <p class="text-sm text-slate-800 dark:text-slate-200 whitespace-pre-line font-medium">{{ b.descripcion }}</p>
                    </div>
                </div>
                {% else %}
                <div class="text-center py-10 opacity-50">
                    <i class="fa-solid fa-book-open text-4xl mb-2"></i>
                    <p class="text-xs font-bold uppercase tracking-widest">Sin anotaciones registradas.</p>
                </div>
                {% endfor %}
            </div>
            
            <!-- INPUT DE BITÁCORA CON DICTADO -->
            <div class="bg-slate-50 dark:bg-slate-900 p-4 border border-t-0 border-slate-200 dark:border-slate-800 rounded-b-2xl shadow-sm">
                <form action="{{ url_for('conflictos.agregar_bitacora', id_conflicto=conflicto.id_conflicto) }}" method="POST" class="flex items-end space-x-2">
                    <button type="button" id="btn-dictar" onclick="iniciarDictado()" class="bg-slate-200 dark:bg-slate-800 hover:bg-red-100 dark:hover:bg-red-900/50 text-slate-600 dark:text-slate-400 hover:text-red-600 dark:hover:text-red-400 p-4 rounded-xl shadow-sm transition h-full flex flex-col items-center justify-center" title="Dictar por voz">
                        <i id="icono-mic" class="fa-solid fa-microphone text-lg"></i>
                    </button>
                    <textarea id="texto-bitacora" name="descripcion" rows="2" required placeholder="Escribí o dictá el comentario..." class="flex-1 px-4 py-3 rounded-xl border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-950 text-sm font-medium focus:border-blue-500 outline-none resize-none"></textarea>
                    <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white p-4 rounded-xl shadow-md transition group h-full">
                        <i class="fa-solid fa-paper-plane group-hover:scale-110 transition"></i>
                    </button>
                </form>
            </div>
        </div>

        <!-- COLUMNA DERECHA: DOCUMENTOS Y AJUSTES -->
        <div class="space-y-6">
            
            <!-- TARJETA: INFO Y ESTADO -->
            <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 shadow-sm">
                <div class="flex justify-between items-center border-b border-slate-100 dark:border-slate-800 pb-2 mb-3">
                    <h3 class="text-xs font-black uppercase text-slate-400"><i class="fa-solid fa-circle-info mr-2"></i>Información</h3>
                    <div class="flex space-x-2">
                        <a href="{{ url_for('conflictos.imprimir_pdf', id_conflicto=conflicto.id_conflicto) }}" target="_blank" class="text-[9px] font-black bg-red-100 hover:bg-red-200 text-red-700 px-2 py-1 rounded transition uppercase shadow-sm border border-red-200" title="Generar PDF">
                            <i class="fa-solid fa-print mr-1"></i>Imprimir
                        </a>
                        {% if user_rol >= 3 %}
                        <button onclick="document.getElementById('modalTransferir').classList.remove('hidden'); document.getElementById('modalTransferir').classList.add('flex');" class="text-[9px] font-black bg-slate-200 hover:bg-slate-300 dark:bg-slate-800 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-300 px-2 py-1 rounded transition uppercase border border-slate-300 dark:border-slate-700 shadow-sm">
                            Traspaso
                        </button>
                        {% endif %}
                    </div>
                </div>

                <div class="space-y-2 mb-4">
                    <p class="text-xs text-slate-600 dark:text-slate-400"><strong class="uppercase">Ámbito:</strong> {{ conflicto.ambito }}</p>
                    <p class="text-xs text-slate-600 dark:text-slate-400"><strong class="uppercase">RUT Entidad:</strong> {{ conflicto.empresa_rut or 'N/D' }}</p>
                    <p class="text-xs text-slate-600 dark:text-slate-400"><strong class="uppercase">Responsable:</strong> @{{ conflicto.responsable_nombre }}</p>
                </div>

                {% if user_rol >= 3 %}
                <form action="{{ url_for('conflictos.cambiar_esperando', id_conflicto=conflicto.id_conflicto) }}" method="POST" class="border-t border-slate-100 dark:border-slate-800 pt-3 mb-3">
                    <label class="block text-[9px] font-black text-slate-500 mb-1 uppercase">Turno de Respuesta</label>
                    <select name="esperando_a" onchange="this.form.submit()" 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-xs font-bold outline-none cursor-pointer">
                        <option value="UTRAU" {% if conflicto.esperando_a == 'UTRAU' %}selected{% endif %}>Pelota en UTRAU</option>
                        <option value="Empresa" {% if conflicto.esperando_a == 'Empresa' %}selected{% endif %}>Esperando a Empresa</option>
                        <option value="MTSS/Judicial" {% if conflicto.esperando_a == 'MTSS/Judicial' %}selected{% endif %}>Trancado en MTSS/Justicia</option>
                    </select>
                </form>

                <form action="{{ url_for('conflictos.cambiar_estado', id_conflicto=conflicto.id_conflicto) }}" method="POST" class="border-t border-slate-100 dark:border-slate-800 pt-3">
                    <label class="block text-[9px] font-black text-slate-500 mb-1 uppercase">Estado del Expediente</label>
                    <div class="flex space-x-2">
                        <select name="estado" class="flex-1 px-3 py-2 rounded-lg border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800 text-xs font-bold outline-none">
                            <option value="Activo" {% if conflicto.estado == 'Activo' %}selected{% endif %}>Activo</option>
                            <option value="Archivado" {% if conflicto.estado == 'Archivado' %}selected{% endif %}>Archivado</option>
                        </select>
                        <button type="submit" class="bg-slate-200 hover:bg-slate-300 dark:bg-slate-700 dark:hover:bg-slate-600 px-3 py-2 rounded-lg text-xs font-black transition">Confirmar</button>
                    </div>
                </form>
                {% endif %}
            </div>

            <!-- TARJETA: DOCUMENTOS -->
            <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 shadow-sm">
                <div class="flex justify-between items-center border-b border-slate-100 dark:border-slate-800 pb-2 mb-3">
                    <h3 class="text-xs font-black uppercase text-slate-400"><i class="fa-solid fa-folder-open mr-2"></i>Anexos</h3>
                    <button onclick="document.getElementById('modalDoc').classList.remove('hidden'); document.getElementById('modalDoc').classList.add('flex');" class="text-[9px] font-black bg-emerald-100 text-emerald-700 px-2 py-1 rounded uppercase hover:bg-emerald-200 transition">Subir</button>
                </div>
                
                <div class="space-y-2 max-h-48 overflow-y-auto pr-1">
                    {% for d in documentos %}
                    <a href="{{ d.ruta_archivo }}" target="_blank" class="block p-2 bg-slate-50 dark:bg-slate-800/50 border border-slate-200 dark:border-slate-700 rounded-lg hover:border-blue-500 transition group">
                        <div class="flex justify-between items-start">
                            <div class="flex items-start space-x-2">
                                <i class="fa-solid fa-file-pdf text-red-500 mt-1"></i>
                                <div>
                                    <p class="text-xs font-black text-slate-800 dark:text-slate-200 leading-tight group-hover:text-blue-500">{{ d.descripcion_corta }}</p>
                                    <p class="text-[9px] font-bold text-slate-500 uppercase">{{ d.tipo_documento }} | @{{ d.subido_por }}</p>
                                </div>
                            </div>
                        </div>
                    </a>
                    {% else %}
                    <p class="text-[10px] font-bold text-slate-400 text-center italic py-2">Sin anexos registrados.</p>
                    {% endfor %}
                </div>
            </div>

            <!-- TARJETA: PARTICIPANTES -->
            <div class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-2xl p-5 shadow-sm">
                <div class="flex justify-between items-center border-b border-slate-100 dark:border-slate-800 pb-2 mb-3">
                    <h3 class="text-xs font-black uppercase text-slate-400"><i class="fa-solid fa-users mr-2"></i>Compañeros Asignados</h3>
                    {% if user_rol >= 3 %}
                    <button onclick="document.getElementById('modalPart').classList.remove('hidden'); document.getElementById('modalPart').classList.add('flex');" class="text-[9px] font-black bg-blue-100 text-blue-700 px-2 py-1 rounded uppercase hover:bg-blue-200 transition">Sumar</button>
                    {% endif %}
                </div>
                
                <div class="flex flex-wrap gap-2 max-h-48 overflow-y-auto pr-1">
                    {% for p in participantes %}
                    <span class="bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 px-3 py-1.5 rounded-lg text-xs font-bold text-slate-800 dark:text-slate-200 shadow-sm flex items-center">
                        @{{ p.alias }} 
                        {% if p.grupos %}
                        <span class="text-[9px] font-black uppercase text-slate-400 ml-1">({{ p.grupos }})</span>
                        {% endif %}
                    </span>
                    {% endfor %}
                </div>
            </div>
            
        </div>
    </main>

    <!-- MODAL: SUBIR DOCUMENTO -->
    <div id="modalDoc" 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 p-6 rounded-3xl shadow-2xl w-full max-w-sm border border-slate-200 dark:border-slate-800">
            <div class="flex justify-between items-center mb-4 border-b border-slate-100 dark:border-slate-800 pb-2">
                <h3 class="text-lg font-black uppercase tracking-tight text-emerald-600"><i class="fa-solid fa-cloud-arrow-up mr-2"></i>Subir Documento</h3>
                <button type="button" onclick="document.getElementById('modalDoc').classList.add('hidden'); document.getElementById('modalDoc').classList.remove('flex');" class="text-slate-400 hover:text-red-500"><i class="fa-solid fa-xmark text-xl"></i></button>
            </div>
            
            <form action="{{ url_for('conflictos.subir_documento', id_conflicto=conflicto.id_conflicto) }}" method="POST" enctype="multipart/form-data" class="space-y-4">
                <div>
                    <label class="block text-[10px] font-black text-slate-500 mb-1 uppercase">Clasificación</label>
                    <select name="tipo_documento" required class="w-full px-4 py-2 border-2 rounded-xl dark:bg-slate-800 dark:border-slate-700 outline-none focus:border-emerald-500 font-bold text-sm">
                        <option value="Acta" class="text-black">Acta / Resolución</option>
                        <option value="Denuncia" class="text-black">Denuncia</option>
                        <option value="Recibo" class="text-black">Recibo / Factura</option>
                        <option value="Respuesta" class="text-black">Comunicado Patronal</option>
                        <option value="Evidencia" class="text-black">Prueba / Evidencia</option>
                        <option value="Otro" class="text-black">Otro</option>
                    </select>
                </div>
                <div>
                    <label class="block text-[10px] font-black text-slate-500 mb-1 uppercase">Título (Breve)</label>
                    <input type="text" name="descripcion_corta" required class="w-full px-4 py-2 border-2 rounded-xl dark:bg-slate-800 dark:border-slate-700 outline-none focus:border-emerald-500 font-bold text-sm">
                </div>
                <div class="p-4 border-2 border-dashed border-slate-300 dark:border-slate-700 rounded-xl bg-slate-50 dark:bg-slate-800/50 text-center">
                    <input type="file" name="archivo" required accept="image/*,.pdf,.doc,.docx" class="w-full text-[10px] text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-[10px] file:font-black file:bg-emerald-100 file:text-emerald-700 hover:file:bg-emerald-200">
                </div>
                
                <button type="submit" class="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-black py-3 rounded-xl mt-4 transition uppercase tracking-wider text-sm shadow-md">Registrar Anexo</button>
            </form>
        </div>
    </div>

    <!-- MODAL: AGREGAR PARTICIPANTE Y GRUPOS -->
    <div id="modalPart" 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 p-6 rounded-3xl shadow-2xl w-full max-w-sm border border-slate-200 dark:border-slate-800">
            <div class="flex justify-between items-center mb-4 border-b border-slate-100 dark:border-slate-800 pb-2">
                <h3 class="text-lg font-black uppercase tracking-tight text-blue-600"><i class="fa-solid fa-user-plus mr-2"></i>Convocatoria</h3>
                <button type="button" onclick="document.getElementById('modalPart').classList.add('hidden'); document.getElementById('modalPart').classList.remove('flex');" class="text-slate-400 hover:text-red-500"><i class="fa-solid fa-xmark text-xl"></i></button>
            </div>
            
            <form action="{{ url_for('conflictos.agregar_participante', id_conflicto=conflicto.id_conflicto) }}" method="POST" class="flex flex-col space-y-4">
                
                <div>
                    <label class="block text-[10px] font-black text-slate-500 mb-1 uppercase">Padrón Individual (Opcional)</label>
                    <select name="id_usuario" class="w-full px-4 py-3 border-2 rounded-xl dark:bg-slate-800 dark:border-slate-700 outline-none focus:border-blue-500 font-bold text-sm">
                        <option value="">-- Buscar Compañero --</option>
                        {% for u in usuarios_disponibles %}
                        <option value="{{ u.id_usuario }}" class="text-black">@{{ u.alias }}</option>
                        {% endfor %}
                    </select>
                </div>

                <div class="flex-1 flex flex-col max-h-[150px]">
                    <label class="block text-[10px] font-black text-slate-500 mb-1 uppercase">Sumar Sectores Completos (Opcional)</label>
                    <div class="flex-1 overflow-y-auto border-2 border-slate-200 dark:border-slate-700 rounded-xl p-2 bg-slate-50 dark:bg-slate-800/50 space-y-1">
                        {% for g in grupos %}
                        <label class="flex items-center space-x-2 p-1.5 hover:bg-white dark:hover:bg-slate-700 rounded cursor-pointer transition">
                            <input type="checkbox" name="grupos_ids" value="{{ g.id_grupo }}" class="w-4 h-4 accent-blue-600">
                            <span class="text-xs font-bold text-slate-800 dark:text-slate-200">{{ g.nombre_grupo }}</span>
                        </label>
                        {% endfor %}
                    </div>
                </div>

                <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-black py-3 rounded-xl transition uppercase tracking-wider text-sm shadow-md">Confirmar Integración</button>
            </form>
        </div>
    </div>

    <!-- MODAL: TRANSFERIR RESPONSABILIDAD -->
    <div id="modalTransferir" 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 p-6 rounded-3xl shadow-2xl w-full max-w-sm border border-slate-200 dark:border-slate-800">
            <div class="flex justify-between items-center mb-4 border-b border-slate-100 dark:border-slate-800 pb-2">
                <h3 class="text-lg font-black uppercase tracking-tight text-slate-700 dark:text-slate-300"><i class="fa-solid fa-arrow-right-arrow-left mr-2"></i>Traspaso</h3>
                <button type="button" onclick="document.getElementById('modalTransferir').classList.add('hidden'); document.getElementById('modalTransferir').classList.remove('flex');" class="text-slate-400 hover:text-red-500"><i class="fa-solid fa-xmark text-xl"></i></button>
            </div>
            
            <form action="{{ url_for('conflictos.transferir_responsabilidad', id_conflicto=conflicto.id_conflicto) }}" method="POST" class="space-y-4">
                <div>
                    <label class="block text-[10px] font-black text-slate-500 mb-1 uppercase">Nuevo Responsable</label>
                    <select name="nuevo_responsable" required class="w-full px-4 py-3 border-2 rounded-xl dark:bg-slate-800 dark:border-slate-700 outline-none focus:border-slate-500 font-bold text-sm">
                        <option value="">-- Seleccionar --</option>
                        {% for r in responsables %}
                        <option value="{{ r.id_usuario }}" class="text-black">@{{ r.alias }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div>
                    <label class="block text-[10px] font-black text-slate-500 mb-1 uppercase">Motivo del traspaso</label>
                    <textarea name="motivo_transferencia" required rows="2" class="w-full px-4 py-2 border-2 rounded-xl dark:bg-slate-800 dark:border-slate-700 outline-none focus:border-slate-500 font-bold text-sm resize-none"></textarea>
                </div>
                <button type="submit" class="w-full bg-slate-800 hover:bg-slate-700 text-white font-black py-3 rounded-xl transition uppercase tracking-wider text-sm shadow-md">Efectuar Transferencia</button>
            </form>
        </div>
    </div>

    <!-- SCRIPT DE DICTADO POR VOZ -->
    <script>
        function iniciarDictado() {
            if (!('webkitSpeechRecognition' in window)) {
                alert("Tu navegador no soporta el dictado por voz. Te recomendamos usar Google Chrome en el celular o PC.");
                return;
            }

            const recognition = new webkitSpeechRecognition();
            recognition.lang = 'es-UY'; // Configurado para español Uruguay
            recognition.interimResults = false;
            recognition.maxAlternatives = 1;

            const btnMic = document.getElementById('btn-dictar');
            const iconoMic = document.getElementById('icono-mic');
            const textArea = document.getElementById('texto-bitacora');

            recognition.onstart = function() {
                iconoMic.classList.remove('fa-microphone');
                iconoMic.classList.add('fa-microphone-lines', 'fa-beat-fade');
                btnMic.classList.add('bg-red-200', 'text-red-700');
                btnMic.classList.remove('bg-slate-200', 'dark:bg-slate-800');
            };

            recognition.onresult = function(event) {
                const transcripcion = event.results[0][0].transcript;
                // Agrega el texto dictado manteniendo lo que ya estaba escrito
                textArea.value += (textArea.value ? ' ' : '') + transcripcion + ' ';
            };

            recognition.onerror = function(event) {
                console.error("Error en el dictado: ", event.error);
                alert("Hubo un problema al escuchar el micrófono. Intentá de nuevo.");
            };

            recognition.onend = function() {
                iconoMic.classList.remove('fa-microphone-lines', 'fa-beat-fade');
                iconoMic.classList.add('fa-microphone');
                btnMic.classList.remove('bg-red-200', 'text-red-700');
                btnMic.classList.add('bg-slate-200', 'dark:bg-slate-800');
                textArea.focus();
            };

            recognition.start();
        }
    </script>
</body>
</html>