/**
 * FYCLS - Sidebar Dinámico v14 CON MENU COLAPSABLE
 * FIX: Lee claves correctas de BD (org_nombre + nombre_empresa, org_logo + logo_url)
 * Solo muestra logo sin texto en el header
 */
(function(){
    ['userName','userAvatar'].forEach(function(id){
        if(!document.getElementById(id)){
            var el=document.createElement('span');
            el.id=id; el.style.display='none';
            document.body.appendChild(el);
        }
    });

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

    var user=null, initials='F', 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:'—';
    var path=window.location.pathname;
    var isAdmin=path.indexOf('/admin')!==-1;
    var perfilUrl=isAdmin?'/app/admin/perfil.html':'/app/portal/perfil.html';

    function ic(d){ return '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">'+d+'</svg>'; }

    var icons = {
        dashboard:   ic('<rect x="3" y="3" width="7" height="9" rx="1"/><rect x="14" y="3" width="7" height="5" rx="1"/><rect x="14" y="12" width="7" height="9" rx="1"/><rect x="3" y="16" width="7" height="5" rx="1"/>'),
        ticket:      ic('<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"/>'),
        monitor:     ic('<rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/>'),
        laptop:      ic('<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"/>'),
        satellite:   ic('<path d="M13 7 8.7 2.7a2.41 2.41 0 0 0-3.4 0L2.7 5.3a2.41 2.41 0 0 0 0 3.4L7 13"/><path d="m17 11 4.3 4.3a2.41 2.41 0 0 1 0 3.4l-2.6 2.6a2.41 2.41 0 0 1-3.4 0L11 17"/><path d="m8 12 4 4"/><path d="m16 8-3-3"/>'),
        wrench:      ic('<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"/>'),
        alert:       ic('<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"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>'),
        chart:       ic('<line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/>'),
        book:        ic('<path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20"/>'),
        users:       ic('<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"/>'),
        lock:        ic('<rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>'),
        tag:         ic('<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"/>'),
        link:        ic('<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>'),
        settings:    ic('<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>'),
        home:        ic('<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"/>'),
        user:        ic('<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>'),
        help:        ic('<circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/>'),
        eye:         ic('<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>'),
        shield:      ic('<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>'),
        file:        ic('<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>'),
        chevron:     ic('<polyline points="6 9 12 15 18 9"/>')
    };

    // Leer branding cacheado - soportar ambos formatos de claves
    var orgName = 'Fycls', orgLogo = '', orgInitial = 'F';
    try {
        var cached = JSON.parse(localStorage.getItem('nexus_branding') || '{}');
        var cachedName = cached.nombre_empresa || cached.org_nombre;
        if (cachedName) { orgName = cachedName; orgInitial = orgName.charAt(0).toUpperCase(); }
        var cachedLogo = cached.logo_url || cached.org_logo;
        if (cachedLogo) orgLogo = cachedLogo;
    } catch(e) {}

    function getCollapsedState() {
        try { return JSON.parse(localStorage.getItem('sidebar_collapsed') || '{}'); } catch(e) { return {}; }
    }
    function saveCollapsedState(state) {
        try { localStorage.setItem('sidebar_collapsed', JSON.stringify(state)); } catch(e) {}
    }

    function buildSidebar() {
        // Solo logo, sin texto
        var logoHtml;
        if (orgLogo) {
            logoHtml = '<img src="' + orgLogo + '" class="sidebar-logo-img" alt="Logo">';
        } else {
            logoHtml = '<div class="sidebar-logo-fallback">' + orgInitial + '</div>';
        }

        var nav = '';
        var cs = getCollapsedState();

        if (isAdmin) {
            nav += '<div class="nav-section">';
            nav += '<a href="/app/admin/" class="nav-item"><span class="icon">'+icons.dashboard+'</span> Dashboard</a>';
            nav += '</div>';

            nav += buildSection('mesa', 'Mesa de Ayuda', cs, [
                {href:'/app/admin/tickets.html', icon:icons.ticket, label:'Tickets'},
                (rol==='admin'||rol==='tecnico') ? {href:'/app/admin/categorias.html', icon:icons.tag, label:'Categorías'} : null
            ]);

            if (rol === 'admin' || rol === 'tecnico' || rol === 'supervisor') {
                var invItems = [
                    {href:'/app/admin/activos.html', icon:icons.laptop, label:'Activos'},
                    {href:'/app/admin/licencias.html', icon:icons.lock, label:'Licencias'},
                    {href:'/app/admin/mantenimientos.html', icon:icons.wrench, label:'Mantenimientos'}
                ];
                if (rol === 'admin') invItems.push({href:'/app/admin/contratos.html', icon:icons.file, label:'Contratos'});
                nav += buildSection('inventario', 'Inventario', cs, invItems);
            }

            if (rol === 'admin') {
                var userItems = [{href:'/app/admin/usuarios.html', icon:icons.users, label:'Usuarios'}];
                userItems.push({href:'/app/admin/credenciales.html', icon:icons.shield, label:'Credenciales'});
                nav += buildSection('usuarios', 'Usuarios', cs, userItems);
            }

            if (rol === 'admin' || rol === 'supervisor' || rol === 'tecnico') {
                var repItems = [
                    {href:'/app/admin/reportes.html', icon:icons.chart, label:'Reportes & Auditoría'}
                ];
                if (rol === 'admin') repItems.push({href:'/app/admin/supervisor.html', icon:icons.eye, label:'Métricas del Equipo'});
                if (rol === 'admin') repItems.push({href:'/app/admin/alertas.html', icon:icons.alert, label:'Alertas'});
                nav += buildSection('reportes', 'Reportes', cs, repItems);
            }

            var herrItems = [];
            if (rol === 'admin' || rol === 'tecnico') herrItems.push({href:'/app/admin/soporte-remoto.html', icon:icons.monitor, label:'Soporte Remoto'});
            if (rol === 'admin') herrItems.push({href:'/app/admin/agente.html', icon:icons.satellite, label:'Agente de Monitoreo'});
            herrItems.push({href:'/app/admin/kb-editor.html', icon:icons.book, label:'Base de Conocimientos'});
            nav += buildSection('herramientas', 'Herramientas', cs, herrItems);

            if (rol === 'admin') {
                nav += buildSection('config', 'Configuración', cs, [
                    {href:'/app/admin/configuracion.html', icon:icons.settings, label:'General'},
                    {href:'/app/admin/integraciones.html', icon:icons.link, label:'Integraciones'}
                ]);
            }

        } else {
            nav += '<div class="nav-section"><div class="nav-section-title">Mi Portal</div>';
            nav += '<a href="/app/portal/" class="nav-item"><span class="icon">'+icons.home+'</span> Inicio</a>';
            nav += '<a href="/app/portal/mis-tickets.html" class="nav-item"><span class="icon">'+icons.ticket+'</span> Mis Solicitudes</a>';
            nav += '<a href="/app/portal/nuevo-ticket.html" class="nav-item"><span class="icon">'+icons.help+'</span> Pedir Ayuda</a>';
            nav += '<a href="/app/portal/mis-equipos.html" class="nav-item"><span class="icon">'+icons.laptop+'</span> Mi Equipo</a>';
            nav += '<a href="/app/portal/mis-accesos.html" class="nav-item"><span class="icon">'+icons.lock+'</span> Mis Accesos</a>';
            nav += '<a href="/app/portal/ayuda.html" class="nav-item"><span class="icon">'+icons.book+'</span> Ayuda</a>';
            nav += '</div>';
        }

        sidebar.innerHTML =
            '<div class="sidebar-header sidebar-header-logo-only" id="sidebarHeader">' + logoHtml + '</div>' +
            '<nav class="sidebar-nav">' + nav + '</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" style="font-size:10px;text-transform:capitalize">' + rol + '</div></div></a>' +
            '<div style="text-align:center;margin-top:6px"><a href="#" onclick="NexusAuth.logout();return false" style="font-size:11px;color:var(--text-muted,#64748b);text-decoration:none">Cerrar sesión</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');
            }
        }

        addStyles();
    }

    function buildSection(name, title, cs, items) {
        items = items.filter(function(i){return i !== null;});
        if (items.length === 0) return '';
        var isOpen = cs[name] !== false;
        var html = '<div class="nav-section collapsible">';
        html += '<div class="nav-section-title" onclick="toggleSection(\''+name+'\')">';
        html += '<span>'+title+'</span>';
        html += '<span class="chevron '+(isOpen?'open':'')+'">'+icons.chevron+'</span>';
        html += '</div>';
        html += '<div class="nav-section-content" style="display:'+(isOpen?'block':'none')+'" data-section="'+name+'">';
        items.forEach(function(item){
            html += '<a href="'+item.href+'" class="nav-item"><span class="icon">'+item.icon+'</span> '+item.label+'</a>';
        });
        html += '</div></div>';
        return html;
    }

    function addStyles() {
        if (document.getElementById('sidebar-v14-styles')) return;
        var style = document.createElement('style');
        style.id = 'sidebar-v14-styles';
        style.textContent = [
            '.sidebar-header-logo-only { display:flex; align-items:center; justify-content:center; padding:20px 16px; }',
            '.sidebar-header-logo-only .sidebar-brand { display:none !important; }',
            '.sidebar-header-logo-only .sidebar-logo-img { max-width:160px; width:auto; height:auto; max-height:55px; object-fit:contain; }',
            '.sidebar-header-logo-only .sidebar-logo-fallback { width:48px; height:48px; border-radius:12px; display:flex; align-items:center; justify-content:center; font-size:22px; font-weight:700; background:var(--primary,#6366f1); color:#fff; }',
            '.nav-section.collapsible { margin-bottom:4px; }',
            '.nav-section.collapsible .nav-section-title { cursor:pointer; user-select:none; display:flex; align-items:center; justify-content:space-between; padding:8px 16px; font-size:11px; font-weight:600; text-transform:uppercase; letter-spacing:0.5px; color:var(--color-text-muted,#94a3b8); transition:all 0.2s; }',
            '.nav-section.collapsible .nav-section-title:hover { color:var(--color-text,#e2e8f0); background:rgba(255,255,255,0.05); border-radius:8px; }',
            '.nav-section.collapsible .chevron { transition:transform 0.3s ease; opacity:0.6; }',
            '.nav-section.collapsible .chevron.open { transform:rotate(180deg); }',
            '.nav-section-content { overflow:hidden; transition:all 0.3s ease; }'
        ].join('\n');
        document.head.appendChild(style);
    }

    window.toggleSection = function(sectionName) {
        var content = document.querySelector('[data-section="'+sectionName+'"]');
        if (!content) return;
        var chevron = content.parentElement.querySelector('.chevron');
        var cs = getCollapsedState();
        if (content.style.display === 'none') {
            content.style.display = 'block';
            if (chevron) chevron.classList.add('open');
            cs[sectionName] = true;
        } else {
            content.style.display = 'none';
            if (chevron) chevron.classList.remove('open');
            cs[sectionName] = false;
        }
        saveCollapsedState(cs);
    };

    buildSidebar();

    // Cargar branding desde API
    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;

                // Normalizar: la API ahora devuelve ambos formatos
                var brandName = b.nombre_empresa || b.org_nombre || null;
                var brandLogo = b.logo_url || b.org_logo || null;

                // Guardar en cache normalizado
                try { localStorage.setItem('nexus_branding', JSON.stringify(b)); } catch(e){}

                // Actualizar título
                if (brandName) {
                    orgName = brandName;
                    var title = document.title;
                    if (title.indexOf('Nexus IT') !== -1) document.title = title.replace('Nexus IT', orgName);
                    if (title.indexOf('Fycls') !== -1) document.title = title.replace('Fycls', orgName);
                }

                // Actualizar logo en sidebar
                if (brandLogo) {
                    orgLogo = brandLogo;
                    var header = document.getElementById('sidebarHeader');
                    if (header) {
                        header.innerHTML = '<img src="' + brandLogo + '" class="sidebar-logo-img" alt="Logo">';
                    }
                }

                // Colores
                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('--color-accent', b.brand_color_accent);
                if (b.brand_sidebar_bg) sidebar.style.background = b.brand_sidebar_bg;
                if (b.brand_header_bg) { var tb = document.querySelector('.top-bar'); if (tb) tb.style.background = b.brand_header_bg; }
            })
            .catch(function(e){ console.warn('Branding load error:', e); });
    }

    loadBranding();
})();