/**
 * RSL Navbar Component
 *
 * Multi-level navigation component with dropdown menus, mega menus, and mobile support.
 * Provides full keyboard navigation, focus management, and ARIA compliance for
 * accessible navigation across all devices and input methods.
 *
 * @fileoverview Responsive navigation with dropdown and mega menu support
 * @version 2.1.0
 * @license MIT
 *
 * Key Features:
 * - Multi-level dropdown navigation with keyboard support
 * - Mega menu dropdowns with arbitrary HTML content
 * - Mobile hamburger menu with focus trap
 * - Full WCAG 2.1 AA compliance
 * - Arrow key navigation in dropdowns
 * - Tab key navigation in mega menus
 * - Escape key to close dropdowns and mobile menu
 * - Automatic ARIA attribute management
 * - Configurable dropdown trigger (click-only or hover on desktop)
 * - Smart viewport positioning to prevent overflow
 *
 * Usage:
 * // Basic navigation (auto-initialized):
 * <nav class="rsl-navbar">
 *   <a href="#" class="rsl-navbar-brand">Logo</a>
 *   <ul class="rsl-navbar-menu">
 *     <li class="rsl-navbar-item">
 *       <a href="#" class="rsl-navbar-link">Home</a>
 *     </li>
 *   </ul>
 * </nav>
 *
 * // With dropdown:
 * <li class="rsl-navbar-item">
 *   <a href="#" class="rsl-navbar-link">Products</a>
 *   <ul class="rsl-navbar-dropdown">
 *     <li class="rsl-navbar-item">
 *       <a href="#" class="rsl-navbar-link">Item</a>
 *     </li>
 *   </ul>
 * </li>
 *
 * // With mega menu:
 * <li class="rsl-navbar-item" data-menu-type="mega">
 *   <a href="#" class="rsl-navbar-link">Solutions</a>
 *   <div class="rsl-navbar-mega-menu">
 *     <!-- Arbitrary HTML content -->
 *   </div>
 * </li>
 *
 * // Enable hover mode (desktop only):
 * <nav class="rsl-navbar" data-hover-dropdowns="true">...</nav>
 *
 * // Layouts:
 * <nav class="rsl-navbar" data-layout="default">...</nav>      <!-- Logo left -->
 * <nav class="rsl-navbar" data-layout="logo-right">...</nav>   <!-- Logo right -->
 * <nav class="rsl-navbar" data-layout="logo-center">...</nav>  <!-- Logo center -->
 *
 * Public API:
 * - RSL.Navbar.init() - Initialize all navbars
 * - RSL.Navbar.open(element) - Open specific dropdown
 * - RSL.Navbar.close(element) - Close specific dropdown
 * - RSL.Navbar.toggle(element) - Toggle specific dropdown
 * - RSL.Navbar.closeAll() - Close all open dropdowns
 */

(function() {
    'use strict';

    // Initialize RSL namespace
    window.RSL = window.RSL || {};

    /**
     * Global navbar state management
     * @type {Object}
     * @property {boolean} mobileMenuOpen - Whether mobile menu is currently open
     * @property {HTMLElement|null} currentOpenNavbar - Reference to currently open navbar
     * @property {Array<HTMLElement>} openDropdowns - Array of currently open dropdown items
     * @property {HTMLElement|null} focusedElement - Currently focused element
     * @property {HTMLElement|null} lastFocusedBeforeMenu - Element that had focus before menu opened
     */
    const state = {
        mobileMenuOpen: false,
        currentOpenNavbar: null,
        openDropdowns: [],
        focusedElement: null,
        lastFocusedBeforeMenu: null
    };

    /**
     * Initialize all navbars on the page
     *
     * Finds all elements with .rsl-navbar class and sets up navigation,
     * dropdown, and accessibility features for each.
     *
     * @public
     *
     * @example
     * // Called automatically on DOMContentLoaded
     * // Can be called manually after dynamic content:
     * RSL.Navbar.init();
     */
    function init() {
        const navbars = document.querySelectorAll('.rsl-navbar');
        navbars.forEach(navbar => {
            setupNavbar(navbar);
        });
    }

    /**
     * Setup a single navbar instance
     *
     * Initializes all navbar features including ARIA attributes, layout,
     * mobile toggle, dropdowns, keyboard navigation, and click-outside handling.
     * Uses data-rsl-navbar-initialized attribute to prevent duplicate initialization.
     *
     * @param {HTMLElement} navbar - The navbar element to initialize
     *
     * @example
     * const navbar = document.querySelector('.rsl-navbar');
     * setupNavbar(navbar);
     */
    function setupNavbar(navbar) {
        // Prevent re-initialization - critical for JSON Layout API compatibility
        // where _initializeComponents() may call init() multiple times
        if (navbar.hasAttribute('data-rsl-navbar-initialized')) {
            return;
        }
        navbar.setAttribute('data-rsl-navbar-initialized', 'true');

        setupAria(navbar);
        setupNavbarLayout(navbar);
        setupMobileToggle(navbar);
        setupDropdowns(navbar);
        setupKeyboardNav(navbar);
        setupClickOutside(navbar);
    }

    /**
     * Setup navbar layout based on data-layout attribute
     *
     * Supports three layouts:
     * - default: Logo left, links right
     * - logo-right: Links left, logo right
     * - logo-center: Links split left and right with centered logo
     *
     * @param {HTMLElement} navbar - The navbar element
     *
     * @example
     * <nav class="rsl-navbar" data-layout="logo-center">...</nav>
     */
    function setupNavbarLayout(navbar) {
        const layout = navbar.getAttribute('data-layout');
        const brand = navbar.querySelector('.rsl-navbar-brand');
        const menu = navbar.querySelector('.rsl-navbar-menu');
        const toggle = navbar.querySelector('.rsl-navbar-toggle');

        if (!brand || !menu) return;

        if (!layout || layout === 'default') {
            return;
        }

        if (layout === 'logo-right') {
            navbar.classList.add('layout-logo-right');
            const referenceElement = toggle || menu;
            if (brand.compareDocumentPosition(referenceElement) & Node.DOCUMENT_POSITION_FOLLOWING) {
                navbar.appendChild(brand);
            }
        }

        if (layout === 'logo-center') {
            navbar.classList.add('layout-logo-center');

            const menuItems = Array.from(menu.children);
            const totalItems = menuItems.length;
            const leftCount = Math.floor(totalItems / 2);

            const leftMenu = document.createElement('ul');
            leftMenu.className = 'rsl-navbar-menu rsl-navbar-menu-left';
            leftMenu.setAttribute('role', 'menubar');
            leftMenu.setAttribute('aria-orientation', 'horizontal');

            for (let i = 0; i < leftCount; i++) {
                leftMenu.appendChild(menuItems[i]);
            }

            menu.classList.add('rsl-navbar-menu-right');
            navbar.insertBefore(leftMenu, brand);

            const leftItems = leftMenu.querySelectorAll('.rsl-navbar-item');
            leftItems.forEach(item => setupMenuItemAria(item, true));
        }
    }

    /**
     * Setup ARIA attributes for accessibility
     *
     * Applies appropriate ARIA roles, labels, and attributes to navbar,
     * menu, menu items, and dropdowns for screen reader support.
     *
     * @param {HTMLElement} navbar - The navbar element
     *
     * @example
     * setupAria(navbar);
     * // Applies: role="navigation", role="menubar", aria-haspopup, etc.
     */
    function setupAria(navbar) {
        if (!navbar.hasAttribute('role')) {
            navbar.setAttribute('role', 'navigation');
        }

        if (!navbar.hasAttribute('aria-label') && !navbar.hasAttribute('aria-labelledby')) {
            navbar.setAttribute('aria-label', 'Main navigation');
        }

        const menu = navbar.querySelector('.rsl-navbar-menu');
        if (menu) {
            menu.setAttribute('role', 'menubar');
            menu.setAttribute('aria-orientation', 'horizontal');
        }

        const topLevelItems = navbar.querySelectorAll('.rsl-navbar-menu > .rsl-navbar-item');
        topLevelItems.forEach(item => {
            setupMenuItemAria(item, true);
        });

        const dropdownItems = navbar.querySelectorAll('.rsl-navbar-dropdown .rsl-navbar-item');
        dropdownItems.forEach(item => {
            setupMenuItemAria(item, false);
        });

        const toggle = navbar.querySelector('.rsl-navbar-toggle');
        if (toggle) {
            toggle.setAttribute('aria-label', 'Toggle navigation menu');
            toggle.setAttribute('aria-expanded', 'false');
            toggle.setAttribute('aria-controls', menu ? menu.id || 'navbar-menu' : '');

            if (menu && !menu.id) {
                menu.id = 'navbar-menu';
            }
        }
    }

    /**
     * Setup ARIA attributes for a menu item
     *
     * Configures role, tabindex, aria-haspopup, and aria-expanded attributes
     * based on whether the item is top-level and whether it has a dropdown.
     *
     * @param {HTMLElement} item - The menu item element
     * @param {boolean} isTopLevel - Whether this is a top-level menu item
     *
     * @example
     * const item = document.querySelector('.rsl-navbar-item');
     * setupMenuItemAria(item, true);
     */
    function setupMenuItemAria(item, isTopLevel) {
        const link = item.querySelector('.rsl-navbar-link');
        const dropdown = item.querySelector('.rsl-navbar-dropdown');
        const megaMenu = item.querySelector('.rsl-navbar-mega-menu');
        const menuType = item.getAttribute('data-menu-type');

        if (!link) return;

        link.setAttribute('role', 'menuitem');
        link.setAttribute('tabindex', isTopLevel ? '0' : '-1');

        const menuElement = megaMenu || dropdown;
        if (menuElement) {
            link.setAttribute('aria-haspopup', 'true');
            link.setAttribute('aria-expanded', 'false');

            if (menuType === 'mega') {
                menuElement.setAttribute('role', 'region');
                menuElement.setAttribute('aria-label', 'Mega menu');
            } else {
                menuElement.setAttribute('role', 'menu');
                menuElement.setAttribute('aria-orientation', 'vertical');
            }

            if (!menuElement.id) {
                menuElement.id = `${menuType === 'mega' ? 'mega' : 'dropdown'}-${Math.random().toString(36).substr(2, 9)}`;
            }
            link.setAttribute('aria-controls', menuElement.id);
        }
    }

    /**
     * Setup mobile toggle functionality
     *
     * Configures hamburger menu button, creates overlay element,
     * and sets up event listeners for mobile menu interactions.
     *
     * @param {HTMLElement} navbar - The navbar element
     *
     * @example
     * setupMobileToggle(navbar);
     */
    function setupMobileToggle(navbar) {
        const toggle = navbar.querySelector('.rsl-navbar-toggle');
        const menu = navbar.querySelector('.rsl-navbar-menu');
        const overlay = document.createElement('div');

        if (!toggle || !menu) return;

        overlay.className = 'rsl-navbar-overlay';
        document.body.appendChild(overlay);

        toggle.addEventListener('click', (e) => {
            e.stopPropagation();
            toggleMobileMenu(navbar, toggle, menu, overlay);
        });

        overlay.addEventListener('click', () => {
            if (state.mobileMenuOpen) {
                closeMobileMenu(navbar, toggle, menu, overlay);
            }
        });

        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && state.mobileMenuOpen && state.currentOpenNavbar === navbar) {
                closeMobileMenu(navbar, toggle, menu, overlay);
            }
        });
    }

    /**
     * Toggle mobile menu open/closed state
     *
     * @param {HTMLElement} navbar - The navbar element
     * @param {HTMLElement} toggle - The toggle button
     * @param {HTMLElement} menu - The menu element
     * @param {HTMLElement} overlay - The overlay element
     *
     * @example
     * toggleMobileMenu(navbar, toggle, menu, overlay);
     */
    function toggleMobileMenu(navbar, toggle, menu, overlay) {
        if (state.mobileMenuOpen) {
            closeMobileMenu(navbar, toggle, menu, overlay);
        } else {
            openMobileMenu(navbar, toggle, menu, overlay);
        }
    }

    /**
     * Open mobile menu
     *
     * Opens the mobile navigation menu, activates overlay, locks body scroll,
     * saves previous focus, and activates focus trap.
     *
     * @param {HTMLElement} navbar - The navbar element
     * @param {HTMLElement} toggle - The toggle button
     * @param {HTMLElement} menu - The menu element
     * @param {HTMLElement} overlay - The overlay element
     *
     * @example
     * openMobileMenu(navbar, toggle, menu, overlay);
     */
    function openMobileMenu(navbar, toggle, menu, overlay) {
        state.lastFocusedBeforeMenu = document.activeElement;

        state.mobileMenuOpen = true;
        state.currentOpenNavbar = navbar;
        toggle.classList.add('active');
        toggle.setAttribute('aria-expanded', 'true');
        menu.classList.add('mobile-open');
        overlay.classList.add('active');
        document.body.style.overflow = 'hidden';

        const firstLink = menu.querySelector('.rsl-navbar-link');
        if (firstLink) {
            setTimeout(() => firstLink.focus(), 100);
        }

        setupFocusTrap(menu);
    }

    /**
     * Close mobile menu
     *
     * Closes the mobile navigation menu, removes overlay, restores body scroll,
     * closes all dropdowns, and restores previous focus.
     *
     * @param {HTMLElement} navbar - The navbar element
     * @param {HTMLElement} toggle - The toggle button
     * @param {HTMLElement} menu - The menu element
     * @param {HTMLElement} overlay - The overlay element
     *
     * @example
     * closeMobileMenu(navbar, toggle, menu, overlay);
     */
    function closeMobileMenu(navbar, toggle, menu, overlay) {
        state.mobileMenuOpen = false;
        state.currentOpenNavbar = null;
        toggle.classList.remove('active');
        toggle.setAttribute('aria-expanded', 'false');
        menu.classList.remove('mobile-open');
        overlay.classList.remove('active');
        document.body.style.overflow = '';

        closeAllDropdowns(navbar);

        if (state.lastFocusedBeforeMenu) {
            state.lastFocusedBeforeMenu.focus();
            state.lastFocusedBeforeMenu = null;
        }
    }

    /**
     * Setup focus trap for mobile menu
     *
     * Traps keyboard focus within the mobile menu when open, ensuring
     * Tab and Shift+Tab cycle through focusable elements in the menu.
     *
     * @param {HTMLElement} menu - The menu element
     *
     * @example
     * setupFocusTrap(menu);
     */
    function setupFocusTrap(menu) {
        const navbar = menu.closest('.rsl-navbar');
        const toggle = navbar.querySelector('.rsl-navbar-toggle');

        const menuFocusableElements = Array.from(menu.querySelectorAll('a, button, [tabindex]:not([tabindex="-1"])'));
        const focusableElements = toggle ? [toggle, ...menuFocusableElements] : menuFocusableElements;

        if (focusableElements.length === 0) return;

        const firstElement = focusableElements[0];
        const lastElement = focusableElements[focusableElements.length - 1];

        const handleTabKey = (e) => {
            if (!state.mobileMenuOpen) {
                document.removeEventListener('keydown', handleTabKey);
                return;
            }

            if (e.key !== 'Tab') return;

            if (e.shiftKey) {
                if (document.activeElement === firstElement) {
                    e.preventDefault();
                    lastElement.focus();
                }
            } else {
                if (document.activeElement === lastElement) {
                    e.preventDefault();
                    firstElement.focus();
                }
            }
        };

        document.addEventListener('keydown', handleTabKey);
    }

    /**
     * Setup dropdown interactions for desktop
     *
     * Configures click and optional hover interactions for dropdowns and mega menus.
     * Hover mode is enabled only when data-hover-dropdowns="true" and viewport > 768px.
     *
     * @param {HTMLElement} navbar - The navbar element
     *
     * @example
     * setupDropdowns(navbar);
     */
    function setupDropdowns(navbar) {
        const dropdownToggles = navbar.querySelectorAll('.rsl-navbar-item > .rsl-navbar-link[aria-haspopup="true"]');
        const hoverMode = navbar.getAttribute('data-hover-dropdowns') === 'true';

        dropdownToggles.forEach(toggle => {
            const item = toggle.parentElement;
            const dropdown = item.querySelector('.rsl-navbar-dropdown');
            const megaMenu = item.querySelector('.rsl-navbar-mega-menu');
            const menuElement = megaMenu || dropdown;

            if (!menuElement) return;

            toggle.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                toggleDropdown(item, toggle, menuElement);
            });

            if (hoverMode) {
                const handleMouseEnter = () => {
                    if (window.innerWidth > 768) {
                        openDropdown(item, toggle, menuElement);
                    }
                };

                const handleMouseLeave = () => {
                    if (window.innerWidth > 768) {
                        closeDropdown(item, toggle, menuElement);
                    }
                };

                item.addEventListener('mouseenter', handleMouseEnter);
                item.addEventListener('mouseleave', handleMouseLeave);
            }
        });
    }

    /**
     * Toggle dropdown open/closed state
     *
     * @param {HTMLElement} item - The menu item containing the dropdown
     * @param {HTMLElement} toggle - The toggle link element
     * @param {HTMLElement} dropdown - The dropdown menu element
     *
     * @example
     * toggleDropdown(item, toggle, dropdown);
     */
    function toggleDropdown(item, toggle, dropdown) {
        if (item.classList.contains('open')) {
            closeDropdown(item, toggle, dropdown);
        } else {
            openDropdown(item, toggle, dropdown);
        }
    }

    /**
     * Open dropdown menu
     *
     * Opens the dropdown, closes sibling dropdowns at same level,
     * updates ARIA attributes, enables focusable elements, and
     * positions menu to prevent viewport overflow.
     *
     * @param {HTMLElement} item - The menu item containing the dropdown
     * @param {HTMLElement} toggle - The toggle link element
     * @param {HTMLElement} dropdown - The dropdown menu element (or mega menu)
     *
     * @example
     * openDropdown(item, toggle, dropdown);
     */
    function openDropdown(item, toggle, dropdown) {
        const siblings = Array.from(item.parentElement.children).filter(el =>
            el !== item && el.classList.contains('rsl-navbar-item')
        );
        siblings.forEach(sibling => {
            const siblingToggle = sibling.querySelector('.rsl-navbar-link[aria-haspopup="true"]');
            const siblingDropdown = sibling.querySelector('.rsl-navbar-dropdown');
            const siblingMegaMenu = sibling.querySelector('.rsl-navbar-mega-menu');
            const siblingMenu = siblingMegaMenu || siblingDropdown;

            if (siblingToggle && siblingMenu) {
                closeDropdown(sibling, siblingToggle, siblingMenu);
            }
        });

        item.classList.add('open');
        toggle.setAttribute('aria-expanded', 'true');
        state.openDropdowns.push(item);

        const isMegaMenu = dropdown.classList.contains('rsl-navbar-mega-menu');
        if (isMegaMenu) {
            const focusableElements = dropdown.querySelectorAll('a, button, input, select, textarea, [tabindex]');
            focusableElements.forEach(el => {
                const currentTabindex = el.getAttribute('tabindex');
                if (currentTabindex !== '-1') {
                    el.setAttribute('tabindex', '0');
                }
            });

            if (window.innerWidth > 768) {
                positionMegaMenu(item, dropdown);
            }
        } else {
            const dropdownLinks = dropdown.querySelectorAll('.rsl-navbar-link');
            dropdownLinks.forEach(link => link.setAttribute('tabindex', '0'));

            if (window.innerWidth > 768) {
                positionDropdown(item, dropdown);
            }
        }
    }

    /**
     * Position mega menu to prevent viewport overflow
     *
     * Checks if mega menu extends beyond viewport edges and applies
     * alignment classes to reposition it within viewport bounds.
     *
     * @param {HTMLElement} item - The menu item containing the mega menu
     * @param {HTMLElement} megaMenu - The mega menu element
     *
     * @example
     * positionMegaMenu(item, megaMenu);
     */
    function positionMegaMenu(item, megaMenu) {
        megaMenu.classList.remove('align-right', 'align-left');

        requestAnimationFrame(() => {
            const rect = megaMenu.getBoundingClientRect();
            const viewportWidth = window.innerWidth;

            if (rect.right > viewportWidth) {
                megaMenu.classList.add('align-right');
            }
            else if (rect.left < 0) {
                megaMenu.classList.add('align-left');
            }
        });
    }

    /**
     * Position regular dropdown to prevent viewport overflow
     *
     * Checks if dropdown extends beyond viewport right edge and applies
     * alignment class to reposition it.
     *
     * @param {HTMLElement} item - The menu item containing the dropdown
     * @param {HTMLElement} dropdown - The dropdown element
     *
     * @example
     * positionDropdown(item, dropdown);
     */
    function positionDropdown(item, dropdown) {
        // Check if this is a nested dropdown (inside another dropdown)
        const isNested = item.closest('.rsl-navbar-dropdown') !== null;

        if (isNested) {
            // For nested dropdowns, add align-right to the ITEM (parent)
            // CSS selector: .rsl-navbar-dropdown .rsl-navbar-item.align-right > .rsl-navbar-dropdown
            item.classList.remove('align-right');
        } else {
            // For top-level dropdowns, add align-right to the dropdown itself
            dropdown.classList.remove('align-right');
        }

        requestAnimationFrame(() => {
            const rect = dropdown.getBoundingClientRect();
            const viewportWidth = window.innerWidth;

            if (rect.right > viewportWidth) {
                if (isNested) {
                    item.classList.add('align-right');
                } else {
                    dropdown.classList.add('align-right');
                }
            }
        });
    }

    /**
     * Close dropdown menu
     *
     * Closes the dropdown, updates ARIA attributes, removes positioning classes,
     * closes nested dropdowns, and disables focusable elements.
     *
     * @param {HTMLElement} item - The menu item containing the dropdown
     * @param {HTMLElement} toggle - The toggle link element
     * @param {HTMLElement} dropdown - The dropdown menu element (or mega menu)
     *
     * @example
     * closeDropdown(item, toggle, dropdown);
     */
    function closeDropdown(item, toggle, dropdown) {
        item.classList.remove('open');
        toggle.setAttribute('aria-expanded', 'false');

        state.openDropdowns = state.openDropdowns.filter(el => el !== item);

        // Remove alignment classes from both dropdown and item (for nested dropdowns)
        dropdown.classList.remove('align-right', 'align-left');
        item.classList.remove('align-right');

        const nestedItems = dropdown.querySelectorAll('.rsl-navbar-item.open');
        nestedItems.forEach(nestedItem => {
            const nestedToggle = nestedItem.querySelector('.rsl-navbar-link[aria-haspopup="true"]');
            const nestedDropdown = nestedItem.querySelector('.rsl-navbar-dropdown');
            const nestedMegaMenu = nestedItem.querySelector('.rsl-navbar-mega-menu');
            const nestedMenu = nestedMegaMenu || nestedDropdown;

            if (nestedToggle && nestedMenu) {
                closeDropdown(nestedItem, nestedToggle, nestedMenu);
            }
        });

        const isMegaMenu = dropdown.classList.contains('rsl-navbar-mega-menu');
        if (isMegaMenu) {
            const focusableElements = dropdown.querySelectorAll('a, button, input, select, textarea, [tabindex]');
            focusableElements.forEach(el => {
                const currentTabindex = el.getAttribute('tabindex');
                if (currentTabindex === '0') {
                    el.setAttribute('tabindex', '-1');
                }
            });
        } else {
            const dropdownLinks = dropdown.querySelectorAll('.rsl-navbar-link');
            dropdownLinks.forEach(link => link.setAttribute('tabindex', '-1'));
        }
    }

    /**
     * Close all open dropdowns in navbar
     *
     * @param {HTMLElement} navbar - The navbar element
     *
     * @example
     * closeAllDropdowns(navbar);
     */
    function closeAllDropdowns(navbar) {
        const openItems = navbar.querySelectorAll('.rsl-navbar-item.open');
        openItems.forEach(item => {
            const toggle = item.querySelector('.rsl-navbar-link[aria-haspopup="true"]');
            const dropdown = item.querySelector('.rsl-navbar-dropdown');
            const megaMenu = item.querySelector('.rsl-navbar-mega-menu');
            const menuElement = megaMenu || dropdown;

            if (toggle && menuElement) {
                closeDropdown(item, toggle, menuElement);
            }
        });
        state.openDropdowns = [];
    }

    /**
     * Setup keyboard navigation
     *
     * Implements keyboard navigation for menus and dropdowns:
     * - Arrow keys: Navigate between items
     * - Enter/Space: Open/close dropdowns
     * - Escape: Close dropdowns
     * - Tab: Navigate in mega menus
     * - Home/End: Jump to first/last item
     *
     * @param {HTMLElement} navbar - The navbar element
     *
     * @example
     * setupKeyboardNav(navbar);
     */
    function setupKeyboardNav(navbar) {
        const menu = navbar.querySelector('.rsl-navbar-menu');
        if (!menu) return;

        menu.addEventListener('keydown', (e) => {
            const target = e.target;

            const inMegaMenu = target.closest('.rsl-navbar-mega-menu');
            if (inMegaMenu && e.key === 'Tab') {
                const megaMenuItem = inMegaMenu.closest('.rsl-navbar-item');
                const megaToggle = megaMenuItem.querySelector('.rsl-navbar-link[aria-haspopup="true"]');
                const focusableElements = Array.from(inMegaMenu.querySelectorAll('a, button, input, select, textarea, [tabindex]:not([tabindex="-1"])'));

                if (focusableElements.length > 0) {
                    const firstElement = focusableElements[0];
                    const lastElement = focusableElements[focusableElements.length - 1];

                    if (!e.shiftKey && target === lastElement) {
                        setTimeout(() => {
                            closeDropdown(megaMenuItem, megaToggle, inMegaMenu);
                        }, 0);
                    }
                    else if (e.shiftKey && target === firstElement) {
                        e.preventDefault();
                        closeDropdown(megaMenuItem, megaToggle, inMegaMenu);
                        megaToggle.focus();
                    }
                }
                return;
            }

            if (!target.classList.contains('rsl-navbar-link')) return;

            const item = target.closest('.rsl-navbar-item');
            const isTopLevel = item.parentElement === menu;
            const hasDropdown = target.getAttribute('aria-haspopup') === 'true';
            const menuType = item.getAttribute('data-menu-type');

            switch (e.key) {
                case 'ArrowRight':
                    e.preventDefault();
                    if (isTopLevel) {
                        focusNextSibling(item);
                    } else if (hasDropdown && menuType !== 'mega') {
                        const dropdown = item.querySelector('.rsl-navbar-dropdown');
                        if (dropdown) {
                            openDropdown(item, target, dropdown);
                            const firstLink = dropdown.querySelector('.rsl-navbar-link');
                            if (firstLink) firstLink.focus();
                        }
                    }
                    break;

                case 'ArrowLeft':
                    e.preventDefault();
                    if (isTopLevel) {
                        focusPreviousSibling(item);
                    } else if (menuType !== 'mega') {
                        const parentItem = item.closest('.rsl-navbar-dropdown').closest('.rsl-navbar-item');
                        if (parentItem) {
                            const parentToggle = parentItem.querySelector('.rsl-navbar-link[aria-haspopup="true"]');
                            const parentDropdown = parentItem.querySelector('.rsl-navbar-dropdown');
                            if (parentToggle && parentDropdown) {
                                closeDropdown(parentItem, parentToggle, parentDropdown);
                                parentToggle.focus();
                            }
                        }
                    }
                    break;

                case 'ArrowDown':
                    e.preventDefault();
                    if (hasDropdown && !item.classList.contains('open')) {
                        const dropdown = item.querySelector('.rsl-navbar-dropdown');
                        const megaMenu = item.querySelector('.rsl-navbar-mega-menu');
                        const menuElement = megaMenu || dropdown;

                        if (menuElement) {
                            openDropdown(item, target, menuElement);

                            if (megaMenu) {
                                const firstFocusable = megaMenu.querySelector('a, button, [tabindex]:not([tabindex="-1"])');
                                if (firstFocusable) firstFocusable.focus();
                            } else {
                                const firstLink = dropdown.querySelector('.rsl-navbar-link');
                                if (firstLink) firstLink.focus();
                            }
                        }
                    } else if (menuType !== 'mega') {
                        focusNextInDropdown(item);
                    }
                    break;

                case 'ArrowUp':
                    e.preventDefault();
                    focusPreviousInDropdown(item);
                    break;

                case 'Escape':
                    e.preventDefault();
                    const dropdown = target.closest('.rsl-navbar-dropdown');
                    if (dropdown) {
                        const parentItem = dropdown.closest('.rsl-navbar-item');
                        if (parentItem) {
                            const parentToggle = parentItem.querySelector('.rsl-navbar-link[aria-haspopup="true"]');
                            if (parentToggle) {
                                closeDropdown(parentItem, parentToggle, dropdown);
                                parentToggle.focus();
                            }
                        }
                    }
                    break;

                case 'Enter':
                case ' ':
                    if (hasDropdown) {
                        e.preventDefault();
                        const dropdown = item.querySelector('.rsl-navbar-dropdown');
                        const megaMenu = item.querySelector('.rsl-navbar-mega-menu');
                        const menuElement = megaMenu || dropdown;

                        if (menuElement) {
                            toggleDropdown(item, target, menuElement);
                            if (item.classList.contains('open')) {
                                if (megaMenu) {
                                    const firstFocusable = megaMenu.querySelector('a, button, input, select, textarea, [tabindex]:not([tabindex="-1"])');
                                    if (firstFocusable) firstFocusable.focus();
                                } else {
                                    const firstLink = dropdown.querySelector('.rsl-navbar-link');
                                    if (firstLink) firstLink.focus();
                                }
                            }
                        }
                    }
                    break;

                case 'Home':
                    e.preventDefault();
                    const firstItem = isTopLevel ?
                        menu.querySelector('.rsl-navbar-item .rsl-navbar-link') :
                        item.closest('.rsl-navbar-dropdown').querySelector('.rsl-navbar-link');
                    if (firstItem) firstItem.focus();
                    break;

                case 'End':
                    e.preventDefault();
                    const items = isTopLevel ?
                        menu.querySelectorAll('.rsl-navbar-menu > .rsl-navbar-item .rsl-navbar-link') :
                        item.closest('.rsl-navbar-dropdown').querySelectorAll('.rsl-navbar-link');
                    const lastItem = items[items.length - 1];
                    if (lastItem) lastItem.focus();
                    break;
            }
        });
    }

    /**
     * Focus next sibling menu item at same level
     *
     * Wraps to first item if at end of list.
     *
     * @param {HTMLElement} currentItem - Current menu item
     *
     * @example
     * focusNextSibling(item);
     */
    function focusNextSibling(currentItem) {
        const nextItem = currentItem.nextElementSibling;
        if (nextItem && nextItem.classList.contains('rsl-navbar-item')) {
            const link = nextItem.querySelector('.rsl-navbar-link');
            if (link) link.focus();
        } else {
            const parent = currentItem.parentElement;
            const firstItem = parent.querySelector('.rsl-navbar-item');
            if (firstItem) {
                const link = firstItem.querySelector('.rsl-navbar-link');
                if (link) link.focus();
            }
        }
    }

    /**
     * Focus previous sibling menu item at same level
     *
     * Wraps to last item if at start of list.
     *
     * @param {HTMLElement} currentItem - Current menu item
     *
     * @example
     * focusPreviousSibling(item);
     */
    function focusPreviousSibling(currentItem) {
        const prevItem = currentItem.previousElementSibling;
        if (prevItem && prevItem.classList.contains('rsl-navbar-item')) {
            const link = prevItem.querySelector('.rsl-navbar-link');
            if (link) link.focus();
        } else {
            const parent = currentItem.parentElement;
            const items = parent.querySelectorAll('.rsl-navbar-item');
            const lastItem = items[items.length - 1];
            if (lastItem) {
                const link = lastItem.querySelector('.rsl-navbar-link');
                if (link) link.focus();
            }
        }
    }

    /**
     * Focus next item in dropdown menu
     *
     * Does not wrap to first item if at end.
     *
     * @param {HTMLElement} currentItem - Current menu item
     *
     * @example
     * focusNextInDropdown(item);
     */
    function focusNextInDropdown(currentItem) {
        const nextItem = currentItem.nextElementSibling;
        if (nextItem && nextItem.classList.contains('rsl-navbar-item')) {
            const link = nextItem.querySelector('.rsl-navbar-link');
            if (link) link.focus();
        }
    }

    /**
     * Focus previous item in dropdown menu
     *
     * Does not wrap to last item if at start.
     *
     * @param {HTMLElement} currentItem - Current menu item
     *
     * @example
     * focusPreviousInDropdown(item);
     */
    function focusPreviousInDropdown(currentItem) {
        const prevItem = currentItem.previousElementSibling;
        if (prevItem && prevItem.classList.contains('rsl-navbar-item')) {
            const link = prevItem.querySelector('.rsl-navbar-link');
            if (link) link.focus();
        }
    }

    /**
     * Setup click-outside handler to close dropdowns
     *
     * Closes all open dropdowns when user clicks outside navbar,
     * except when mobile menu is open.
     *
     * @param {HTMLElement} navbar - The navbar element
     *
     * @example
     * setupClickOutside(navbar);
     */
    function setupClickOutside(navbar) {
        document.addEventListener('click', (e) => {
            if (!navbar.contains(e.target) && !state.mobileMenuOpen) {
                closeAllDropdowns(navbar);
            }
        });
    }

    /**
     * Public API
     *
     * @namespace RSL.Navbar
     * @property {Function} init - Initialize all navbars
     * @property {Function} open - Open specific dropdown
     * @property {Function} close - Close specific dropdown
     * @property {Function} toggle - Toggle specific dropdown
     * @property {Function} closeAll - Close all open dropdowns
     */
    window.RSL.Navbar = {
        init: init,

        /**
         * Open a specific dropdown
         *
         * @param {HTMLElement} element - The menu item or link element
         *
         * @example
         * const menuItem = document.querySelector('.rsl-navbar-item');
         * RSL.Navbar.open(menuItem);
         */
        open: function(element) {
            const item = element.classList.contains('rsl-navbar-item') ?
                element : element.closest('.rsl-navbar-item');
            const toggle = item.querySelector('.rsl-navbar-link[aria-haspopup="true"]');
            const dropdown = item.querySelector('.rsl-navbar-dropdown');

            if (toggle && dropdown) {
                openDropdown(item, toggle, dropdown);
            }
        },

        /**
         * Close a specific dropdown
         *
         * @param {HTMLElement} element - The menu item or link element
         *
         * @example
         * const menuItem = document.querySelector('.rsl-navbar-item');
         * RSL.Navbar.close(menuItem);
         */
        close: function(element) {
            const item = element.classList.contains('rsl-navbar-item') ?
                element : element.closest('.rsl-navbar-item');
            const toggle = item.querySelector('.rsl-navbar-link[aria-haspopup="true"]');
            const dropdown = item.querySelector('.rsl-navbar-dropdown');

            if (toggle && dropdown) {
                closeDropdown(item, toggle, dropdown);
            }
        },

        /**
         * Toggle a specific dropdown
         *
         * @param {HTMLElement} element - The menu item or link element
         *
         * @example
         * const menuItem = document.querySelector('.rsl-navbar-item');
         * RSL.Navbar.toggle(menuItem);
         */
        toggle: function(element) {
            const item = element.classList.contains('rsl-navbar-item') ?
                element : element.closest('.rsl-navbar-item');
            const toggle = item.querySelector('.rsl-navbar-link[aria-haspopup="true"]');
            const dropdown = item.querySelector('.rsl-navbar-dropdown');

            if (toggle && dropdown) {
                toggleDropdown(item, toggle, dropdown);
            }
        },

        /**
         * Close all open dropdowns in all navbars
         *
         * @example
         * RSL.Navbar.closeAll();
         */
        closeAll: function() {
            const navbars = document.querySelectorAll('.rsl-navbar');
            navbars.forEach(navbar => closeAllDropdowns(navbar));
        }
    };

    /**
     * Auto-initialize on DOM ready or immediately if already loaded
     */
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

    /**
     * Observe DOM for dynamically added navbars
     *
     * Uses MutationObserver to automatically initialize navbars
     * that are added to the DOM after initial page load.
     */
    if (window.MutationObserver) {
        const observer = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
                mutation.addedNodes.forEach(node => {
                    if (node.nodeType === 1) {
                        if (node.matches && node.matches('.rsl-navbar')) {
                            setupNavbar(node);
                        }
                    }
                });
            });
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }

})();
