/**
 * File navigation.js.
 *
 * Handles toggling the navigation menu for small screens and enables TAB key navigation support for dropdown menus.
 * Enhanced for keyboard accessibility with Enter/Space toggle for submenus.
 */
(function () {
    const siteNavigation = document.getElementById('site-navigation');

    // Return early if the navigation doesn't exist.
    if (!siteNavigation) {
        return;
    }

    const button = siteNavigation.getElementsByTagName('button')[0];

    // Return early if the button doesn't exist.
    if ('undefined' === typeof button) {
        return;
    }

    const menu = siteNavigation.getElementsByTagName('ul')[0];

    // Hide menu toggle button if menu is empty and return early.
    if ('undefined' === typeof menu) {
        button.style.display = 'none';
        return;
    }

    if (!menu.classList.contains('nav-menu')) {
        menu.classList.add('nav-menu');
    }

    // Toggle the .toggled class and the aria-expanded value each time the button is clicked.
    button.addEventListener('click', function () {
        siteNavigation.classList.toggle('toggled');

        if (button.getAttribute('aria-expanded') === 'true') {
            button.setAttribute('aria-expanded', 'false');
        } else {
            button.setAttribute('aria-expanded', 'true');
        }
    });

    // Remove the .toggled class and set aria-expanded to false when the user clicks outside the navigation.
    document.addEventListener('click', function (event) {
        const isClickInside = siteNavigation.contains(event.target);

        if (!isClickInside) {
            siteNavigation.classList.remove('toggled');
            button.setAttribute('aria-expanded', 'false');
        }
    });

    // =========================================
    // Keyboard Accessible Dropdown Menus
    // =========================================

    // Get all menu items with children (has dropdown)
    const menuItemsWithChildren = menu.querySelectorAll('.menu-item-has-children, .blog-over-has-dropdown');
    const subMenus = menu.getElementsByTagName('ul');

    // Set initial ARIA states for all sub-menus
    for (let i = 0; i < subMenus.length; i++) {
        if (!subMenus[i].classList.contains('sub-menu')) {
            subMenus[i].classList.add('sub-menu');
        }
        subMenus[i].setAttribute('aria-hidden', 'true');
        subMenus[i].parentNode.setAttribute('aria-haspopup', 'true');
    }

    // Process each menu item with children
    menuItemsWithChildren.forEach(function (menuItem) {
        const link = menuItem.querySelector(':scope > a');
        const dropdownToggle = menuItem.querySelector(':scope > .blog-over-dropdown-toggle, :scope > button.dropdown-toggle');
        const subMenu = menuItem.querySelector(':scope > ul');

        if (!subMenu) return;

        // Make submenu items not focusable when closed
        setSubMenuTabIndex(subMenu, -1);

        // =========================================
        // Dropdown Toggle Button (Chevron) - Click Handler
        // =========================================
        if (dropdownToggle) {
            dropdownToggle.addEventListener('click', function (e) {
                e.preventDefault();
                e.stopPropagation();
                toggleSubmenu(menuItem, subMenu, dropdownToggle);
            });

            // Keyboard: Enter/Space on toggle button
            dropdownToggle.addEventListener('keydown', function (e) {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    e.stopPropagation();
                    toggleSubmenu(menuItem, subMenu, dropdownToggle);

                    // If opening, focus first submenu link
                    if (menuItem.classList.contains('submenu-open')) {
                        const firstLink = subMenu.querySelector('a');
                        if (firstLink) {
                            setTimeout(function () {
                                firstLink.focus();
                            }, 50);
                        }
                    }
                }

                // Arrow Down: Open submenu and focus first item
                if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    if (!menuItem.classList.contains('submenu-open')) {
                        toggleSubmenu(menuItem, subMenu, dropdownToggle);
                    }
                    const firstLink = subMenu.querySelector('a');
                    if (firstLink) firstLink.focus();
                }

                // Escape: Close submenu
                if (e.key === 'Escape') {
                    e.preventDefault();
                    if (menuItem.classList.contains('submenu-open')) {
                        closeSubmenu(menuItem, subMenu, dropdownToggle);
                        dropdownToggle.focus();
                    }
                }
            });
        }

        // =========================================
        // Parent Link - Keyboard Handler
        // =========================================
        if (link) {
            link.addEventListener('keydown', function (e) {
                // Arrow Down: Move to dropdown toggle or open submenu
                if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    if (dropdownToggle) {
                        dropdownToggle.focus();
                    } else if (subMenu) {
                        // If no toggle button, open submenu directly
                        openSubmenu(menuItem, subMenu);
                        const firstLink = subMenu.querySelector('a');
                        if (firstLink) firstLink.focus();
                    }
                }

                // Arrow Right: Open submenu (common pattern)
                if (e.key === 'ArrowRight' && subMenu) {
                    e.preventDefault();
                    openSubmenu(menuItem, subMenu, dropdownToggle);
                    const firstLink = subMenu.querySelector('a');
                    if (firstLink) firstLink.focus();
                }

                // Escape: Close any open parent submenus
                if (e.key === 'Escape') {
                    closeAllSubmenus();
                }
            });

            // Remove focus-based auto-expand - submenus stay closed on Tab
            // User must use Enter on toggle button or Arrow keys to expand
        }

        // =========================================
        // Submenu Links - Keyboard Handler
        // =========================================
        const subMenuLinks = subMenu.querySelectorAll('a');
        subMenuLinks.forEach(function (subLink, index) {
            subLink.addEventListener('keydown', function (e) {
                const subMenuItems = Array.from(subMenu.querySelectorAll(':scope > li > a'));
                const currentIndex = subMenuItems.indexOf(subLink);

                // Arrow Down: Next item in submenu
                if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    const nextIndex = currentIndex + 1;
                    if (nextIndex < subMenuItems.length) {
                        subMenuItems[nextIndex].focus();
                    }
                }

                // Arrow Up: Previous item or back to parent
                if (e.key === 'ArrowUp') {
                    e.preventDefault();
                    if (currentIndex > 0) {
                        subMenuItems[currentIndex - 1].focus();
                    } else {
                        // At first item, go back to toggle or parent link
                        if (dropdownToggle) {
                            dropdownToggle.focus();
                        } else if (link) {
                            link.focus();
                        }
                    }
                }

                // Arrow Left: Close submenu and return to parent
                if (e.key === 'ArrowLeft') {
                    e.preventDefault();
                    closeSubmenu(menuItem, subMenu, dropdownToggle);
                    if (dropdownToggle) {
                        dropdownToggle.focus();
                    } else if (link) {
                        link.focus();
                    }
                }

                // Escape: Close submenu and return to parent
                if (e.key === 'Escape') {
                    e.preventDefault();
                    closeSubmenu(menuItem, subMenu, dropdownToggle);
                    if (dropdownToggle) {
                        dropdownToggle.focus();
                    } else if (link) {
                        link.focus();
                    }
                }

                // Tab: If submenu is closed or at last item, let Tab proceed normally
                // This allows Tab to skip closed submenus
            });
        });
    });

    // =========================================
    // Helper Functions
    // =========================================

    /**
     * Toggle submenu open/closed
     */
    function toggleSubmenu(menuItem, subMenu, toggle) {
        if (menuItem.classList.contains('submenu-open')) {
            closeSubmenu(menuItem, subMenu, toggle);
        } else {
            // Close sibling submenus first
            closeSiblingSubmenus(menuItem);
            openSubmenu(menuItem, subMenu, toggle);
        }
    }

    /**
     * Open a submenu
     */
    function openSubmenu(menuItem, subMenu, toggle) {
        menuItem.classList.add('submenu-open');
        subMenu.setAttribute('aria-hidden', 'false');
        if (toggle) {
            toggle.setAttribute('aria-expanded', 'true');
        }
        // Make submenu items focusable
        setSubMenuTabIndex(subMenu, 0);
    }

    /**
     * Close a submenu
     */
    function closeSubmenu(menuItem, subMenu, toggle) {
        menuItem.classList.remove('submenu-open');
        subMenu.setAttribute('aria-hidden', 'true');
        if (toggle) {
            toggle.setAttribute('aria-expanded', 'false');
        }
        // Make submenu items not focusable
        setSubMenuTabIndex(subMenu, -1);
    }

    /**
     * Close sibling submenus (same level)
     */
    function closeSiblingSubmenus(currentItem) {
        const parent = currentItem.parentNode;
        if (!parent) return;

        const siblings = parent.querySelectorAll(':scope > .submenu-open');
        siblings.forEach(function (sibling) {
            if (sibling !== currentItem) {
                const subMenu = sibling.querySelector(':scope > ul');
                const toggle = sibling.querySelector(':scope > .blog-over-dropdown-toggle, :scope > button.dropdown-toggle');
                if (subMenu) {
                    closeSubmenu(sibling, subMenu, toggle);
                }
            }
        });
    }

    /**
     * Close all open submenus
     */
    function closeAllSubmenus() {
        const openItems = menu.querySelectorAll('.submenu-open');
        openItems.forEach(function (item) {
            const subMenu = item.querySelector(':scope > ul');
            const toggle = item.querySelector(':scope > .blog-over-dropdown-toggle, :scope > button.dropdown-toggle');
            if (subMenu) {
                closeSubmenu(item, subMenu, toggle);
            }
        });
    }

    /**
     * Set tabindex on all links within a submenu
     * -1 = not focusable via Tab
     * 0 = focusable via Tab
     */
    function setSubMenuTabIndex(subMenu, tabIndex) {
        const links = subMenu.querySelectorAll('a');
        links.forEach(function (link) {
            link.setAttribute('tabindex', tabIndex);
        });

        // Also handle nested toggle buttons
        const toggles = subMenu.querySelectorAll('.blog-over-dropdown-toggle, button.dropdown-toggle');
        toggles.forEach(function (toggle) {
            toggle.setAttribute('tabindex', tabIndex);
        });
    }

    // =========================================
    // Touch Support for Tablets
    // =========================================
    (function (container) {
        let touchStartFn, i,
            parentLink = container.querySelectorAll('.menu-item-has-children > a, .page_item_has_children > a');

        if ('ontouchstart' in window) {
            touchStartFn = function (e) {
                let menuItem = this.parentNode;
                const subMenu = menuItem.querySelector(':scope > ul');
                const toggle = menuItem.querySelector(':scope > .blog-over-dropdown-toggle');

                if (!menuItem.classList.contains('submenu-open')) {
                    e.preventDefault();
                    // Close siblings
                    closeSiblingSubmenus(menuItem);
                    // Open this one
                    if (subMenu) {
                        openSubmenu(menuItem, subMenu, toggle);
                    }
                }
                // If already open, let the click through to navigate
            };

            for (i = 0; i < parentLink.length; ++i) {
                parentLink[i].addEventListener('touchstart', touchStartFn, false);
            }
        }
    }(siteNavigation));

    // Close submenus when clicking outside
    document.addEventListener('click', function (e) {
        if (!menu.contains(e.target)) {
            closeAllSubmenus();
        }
    });

})();
