// ============================================================================
// ENTERPRISE WMS - LAYOUT JS
// Enhanced menu detection, sidebar state management, responsive behavior
// ============================================================================

(function (window) {
    'use strict';

    const Layout = {
        // Configuration
        config: {
            sidebarSelector: '.enterprise-sidebar',
            menuLinkSelector: '.enterprise-menu-link',
            submenuSelector: '.enterprise-submenu',
            activeClass: 'active',
            submenuOpenClass: 'active',
            breakpoint: 992,
            sidebarStorageKey: 'ships-wms-sidebar-state'
        },

        // Initialize
        init: function () {
            this.setupMenuHandlers();
            this.detectActivePage();
            this.setupMobileToggle();
            this.restoreSidebarState();
            this.setupResponsiveBehavior();
            console.log('Enterprise Layout initialized');
        },

        // Setup menu toggle handlers
        setupMenuHandlers: function () {
            const self = this;
            const menuToggles = document.querySelectorAll('.enterprise-menu-toggle');

            menuToggles.forEach(toggle => {
                toggle.addEventListener('click', function (e) {
                    e.preventDefault();
                    self.toggleSubmenu(this);
                });
            });
        },

        // Toggle submenu visibility
        toggleSubmenu: function (toggleElement) {
            const parentItem = toggleElement.closest('.enterprise-menu-item');
            if (!parentItem) return;

            parentItem.classList.toggle(this.config.submenuOpenClass);
            this.saveSidebarState();
        },

        // Detect active page and highlight menu
        detectActivePage: function () {
            const path = window.location.pathname.toLowerCase();
            const menuLinks = document.querySelectorAll(this.config.menuLinkSelector);

            menuLinks.forEach(link => {
                const href = link.getAttribute('href');
                if (!href || href === '#') return;

                try {
                    const linkPath = new URL(href, window.location.origin).pathname.toLowerCase();

                    if (linkPath === path) {
                        // Highlight this link
                        link.classList.add(this.config.activeClass);

                        // Open parent menus
                        let parent = link.closest('.enterprise-menu-item.has-submenu');
                        while (parent) {
                            parent.classList.add(this.config.submenuOpenClass);
                            const parentMenu = parent.parentElement.closest('.enterprise-menu-item.has-submenu');
                            parent = parentMenu;
                        }

                        this.saveSidebarState();
                    }
                } catch (e) {
                    // Ignore invalid URLs
                }
            });
        },

        // Mobile sidebar toggle
        setupMobileToggle: function () {
            const self = this;
            const toggleBtn = document.getElementById('navbarMobileToggle');
            const sidebarOverlay = document.getElementById('sidebarOverlay');
            const sidebar = document.querySelector(this.config.sidebarSelector);

            if (!toggleBtn || !sidebar) return;

            // Toggle button
            toggleBtn.addEventListener('click', function () {
                self.toggleSidebar();
            });

            // Overlay click
            if (sidebarOverlay) {
                sidebarOverlay.addEventListener('click', function () {
                    self.closeSidebar();
                });
            }

            // Close sidebar on link click (mobile)
            const menuLinks = document.querySelectorAll(this.config.menuLinkSelector);
            menuLinks.forEach(link => {
                link.addEventListener('click', function () {
                    if (window.innerWidth < self.config.breakpoint) {
                        setTimeout(() => self.closeSidebar(), 300);
                    }
                });
            });
        },

        // Toggle sidebar
        toggleSidebar: function () {
            const sidebar = document.querySelector(this.config.sidebarSelector);
            const overlay = document.getElementById('sidebarOverlay');
            if (!sidebar) return;

            const isOpen = sidebar.classList.contains('active');
            if (isOpen) {
                this.closeSidebar();
            } else {
                this.openSidebar();
            }
        },

        // Open sidebar
        openSidebar: function () {
            const sidebar = document.querySelector(this.config.sidebarSelector);
            const overlay = document.getElementById('sidebarOverlay');
            if (!sidebar) return;

            sidebar.classList.add('active');
            if (overlay) overlay.classList.add('active');
            document.body.style.overflow = 'hidden';
            this.saveSidebarState();
        },

        // Close sidebar
        closeSidebar: function () {
            const sidebar = document.querySelector(this.config.sidebarSelector);
            const overlay = document.getElementById('sidebarOverlay');
            if (!sidebar) return;

            sidebar.classList.remove('active');
            if (overlay) overlay.classList.remove('active');
            document.body.style.overflow = '';
            this.saveSidebarState();
        },

        // Save sidebar state to localStorage
        saveSidebarState: function () {
            try {
                const sidebar = document.querySelector(this.config.sidebarSelector);
                const state = {
                    isOpen: sidebar ? sidebar.classList.contains('active') : false,
                    expandedMenus: this.getExpandedMenus()
                };
                localStorage.setItem(this.config.sidebarStorageKey, JSON.stringify(state));
            } catch (e) {
                console.warn('Could not save sidebar state:', e);
            }
        },

        // Restore sidebar state from localStorage
        restoreSidebarState: function () {
            try {
                const state = localStorage.getItem(this.config.sidebarStorageKey);
                if (!state) return;

                const parsed = JSON.parse(state);

                // Restore expanded menus
                if (parsed.expandedMenus && Array.isArray(parsed.expandedMenus)) {
                    parsed.expandedMenus.forEach(menuText => {
                        const menuItems = document.querySelectorAll('.enterprise-menu-item.has-submenu');
                        menuItems.forEach(item => {
                            const text = item.querySelector('.enterprise-menu-text');
                            if (text && text.textContent === menuText) {
                                item.classList.add(this.config.submenuOpenClass);
                            }
                        });
                    });
                }
            } catch (e) {
                console.warn('Could not restore sidebar state:', e);
            }
        },

        // Get list of expanded menus
        getExpandedMenus: function () {
            const expanded = [];
            const openMenus = document.querySelectorAll(`.enterprise-menu-item.has-submenu.${this.config.submenuOpenClass}`);
            openMenus.forEach(menu => {
                const text = menu.querySelector('.enterprise-menu-text');
                if (text) expanded.push(text.textContent);
            });
            return expanded;
        },

        // Handle responsive behavior
        setupResponsiveBehavior: function () {
            const self = this;
            let resizeTimer;

            window.addEventListener('resize', function () {
                clearTimeout(resizeTimer);
                resizeTimer = setTimeout(function () {
                    self.handleResponsiveResize();
                }, 250);
            });
        },

        // Handle resize events
        handleResponsiveResize: function () {
            const sidebar = document.querySelector(this.config.sidebarSelector);
            if (!sidebar) return;

            if (window.innerWidth >= this.config.breakpoint) {
                // Desktop: sidebar should be visible
                sidebar.classList.remove('active');
                document.body.style.overflow = '';
            }
        },

        // Utility: Add active class based on controller/action
        setActiveByRoute: function (controller, action) {
            const links = document.querySelectorAll(this.config.menuLinkSelector);
            links.forEach(link => {
                const href = link.getAttribute('href');
                if (href && href.includes(`/${controller}`) && href.includes(`/${action}`)) {
                    link.classList.add(this.config.activeClass);
                }
            });
        }
    };

    // Auto-initialize when DOM is ready
    document.addEventListener('DOMContentLoaded', function () {
        Layout.init();
    });

    // Expose to window for external use
    window.EnterpriseLayout = Layout;

})(window);
