/**
 * navigation.js
 *
 * Handles toggling the navigation menu for small screens and enables tab
 * support for dropdown menus.
 */
(function () {
    var container, button, menu, links, subMenus;

    container = document.getElementById('masthead');
    if (!container) {
        return;
    }

    button = container.getElementsByTagName('button')[0];
    if ('undefined' === typeof button) {
        return;
    }

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

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

    menu.setAttribute('aria-expanded', 'false');
    if (-1 === menu.className.indexOf('nav-menu')) {
        menu.className += ' nav-menu';
    }

    button.onclick = function () {
        button.onclick = function () {
            if (-1 !== menu.className.indexOf('toggled'))
                menu.className = menu.className.replace(' toggled', '');
            else
                menu.className += ' toggled';
        };

        // Get all the link elements within the menu.
        links = menu.getElementsByTagName('a');
        subMenus = menu.getElementsByTagName('ul');

        // Set menu items with submenus to aria-haspopup="true".
        for (var i = 0, len = subMenus.length; i < len; i++) {
            subMenus[i].parentNode.setAttribute('aria-haspopup', 'true');
        }

        // Each time a menu link is focused or blurred, toggle focus.
        for (i = 0, len = links.length; i < len; i++) {
            links[i].addEventListener('focus', toggleFocus, true);
            links[i].addEventListener('blur', toggleFocus, true);
        }

        /**
         * Sets or removes .focus class on an element.
         */
        function toggleFocus() {
            var self = this;

            // Move up through the ancestors of the current link until we hit .nav-menu.
            while (-1 === self.className.indexOf('nav-menu')) {

                // On li elements toggle the class .focus.
                if ('li' === self.tagName.toLowerCase()) {
                    if (-1 !== self.className.indexOf('focus')) {
                        self.className = self.className.replace(' focus', '');
                    } else {
                        self.className += ' focus';
                    }
                }

                self = self.parentElement;
            }
        }
    }
})();

document.addEventListener('DOMContentLoaded', function () {
    const menuButton = document.querySelector('.menu-toggle');
    const menuList = document.querySelector('.main-navigation ul');

    menuButton.setAttribute('aria-expanded', 'false');

    menuButton.addEventListener('click', function () {
        const isOpen = menuList.classList.contains('open');

        if (isOpen) {
            menuList.classList.remove('open');
            menuButton.classList.remove('open');
            menuButton.setAttribute('aria-expanded', 'false');
        } else {
            menuList.classList.add('open');
            menuButton.classList.add('open');
            menuButton.setAttribute('aria-expanded', 'true');
        }
    });
});

// Get all parent menu items
const parentItems = document.querySelectorAll('.menu-item-has-children');
parentItems.forEach((item) => {
    const link = item.querySelector('a');
    const subMenu = item.querySelector('.sub-menu');

    link.addEventListener('click', function (e) {
        if (window.innerWidth <= 1199) {
            e.preventDefault();
            const isOpen = item.classList.contains('open');

            if (isOpen) {
                item.classList.remove('open');
                subMenu.style.display = 'none';
            } else {
                item.classList.add('open');
                subMenu.style.display = 'block';
            }
        }
    });
});

document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.menu-item-has-children > a, .page_item_has_children > a')
        .forEach(link => {
            link.addEventListener('click', function (e) {
                e.preventDefault();
                this.parentElement.classList.toggle('active');
            });
        });
});

/**
 * Primary Navigation
 */
document.addEventListener("DOMContentLoaded", function () {
    const menuToggle = document.querySelector(".menu-toggle");
    const nav = document.querySelector("#site-navigation");

    if (!menuToggle || !nav) return;

    menuToggle.addEventListener("click", function () {
        const isOpen = nav.classList.contains("toggled");

        // Toggle menu
        nav.classList.toggle("toggled");
        menuToggle.setAttribute("aria-expanded", String(!isOpen));

        if (!isOpen) {
            trapFocus(nav, menuToggle);
        }
    });

    function trapFocus(container, closeButton) {
        const focusableSelectors =
            'a[href], button:not([disabled]), [tabindex="0"]';

        const focusableEls = container.querySelectorAll(focusableSelectors);
        const firstEl = focusableEls[0];
        const lastEl = focusableEls[focusableEls.length - 1];

        // Move focus to first menu item
        firstEl.focus();

        container.addEventListener("keydown", function (e) {
            if (e.key === "Tab") {
                // SHIFT + TAB
                if (e.shiftKey) {
                    if (document.activeElement === firstEl) {
                        e.preventDefault();
                        closeButton.focus(); // Loop to close button
                    }
                } else {
                    // TAB forward
                    if (document.activeElement === lastEl) {
                        e.preventDefault();
                        closeButton.focus(); // Loop to close button
                    }
                }
            }

            // ESC key closes menu and returns focus
            if (e.key === "Escape") {
                container.classList.remove("toggled");
                closeButton.setAttribute("aria-expanded", "false");
                closeButton.focus();
            }
        });
    }
});