export default function menu() {
    const openMenu = '.js-hamburger';
    const closeMenu = '.js-close-hamburger';
    const menuInside = '.js-side-menu *';
    const menuInsideLink = '.js-menu-close a';
    const opensSideMenu = '.js-opens-side-menu';
    const sideMenuContainer = document.querySelector('.js-side-menu');
    const menuTabbable = sideMenuContainer.querySelectorAll('a[href]:not(.js-side-level a[href]), button:not([disabled]):not(.js-side-level button)');
    const sideMenuLink = '.js-menu-item';
    const sideMenuBackButton = '.js-back-button';

    menuTabbable.forEach(function (item) {
        item.setAttribute('tabindex', '-1');
    });

    window.addEventListener('click', function (event) {
        const activeSideMenu = document.querySelectorAll('.sidemenu_is_open');
        if (
            // Check if menu is opened or submenu is opened or closed
            event.target.matches(openMenu) ||
            event.target.matches(sideMenuBackButton) ||
            (event.target.matches(menuInside) && !event.target.matches(closeMenu) && !event.target.matches(menuInsideLink))
        ) {
            hamburgerMenuHandler(event);
        } else {
            document.body.classList.remove('menu_is_open');

            menuTabbable.forEach(function (item) {
                item.setAttribute('tabindex', '-1');
            });

            activeSideMenu.forEach(function (item) {
                item.classList.remove('sidemenu_is_open');

                const navLevelsSideLinks = item.querySelectorAll('a[href], button:not([disabled])');

                navLevelsSideLinks[0].focus();
                navLevelsSideLinks.forEach(function (item) {
                    item.setAttribute('tabindex', '-1');
                });
            });

            if (event.detail === 0) {
                document.querySelector('.js-hamburger').focus();
            }
        }

        if (event.target.matches(opensSideMenu)) {
            const menuItemId = event.target.dataset.menuItem;
            const menuLink = '#menu-item-' + menuItemId;
            const menuItemParent = document.querySelector(menuLink).parentElement;

            hamburgerMenuHandler(event, menuItemParent);
        } else {
            sideMenuContainer.classList.remove('has_side_panel');
        }

        if (event.target.matches(sideMenuLink)) {
            const menuItemParent = event.target.parentElement;

            hamburgerMenuHandler(event, menuItemParent);
        }
    });

    const hamburgerMenuHandler = function (event, menuItem) {
        document.body.classList.add('menu_is_open');

        menuTabbable.forEach(function (item) {
            item.setAttribute('tabindex', '0');
        });

        if (event.detail === 0) {
            sideMenuContainer.querySelector('.js-close-hamburger').focus();
        }

        resetMenuItemsStates(event);

        if (menuItem) {
            changeMenuItemsStates(menuItem);
        }
    };

    const changeMenuItemsStates = function (menuItem) {
        const subMenu = menuItem.querySelector('ul');
        const navLevelsSide = menuItem.querySelector('.js-side-level');
        const navItem = menuItem.querySelector('.js-menu-item');

        if (subMenu.classList.contains('js-side-level')) {
            sideMenuContainer.classList.add('has_side_panel');
            navLevelsSide.classList.add('sidemenu_is_open');
            navItem.classList.add('current_menu_item');

            const navLevelsSideLinks = navLevelsSide.querySelectorAll('a[href], button:not([disabled])');
            const navLevelsSideFirst = navLevelsSide.querySelector('.js-menu-close a');

            navLevelsSideFirst.focus();
            navLevelsSideLinks.forEach(function (item) {
                item.setAttribute('tabindex', '0');
            });
        }
    };

    const resetMenuItemsStates = function (event) {
        const activeMenuItems = document.querySelectorAll('.current_menu_item');
        const activeSideMenu = document.querySelectorAll('.sidemenu_is_open');

        activeMenuItems.forEach(function (item) {
            item.classList.remove('current_menu_item');
        });

        if (event.target.matches(sideMenuLink)) {
            activeSideMenu.forEach(function (item) {
                sideMenuContainer.classList.add('sidemenu_is_closing');
                item.classList.remove('sidemenu_is_open');
            });
            setTimeout(function () {
                activeSideMenu.forEach(function (item) {
                    sideMenuContainer.classList.remove('sidemenu_is_closing');
                });
            }, 400);
        } else {
            activeSideMenu.forEach(function (item) {
                item.classList.remove('sidemenu_is_open');
            });
        }

        activeSideMenu.forEach(function (item) {
            const navLevelsSideLinks = item.querySelectorAll('a[href], button:not([disabled])');
            navLevelsSideLinks.forEach(function (item) {
                item.setAttribute('tabindex', '-1');
            });
        });
    };

    sideMenuContainer.addEventListener('keydown', (e) => {
        const lastSideMenu = document.querySelector('.js-side-level-last');
        let focusableElements = null;

        if (lastSideMenu?.classList.contains('sidemenu_is_open')) {
            focusableElements = sideMenuContainer.querySelectorAll('a[href], button:not([disabled]');
        } else {
            focusableElements = sideMenuContainer.querySelectorAll('a[href]:not(.js-side-level-last a[href]), button:not(.js-back-button-last)');
        }
        const firstFocusableElement = focusableElements[0];
        const lastFocusableElement = focusableElements[focusableElements.length - 1];
        const isTabPressed = e.key === 'Tab';

        if (!isTabPressed) {
            return;
        }

        if (e.shiftKey) {
            if (document.activeElement === firstFocusableElement) {
                lastFocusableElement.focus();
                e.preventDefault();
            }
        } else {
            if (document.activeElement === lastFocusableElement) {
                firstFocusableElement.focus();
                e.preventDefault();
            }
        }
    });
}
