<!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 - Estructura de Grupos</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">
    <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">
    
    <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-indigo-500">UTRAU <span class="text-slate-400 font-bold hidden sm:inline">| ESTRUCTURA SINDICAL</span></span>
        </div>
        <a href="{{ url_for('config.panel') }}" class="text-xs font-bold uppercase text-slate-400 hover:text-white transition"><i class="fa-solid fa-arrow-left mr-2"></i>Volver al Mando</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">
        
        <div class="xl:col-span-2 bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-800 shadow-sm overflow-hidden flex flex-col h-fit max-h-[85vh]">
            <div class="p-6 border-b border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900/50 flex justify-between items-center">
                <div>
                    <h2 class="text-xl font-black uppercase tracking-tight">Mapa de Organización</h2>
                    <p class="text-xs text-slate-500 font-bold mt-1">Sedes, Regiones y Unidades de Trabajo.</p>
                </div>
            </div>
            
            <div class="overflow-y-auto flex-1 p-4 space-y-4">
                {% for g in grupos %}
                <div class="border border-slate-200 dark:border-slate-700 rounded-xl p-4 relative {% if g.id_padre %}ml-8 border-l-4 border-l-indigo-400{% elif '(Sistema)' in g.nombre_grupo %}border-l-4 border-l-amber-500 bg-amber-50 dark:bg-amber-900/10{% else %}bg-slate-50 dark:bg-slate-800/30{% endif %}">
                    
                    <div class="flex justify-between items-start mb-2">
                        <div>
                            <h3 class="text-lg font-black text-slate-800 dark:text-slate-100 leading-tight">
                                {{ g.nombre_grupo }}
                                {% if '(Sistema)' in g.nombre_grupo %}
                                    <i class="fa-solid fa-robot text-amber-500 ml-2" title="Sincronización Automática"></i>
                                {% endif %}
                            </h3>
                            {% if g.nombre_padre %}
                                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest"><i class="fa-solid fa-level-up-alt rotate-90 mr-1"></i>Depende de: {{ g.nombre_padre }}</p>
                            {% elif '(Sistema)' in g.nombre_grupo %}
                                <p class="text-[10px] font-bold text-amber-500 uppercase tracking-widest"><i class="fa-solid fa-shield-halved mr-1"></i>Organo Estatutario Autogestionado</p>
                            {% else %}
                                <p class="text-[10px] font-bold text-indigo-500 uppercase tracking-widest"><i class="fa-solid fa-sitemap mr-1"></i>Grupo Raíz (Principal)</p>
                            {% endif %}
                        </div>
                        
                        {% if '(Sistema)' not in g.nombre_grupo %}
                        <div class="flex space-x-2">
                            <button onclick="editarGrupo('{{ g.id_grupo }}', '{{ g.nombre_grupo }}', '{{ g.id_padre or '' }}')" class="p-1.5 bg-slate-200 dark:bg-slate-700 text-slate-600 dark:text-slate-300 rounded hover:bg-indigo-500 hover:text-white transition" title="Editar Grupo">
                                <i class="fa-solid fa-pen text-xs"></i>
                            </button>
                            <form action="{{ url_for('grupos.eliminar_grupo') }}" method="POST" onsubmit="return confirm('¿Eliminar este grupo definitivamente? Los compañeros no se borrarán, solo saldrán de este grupo.');">
                                <input type="hidden" name="id_grupo" value="{{ g.id_grupo }}">
                                <button type="submit" class="p-1.5 bg-red-100 text-red-600 rounded hover:bg-red-600 hover:text-white transition" title="Eliminar Grupo">
                                    <i class="fa-solid fa-trash text-xs"></i>
                                </button>
                            </form>
                        </div>
                        {% endif %}
                    </div>

                    <div class="mt-4 pt-3 border-t border-slate-100 dark:border-slate-800">
                        <div class="flex justify-between items-center mb-2">
                            <span class="text-[10px] font-black uppercase text-slate-500">Integrantes Asignados ({{ g.integrantes|length }})</span>
                            
                            {% if '(Sistema)' not in g.nombre_grupo %}
                            <button onclick="abrirModalAsignar('{{ g.id_grupo }}', '{{ g.nombre_grupo }}')" class="text-[9px] font-black uppercase bg-emerald-100 hover:bg-emerald-200 text-emerald-700 px-2 py-1 rounded transition flex items-center">
                                <i class="fa-solid fa-user-plus mr-1"></i> Sumar
                            </button>
                            {% else %}
                            <span class="text-[9px] font-bold uppercase text-amber-500">Actualización en tiempo real</span>
                            {% endif %}
                        </div>
                        
                        <div class="flex flex-wrap gap-2">
                            {% for u in g.integrantes %}
                            <div class="flex items-center bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-700 rounded-full pr-1 pl-1 py-1 shadow-sm group">
                                {% if u.path_foto %}
                                    <img src="{{ u.path_foto }}" class="w-5 h-5 rounded-full object-cover mr-2">
                                {% else %}
                                    <div class="w-5 h-5 rounded-full bg-slate-200 dark:bg-slate-700 flex items-center justify-center text-[9px] font-black mr-2">{{ u.nombre_completo[0:1] }}</div>
                                {% endif %}
                                <span class="text-xs font-bold text-slate-700 dark:text-slate-300 mr-2">{{ u.nombre_completo }}</span>
                                
                                {% if '(Sistema)' not in g.nombre_grupo %}
                                <form action="{{ url_for('grupos.quitar_usuario') }}" method="POST" class="inline">
                                    <input type="hidden" name="id_grupo" value="{{ g.id_grupo }}">
                                    <input type="hidden" name="id_usuario" value="{{ u.id_usuario }}">
                                    <button type="submit" title="Quitar del grupo" class="w-5 h-5 rounded-full bg-red-100 hover:bg-red-500 text-red-500 hover:text-white flex items-center justify-center transition opacity-50 group-hover:opacity-100">
                                        <i class="fa-solid fa-xmark text-[10px]"></i>
                                    </button>
                                </form>
                                {% endif %}
                            </div>
                            {% else %}
                            <p class="text-[10px] font-bold text-slate-400 italic">No hay compañeros en este grupo.</p>
                            {% endfor %}
                        </div>
                    </div>
                </div>
                {% else %}
                <div class="text-center py-10 opacity-50">
                    <i class="fa-solid fa-network-wired text-4xl mb-3"></i>
                    <p class="text-sm font-bold uppercase tracking-widest">No hay grupos definidos.</p>
                </div>
                {% endfor %}
            </div>
        </div>

        <div class="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-800 shadow-sm h-fit sticky top-24">
            <div class="p-6 border-b border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900/50 flex justify-between items-center">
                <h2 class="text-lg font-black uppercase tracking-tight" id="titulo_form">Nuevo Grupo</h2>
                <button onclick="limpiarFormulario()" class="text-xs text-indigo-500 hover:text-indigo-700 font-bold uppercase underline">Limpiar</button>
            </div>
            
            <div class="p-6">
                <form action="{{ url_for('grupos.guardar') }}" method="POST" class="space-y-4">
                    <input type="hidden" name="id_grupo" id="form_id_grupo" value="">
                    
                    <div>
                        <label class="block text-[10px] font-black text-slate-500 mb-1.5 uppercase">Nombre de la Unidad / Región*</label>
                        <input type="text" name="nombre_grupo" id="form_nombre_grupo" required placeholder="Ej: SM-Canelones" class="w-full px-4 py-3 border-2 rounded-xl dark:bg-slate-800 dark:border-slate-700 outline-none focus:border-indigo-500 font-black text-sm text-slate-800 dark:text-white">
                    </div>
                    
                    <div>
                        <label class="block text-[10px] font-black text-slate-500 mb-1.5 uppercase">Depende de (Subgrupo de):</label>
                        <select name="id_padre" id="form_id_padre" class="w-full px-4 py-3 border-2 rounded-xl dark:bg-slate-800 dark:border-slate-700 outline-none focus:border-indigo-500 font-bold text-sm">
                            <option value="">-- Ninguno (Es Grupo Raíz) --</option>
                            {% for g in grupos %}
                                {% if '(Sistema)' not in g.nombre_grupo %}
                                <option value="{{ g.id_grupo }}" class="text-black">{{ g.nombre_grupo }}</option>
                                {% endif %}
                            {% endfor %}
                        </select>
                        <p class="text-[9px] font-bold text-slate-400 mt-1">Dejá vacío si es un grupo principal (Ej: San Miguel).</p>
                    </div>
                    
                    <button type="submit" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-black py-4 rounded-xl mt-2 transition uppercase tracking-wider text-sm shadow-md">
                        <i class="fa-solid fa-save mr-2"></i>Guardar Estructura
                    </button>
                </form>
            </div>
        </div>

    </main>

    <div id="modalAsignar" class="fixed inset-0 bg-slate-900/60 z-50 hidden flex 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-md border border-slate-200 dark:border-slate-800 flex flex-col max-h-[90vh]">
            <div class="flex justify-between items-center mb-4 border-b border-slate-100 dark:border-slate-800 pb-4">
                <div>
                    <h3 class="text-lg font-black uppercase tracking-tight text-emerald-600"><i class="fa-solid fa-users mr-2"></i>Asignar Compañeros</h3>
                    <p class="text-[10px] font-bold text-slate-500 uppercase mt-1">Grupo: <span id="lbl_grupo_asignar" class="text-slate-800 dark:text-slate-200"></span></p>
                </div>
                <button type="button" onclick="cerrarModalAsignar()" class="text-slate-400 hover:text-red-500"><i class="fa-solid fa-xmark text-xl"></i></button>
            </div>
            
            <form action="{{ url_for('grupos.asignar_usuarios') }}" method="POST" class="flex flex-col flex-1 overflow-hidden">
                <input type="hidden" name="id_grupo_asignar" id="form_id_grupo_asignar">
                
                <p class="text-[10px] font-black text-slate-500 mb-2 uppercase">Seleccioná del Padrón (Podés elegir varios):</p>
                
                <div class="flex-1 overflow-y-auto border border-slate-200 dark:border-slate-700 rounded-xl p-2 bg-slate-50 dark:bg-slate-800/50 mb-4 space-y-1">
                    {% for u in usuarios %}
                    <label class="flex items-center space-x-3 p-2 hover:bg-white dark:hover:bg-slate-700 rounded-lg cursor-pointer transition border border-transparent hover:border-slate-200 dark:hover:border-slate-600">
                        <input type="checkbox" name="usuarios_ids" value="{{ u.id_usuario }}" class="w-4 h-4 accent-emerald-600 rounded">
                        <div class="flex-1">
                            <p class="text-sm font-bold text-slate-800 dark:text-slate-200 leading-tight">{{ u.nombre_completo }}</p>
                            <p class="text-[9px] text-slate-400 font-black uppercase tracking-widest">@{{ u.alias }}</p>
                        </div>
                    </label>
                    {% endfor %}
                </div>
                
                <button type="submit" class="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-black py-3 rounded-xl transition uppercase tracking-wider text-sm shadow-md">
                    Guardar Selección
                </button>
            </form>
        </div>
    </div>

    <script>
        function editarGrupo(id, nombre, id_padre) {
            document.getElementById('titulo_form').innerText = "Editando: " + nombre;
            document.getElementById('form_id_grupo').value = id;
            document.getElementById('form_nombre_grupo').value = nombre;
            document.getElementById('form_id_padre').value = id_padre;
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }

        function limpiarFormulario() {
            document.getElementById('titulo_form').innerText = "Nuevo Grupo";
            document.getElementById('form_id_grupo').value = "";
            document.getElementById('form_nombre_grupo').value = "";
            document.getElementById('form_id_padre').value = "";
        }

        function abrirModalAsignar(id_grupo, nombre_grupo) {
            document.getElementById('form_id_grupo_asignar').value = id_grupo;
            document.getElementById('lbl_grupo_asignar').innerText = nombre_grupo;
            
            // Limpiar checkboxes previos
            let checkboxes = document.querySelectorAll('input[name="usuarios_ids"]');
            checkboxes.forEach(cb => cb.checked = false);

            document.getElementById('modalAsignar').classList.remove('hidden');
            document.getElementById('modalAsignar').classList.add('flex');
        }

        function cerrarModalAsignar() {
            document.getElementById('modalAsignar').classList.add('hidden');
            document.getElementById('modalAsignar').classList.remove('flex');
        }
    </script>
</body>
</html>