/**
 * NEXUS IT - Sidebar Dinámico v8
 * Lucide SVG Icons + Branding dinámico desde configuración
 */
(function(){
    // ── Lucide SVG Icons (18x18, stroke-width 1.75) ──
    var I = {
        dashboard:    '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>',
        ticket:       '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z"/><path d="M13 5v2"/><path d="M13 17v2"/><path d="M13 11v2"/></svg>',
        remote:       '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8"/><path d="M12 17v4"/></svg>',
        laptop:       '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16"/></svg>',
        radio:        '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M4.9 19.1C1 15.2 1 8.8 4.9 4.9"/><path d="M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.4"/><circle cx="12" cy="12" r="2"/><path d="M16.2 7.8c2.3 2.3 2.3 6.1 0 8.4"/><path d="M19.1 4.9C23 8.8 23 15.1 19.1 19"/></svg>',
        wrench:       '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76Z"/></svg>',
        alert:        '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>',
        chart:        '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="m19 9-5 5-4-4-3 3"/></svg>',
        search:       '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>',
        book:         '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20"/></svg>',
        users:        '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>',
        tag:          '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2H2v10l9.29 9.29c.94.94 2.48.94 3.42 0l6.58-6.58c.94-.94.94-2.48 0-3.42L12 2Z"/><path d="M7 7h.01"/></svg>',
        plug:         '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22v-5"/><path d="M9 8V2"/><path d="M15 8V2"/><path d="M18 8v5a6 6 0 0 1-6 6v0a6 6 0 0 1-6-6V8Z"/></svg>',
        settings:     '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>',
        home:         '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9,22 9,12 15,12 15,22"/></svg>',
        plus:         '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg>',
        user:         '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>',
        logout:       '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16,17 21,12 16,7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>'
    };

    var sidebar = document.getElementById('sidebar');
    if (!sidebar) return;

    var user = null, initials = 'AN', rol = 'usuario';
    try {
        var raw = localStorage.getItem('nexus_user');
        if (raw) user = JSON.parse(raw);
        if (user && user.nombre_completo) initials = user.nombre_completo.split(' ').map(function(n){ return n[0] }).join('').substring(0,2).toUpperCase();
        if (user && user.rol) rol = user.rol;
    } catch(e) {}
    var nombre = user ? user.nombre_completo : '\u2014';
    var path = window.location.pathname;
    var isAdmin = path.indexOf('/admin') !== -1;
    var perfilUrl = isAdmin ? '/app/admin/perfil.html' : '/app/portal/perfil.html';

    var orgName = 'Nexus IT';
    var orgLogo = '';
    var orgInitial = 'N';

    try {
        var cached = JSON.parse(localStorage.getItem('nexus_branding') || '{}');
        if (cached.org_nombre) { orgName = cached.org_nombre; orgInitial = orgName.charAt(0).toUpperCase(); }
        if (cached.org_logo) orgLogo = cached.org_logo;
    } catch(e) {}

    function buildSidebar() {
        var logoHtml = orgLogo
            ? '<img src="' + orgLogo + '" style="width:34px;height:34px;border-radius:8px;object-fit:contain" alt="Logo">'
            : '<div class="sidebar-logo">' + orgInitial + '</div>';

        if (isAdmin) {
            sidebar.innerHTML =
            '<div class="sidebar-header">' + logoHtml + '<span class="sidebar-brand" id="sidebarBrand">' + orgName + '</span></div>' +
            '<nav class="sidebar-nav">' +

            '<div class="nav-section"><div class="nav-section-title">Principal</div>' +
            '<a href="/app/admin/" class="nav-item"><span class="icon">' + I.dashboard + '</span> Dashboard</a>' +
            '<a href="/app/admin/tickets.html" class="nav-item"><span class="icon">' + I.ticket + '</span> Tickets</a>' +
            '<a href="/app/admin/soporte-remoto.html" class="nav-item"><span class="icon">' + I.remote + '</span> Soporte Remoto</a></div>' +

            '<div class="nav-section"><div class="nav-section-title">Inventario</div>' +
            '<a href="/app/admin/activos.html" class="nav-item"><span class="icon">' + I.laptop + '</span> Activos</a>' +
            '<a href="/app/admin/agente.html" class="nav-item"><span class="icon">' + I.radio + '</span> Agente Monitoreo</a>' +
            '<a href="/app/admin/mantenimientos.html" class="nav-item"><span class="icon">' + I.wrench + '</span> Mantenimientos</a>' +
            '<a href="/app/admin/alertas.html" class="nav-item"><span class="icon">' + I.alert + '</span> Alertas</a></div>' +

            '<div class="nav-section"><div class="nav-section-title">An\u00e1lisis</div>' +
            '<a href="/app/admin/reportes.html" class="nav-item"><span class="icon">' + I.chart + '</span> Reportes</a>' +
            '<a href="/app/admin/auditoria.html" class="nav-item"><span class="icon">' + I.search + '</span> Auditor\u00eda</a></div>' +

            '<div class="nav-section"><div class="nav-section-title">Conocimiento</div>' +
            '<a href="/app/admin/kb-editor.html" class="nav-item"><span class="icon">' + I.book + '</span> Base de Conocimientos</a></div>' +

            '<div class="nav-section"><div class="nav-section-title">Administraci\u00f3n</div>' +
            '<a href="/app/admin/usuarios.html" class="nav-item"><span class="icon">' + I.users + '</span> Usuarios</a>' +
            '<a href="/app/admin/categorias.html" class="nav-item"><span class="icon">' + I.tag + '</span> Categor\u00edas</a>' +
            '<a href="/app/admin/integraciones.html" class="nav-item"><span class="icon">' + I.plug + '</span> Integraciones</a>' +
            '<a href="/app/admin/configuracion.html" class="nav-item"><span class="icon">' + I.settings + '</span> Configuraci\u00f3n</a></div>' +

            '</nav>' +
            '<div class="sidebar-footer">' +
            '<a href="' + perfilUrl + '" class="user-card" style="text-decoration:none;color:inherit">' +
            '<div class="user-avatar">' + initials + '</div><div class="user-info">' +
            '<div class="user-name">' + nombre + '</div><div class="user-role">' + I.user + ' Mi Perfil</div></div></a>' +
            '<div style="text-align:center;margin-top:6px"><a href="#" onclick="NexusAuth.logout();return false" style="font-size:11px;color:rgba(255,255,255,.4);text-decoration:none;display:inline-flex;align-items:center;gap:4px">' + I.logout + ' Cerrar sesi\u00f3n</a></div>' +
            '</div>';
        } else {
            sidebar.innerHTML =
            '<div class="sidebar-header">' + logoHtml + '<span class="sidebar-brand" id="sidebarBrand">' + orgName + '</span></div>' +
            '<nav class="sidebar-nav">' +
            '<div class="nav-section"><div class="nav-section-title">Mi Portal</div>' +
            '<a href="/app/portal/" class="nav-item"><span class="icon">' + I.home + '</span> Inicio</a>' +
            '<a href="/app/portal/mis-tickets.html" class="nav-item"><span class="icon">' + I.ticket + '</span> Mis Tickets</a>' +
            '<a href="/app/portal/nuevo-ticket.html" class="nav-item"><span class="icon">' + I.plus + '</span> Nuevo Ticket</a>' +
            '<a href="/app/portal/mis-equipos.html" class="nav-item"><span class="icon">' + I.laptop + '</span> Mis Equipos</a>' +
            '<a href="/app/portal/ayuda.html" class="nav-item"><span class="icon">' + I.book + '</span> Ayuda</a></div>' +
            '</nav>' +
            '<div class="sidebar-footer">' +
            '<a href="' + perfilUrl + '" class="user-card" style="text-decoration:none;color:inherit">' +
            '<div class="user-avatar">' + initials + '</div><div class="user-info">' +
            '<div class="user-name">' + nombre + '</div><div class="user-role">' + I.user + ' Mi Perfil</div></div></a>' +
            '<div style="text-align:center;margin-top:6px"><a href="#" onclick="NexusAuth.logout();return false" style="font-size:11px;color:rgba(255,255,255,.4);text-decoration:none;display:inline-flex;align-items:center;gap:4px">' + I.logout + ' Cerrar sesi\u00f3n</a></div>' +
            '</div>';
        }

        // Active link
        var links = sidebar.querySelectorAll('.nav-item');
        for (var i = 0; i < links.length; i++) {
            var href = links[i].getAttribute('href');
            if (href === path || (href !== '/app/admin/' && href !== '/app/portal/' && path.indexOf(href.replace('.html','')) === 0)) {
                links[i].classList.add('active');
            } else if ((href === '/app/admin/' || href === '/app/portal/') && (path === href || path === href + 'index.html')) {
                links[i].classList.add('active');
            }
        }
    }

    buildSidebar();

    // Branding dinámico
    function loadBranding() {
        fetch('/api/v1/configuracion/branding')
            .then(function(r){ return r.json(); })
            .then(function(res){
                if (!res.success || !res.data) return;
                var b = res.data;
                try { localStorage.setItem('nexus_branding', JSON.stringify(b)); } catch(e){}

                if (b.org_nombre) {
                    orgName = b.org_nombre;
                    orgInitial = orgName.charAt(0).toUpperCase();
                    var brandEl = document.getElementById('sidebarBrand');
                    if (brandEl) brandEl.textContent = orgName;
                    var title = document.title;
                    if (title.indexOf('Nexus IT') !== -1) document.title = title.replace('Nexus IT', orgName);
                }

                if (b.org_logo) {
                    orgLogo = b.org_logo;
                    var header = sidebar.querySelector('.sidebar-header');
                    if (header) {
                        var oldLogo = header.querySelector('.sidebar-logo');
                        var oldImg = header.querySelector('img');
                        var target = oldLogo || oldImg;
                        if (target) {
                            var img = document.createElement('img');
                            img.src = b.org_logo;
                            img.style.cssText = 'width:34px;height:34px;border-radius:8px;object-fit:contain';
                            img.alt = 'Logo';
                            target.replaceWith(img);
                        }
                    }
                }

                if (b.brand_color_primary) {
                    document.documentElement.style.setProperty('--primary', b.brand_color_primary);
                    document.documentElement.style.setProperty('--color-primary', b.brand_color_primary);
                }
                if (b.brand_color_accent) {
                    document.documentElement.style.setProperty('--accent', b.brand_color_accent);
                    document.documentElement.style.setProperty('--color-accent', b.brand_color_accent);
                }
                if (b.brand_sidebar_bg) {
                    sidebar.style.background = b.brand_sidebar_bg;
                }
                if (b.brand_header_bg) {
                    var topBar = document.querySelector('.top-bar');
                    if (topBar) topBar.style.background = b.brand_header_bg;
                }
            })
            .catch(function(e){});
    }

    loadBranding();
})();
