/* =============================================
   SIDEBAR: Colapsar / Expandir
   ============================================= */
var sidebar = document.getElementById('sidebar');
var sidebarToggle = document.getElementById('sidebarToggle');

if (sidebarToggle) {
    sidebarToggle.addEventListener('click', function() {
        document.body.classList.toggle('sidebar-collapsed');
    });
}

/* =============================================
   SIDEBAR: Submenús
   ============================================= */
var submenuItems = document.querySelectorAll('.nav-item.has-submenu > .nav-link');

submenuItems.forEach(function(link) {
    link.addEventListener('click', function(e) {
        e.preventDefault();

        // Si el sidebar está colapsado, no abrir submenú
        if (document.body.classList.contains('sidebar-collapsed')) {
            return;
        }

        var parentItem = this.parentElement;

        // Cerrar otros submenús abiertos
        document.querySelectorAll('.nav-item.has-submenu.open').forEach(function(item) {
            if (item !== parentItem) {
                item.classList.remove('open');
            }
        });

        // Alternar el actual
        parentItem.classList.toggle('open');
    });
});

/* =============================================
   SIDEBAR: Item activo
   ============================================= */
/*

var navLinks = document.querySelectorAll('.nav-link[data-page]');

navLinks.forEach(function(link) {
    link.addEventListener('click', function(e) {
        e.preventDefault();

        // Quitar active de todos
        document.querySelectorAll('.nav-item.active').forEach(function(item) {
            item.classList.remove('active');
        });

        // Poner active al padre
        this.parentElement.classList.add('active');

        // Cambiar breadcrumb
        var pageName = this.querySelector('.nav-text').textContent;
        var breadcrumbActive = document.querySelector('.breadcrumb-item.active');
        if (breadcrumbActive) {
            breadcrumbActive.textContent = pageName;
        }

        // Cerrar sidebar en móvil
        if (window.innerWidth <= 768) {
            sidebar.classList.remove('mobile-open');
            document.getElementById('sidebarOverlay').classList.remove('active');
        }
    });
});
*/

/* =============================================
   SIDEBAR: Navegación entre páginas
   ============================================= */
var navLinks = document.querySelectorAll('.nav-link[data-page]');

navLinks.forEach(function(link) {
    link.addEventListener('click', function(e) {
        e.preventDefault();

        if (document.querySelector('.modal-overlay.visible')) return;

        var page = this.getAttribute('data-page');

        // Activar modo módulo (oculta KPIs, charts, etc.)
        document.getElementById('contentArea').classList.add('modulo-activo');

        // Ocultar todos los contenedores de página
        document.querySelectorAll('[id^="page"]').forEach(function(container) {
            container.style.display = 'none';
        });

        // Mostrar la página seleccionada
        var targetPage = document.getElementById('page' + page);
        if (targetPage) {
            targetPage.style.display = '';
            document.dispatchEvent(new CustomEvent('pageChanged', { detail: { page: page } }));
        }

        // Quitar active de todos los nav-items
        document.querySelectorAll('.nav-item.active').forEach(function(item) {
            item.classList.remove('active');
        });

        // Poner active: si está dentro de un submenú, activar el padre del submenú
        var parentSubmenu = this.closest('.has-submenu');
        if (parentSubmenu) {
            parentSubmenu.classList.add('active');
        } else {
            this.parentElement.classList.add('active');
        }

        // Cambiar breadcrumb
        /*var pageName = this.querySelector('.nav-text').textContent;*/
        var spanText = this.querySelector('.nav-text');
        var pageName = spanText ? spanText.textContent : this.textContent.trim();
        var breadcrumbActive = document.querySelector('.breadcrumb-item.active');
        if (breadcrumbActive) {
            breadcrumbActive.textContent = pageName;
        }

        // Cerrar sidebar en móvil
        if (window.innerWidth <= 768) {
            sidebar.classList.remove('mobile-open');
            document.getElementById('sidebarOverlay').classList.remove('active');
        }
    });
});

// Clic en "Dashboard" o "Inicio" (links sin data-page)
/*
var dashboardLinks = document.querySelectorAll('.nav-link:not([data-page])');
dashboardLinks.forEach(function(link) {
    // Solo los que no son has-submenu ni logout
    if (!link.closest('.has-submenu') && !link.classList.contains('logout-link')) {
        link.addEventListener('click', function(e) {
            e.preventDefault();

            // Ocultar todos
            document.querySelectorAll('[id^="page"]').forEach(function(container) {
                container.style.display = 'none';
            });

            // Mostrar dashboard
            var dashPage = document.getElementById('pageDashboard');
            if (dashPage) dashPage.style.display = 'block';

            // Active
            document.querySelectorAll('.nav-item.active').forEach(function(item) {
                item.classList.remove('active');
            });
            this.parentElement.classList.add('active');

            // Breadcrumb
            var breadcrumbActive = document.querySelector('.breadcrumb-item.active');
            if (breadcrumbActive) breadcrumbActive.textContent = 'Dashboard';

            // Cerrar sidebar móvil
            if (window.innerWidth <= 768) {
                sidebar.classList.remove('mobile-open');
                document.getElementById('sidebarOverlay').classList.remove('active');
            }
        });
    }
});

*/

// Clic en "Dashboard" o "Inicio" (links sin data-page)
var dashboardLinks = document.querySelectorAll('.nav-link:not([data-page])');
dashboardLinks.forEach(function(link) {
    if (!link.closest('.has-submenu') && !link.classList.contains('logout-link')) {
        link.addEventListener('click', function(e) {
            e.preventDefault();

            if (document.querySelector('.modal-overlay.visible')) return;

            // Ocultar proveedores y mostrar dashboard
            document.getElementById('contentArea').classList.remove('modulo-activo');
            var provPage = document.getElementById('pageProveedores');
            if (provPage) provPage.style.display = 'none';

            // Active
            document.querySelectorAll('.nav-item.active').forEach(function(item) {
                item.classList.remove('active');
            });
            this.parentElement.classList.add('active');

            // Breadcrumb
            var breadcrumbActive = document.querySelector('.breadcrumb-item.active');
            if (breadcrumbActive) breadcrumbActive.textContent = 'Dashboard';

            // Cerrar sidebar móvil
            if (window.innerWidth <= 768) {
                sidebar.classList.remove('mobile-open');
                document.getElementById('sidebarOverlay').classList.remove('active');
            }
        });
    }
});


/* =============================================
   TOPBAR: Hamburguesa (móvil)
   ============================================= */
var topbarHamburger = document.getElementById('topbarHamburger');
var sidebarOverlay = document.getElementById('sidebarOverlay');

if (topbarHamburger) {
    topbarHamburger.addEventListener('click', function() {
        sidebar.classList.toggle('mobile-open');
        sidebarOverlay.classList.toggle('active');
    });
}

if (sidebarOverlay) {
    sidebarOverlay.addEventListener('click', function() {
        sidebar.classList.remove('mobile-open');
        this.classList.remove('active');
    });
}

/* =============================================
   ANIMACION DE ENTRADA DE LAS BARRAS
   ============================================= */
(function animateBars() {
    var bars = document.querySelectorAll('.bar');
    // Guardar altura final y poner en 0
    bars.forEach(function(bar) {
        var finalHeight = bar.style.height;
        bar.style.height = '0%';
        bar.dataset.final = finalHeight;
    });

    // Animar después de un breve delay
    setTimeout(function() {
        bars.forEach(function(bar, index) {
            setTimeout(function() {
                bar.style.height = bar.dataset.final;
            }, index * 50);
        });
    }, 300);
})();