/*!
    * Start Bootstrap - SB Admin v7.0.4 (https://startbootstrap.com/template/sb-admin)
    * Copyright 2013-2021 Start Bootstrap
    * Licensed under MIT (https://github.com/StartBootstrap/startbootstrap-sb-admin/blob/master/LICENSE)
    */
// 
// Scripts
// 

window.addEventListener('DOMContentLoaded', event => {

    // Toggle the side navigation
    const sidebarToggle = document.body.querySelector('#sidebarToggle');
    if (sidebarToggle) {
        // Restore sidebar state from localStorage
        if (localStorage.getItem('sb|sidebar-toggle') === 'true') {
            document.body.classList.toggle('sb-sidenav-toggled');
        }

        sidebarToggle.addEventListener('click', event => {
            event.preventDefault();
            document.body.classList.toggle('sb-sidenav-toggled');
            localStorage.setItem('sb|sidebar-toggle', document.body.classList.contains('sb-sidenav-toggled'));
        });
    }

    // Save scroll position before page unload
    window.addEventListener('beforeunload', () => {
        const scrollPos = window.scrollY || document.documentElement.scrollTop;
        sessionStorage.setItem('scrollPosition', scrollPos);
    });

    // Restore scroll position on page load
    const savedScrollPos = sessionStorage.getItem('scrollPosition');
    if (savedScrollPos) {
        // Use requestAnimationFrame to ensure DOM is ready
        requestAnimationFrame(() => {
            window.scrollTo({
                top: parseInt(savedScrollPos),
                behavior: 'auto' // Instant scroll on page load
            });
        });
    }

    // ===================================
    // SIDEBAR ACTIVE ITEM HIGHLIGHTING & AUTO-SCROLL
    // ===================================

    const currentPage = window.location.pathname.split('/').pop();
    const currentFullPath = window.location.pathname;
    const sidebarNav = document.querySelector('.sb-sidenav-menu');

    if (sidebarNav && currentPage) {
        // Find all nav links in sidebar
        const navLinks = sidebarNav.querySelectorAll('.nav-link');
        let activeLink = null;

        // Find the link that matches current page
        navLinks.forEach(link => {
            const linkHref = link.getAttribute('href');
            if (linkHref) {
                // Extract filename from link href
                const linkPage = linkHref.split('/').pop().split('?')[0]; // Remove query params
                const linkFullPath = linkHref;

                // Match by filename OR full path (for vendor portal absolute paths)
                const isMatch = linkPage === currentPage ||
                    linkFullPath === currentFullPath ||
                    currentFullPath.includes(linkHref);

                if (isMatch && linkHref !== '#') { // Ignore collapse toggles
                    activeLink = link;

                    // Add active class to the link
                    link.classList.add('active');

                    // If link is inside a collapse menu, expand it
                    const parentCollapse = link.closest('.collapse');
                    if (parentCollapse) {
                        // Show the parent collapse
                        parentCollapse.classList.add('show');

                        // Find the toggle button for this collapse
                        const collapseId = parentCollapse.getAttribute('id');
                        const toggleBtn = document.querySelector(`[data-bs-target="#${collapseId}"]`);
                        if (toggleBtn) {
                            toggleBtn.classList.remove('collapsed');
                            toggleBtn.setAttribute('aria-expanded', 'true');
                        }
                    }
                }
            }
        });

        // Scroll sidebar to active item
        if (activeLink) {
            // Wait for collapse animation to finish
            setTimeout(() => {
                const sidebarContainer = document.querySelector('#layoutSidenav_nav');
                if (sidebarContainer) {
                    const linkRect = activeLink.getBoundingClientRect();
                    const containerRect = sidebarContainer.getBoundingClientRect();

                    // Calculate if link is out of view
                    const isOutOfView = linkRect.top < containerRect.top ||
                        linkRect.bottom > containerRect.bottom;

                    if (isOutOfView) {
                        // Scroll to center the active link
                        activeLink.scrollIntoView({
                            behavior: 'smooth',
                            block: 'center'
                        });
                    }
                }
            }, 100); // Small delay to let collapse animation start
        }
    }

});
