// CONFIGURACIÓN GLOBAL const API_URL = "https://integrarepara-api.integrarepara.es"; document.addEventListener("DOMContentLoaded", async () => { // 1. Verificar Token const token = localStorage.getItem("token"); if (!token) { window.location.href = "index.html"; return; } // 2. Cargar Componentes HTML await loadComponent("sidebar-container", "sidebar.html"); await loadComponent("header-container", "header.html"); // 3. Inicializar Iconos if (window.lucide) lucide.createIcons(); // 4. Lógica del Usuario (Header) setupUserInfo(token); // 5. Marcar enlace activo (Sidebar) highlightActiveLink(); // 6. Configurar Logout const btnLogout = document.getElementById("globalBtnLogout"); if(btnLogout) { btnLogout.addEventListener("click", () => { localStorage.removeItem("token"); window.location.href = "index.html"; }); } }); // Función para cargar HTML externo async function loadComponent(elementId, filePath) { try { const response = await fetch(filePath); if (response.ok) { const html = await response.text(); document.getElementById(elementId).innerHTML = html; } else { console.error(`Error cargando ${filePath}`); } } catch (e) { console.error(e); } } // Función para rellenar datos del usuario function setupUserInfo(token) { try { const payload = JSON.parse(atob(token.split('.')[1])); // Elementos del Header const nameEl = document.getElementById("headerUserName"); const roleEl = document.getElementById("headerUserRole"); const avatarEl = document.getElementById("headerUserAvatar"); if (nameEl) nameEl.innerText = payload.email || "Usuario"; if (roleEl) roleEl.innerText = (payload.role || "Operario").toUpperCase(); if (avatarEl) avatarEl.innerText = (payload.email?.[0] || "U").toUpperCase(); } catch (e) { console.error("Error decodificando token", e); localStorage.removeItem("token"); window.location.href = "index.html"; } } // Función para poner azul el enlace actual function highlightActiveLink() { // Obtenemos el nombre del archivo actual (ej: panel.html) const path = window.location.pathname.split("/").pop() || "index.html"; const links = document.querySelectorAll(".nav-item"); links.forEach(link => { // Quitamos estilos activos por defecto link.classList.remove("bg-blue-600", "text-white", "shadow-lg", "shadow-blue-500/30"); link.classList.add("text-slate-400", "hover:text-white", "hover:bg-slate-800"); // Si coincide con la página actual, le ponemos el estilo "Activo" if (link.getAttribute("data-page") === path) { link.classList.remove("text-slate-400", "hover:text-white", "hover:bg-slate-800"); link.classList.add("bg-blue-600", "text-white", "shadow-lg", "shadow-blue-500/30"); } }); }