import { onPageLoadComplete } from '@nimius/event-utility';

const initializeMenuOverlayClickObserver = () => {
    // Get all the menu overlay and menu trigger elements
    const menuOverlay = document.querySelector('.c-menu-overlay');
    const menuBlurredOverlay = document.querySelector('.c-menu-overlay--blurred');
    const menuTrigger = document.querySelector('.c-site-header-trigger--menu');

    // Add a click event listener to the menu trigger element
    menuTrigger.addEventListener('click', (event) => {
        // Stop the event propagation to prevent the click on the menu trigger from registering as a click on
        // the document object after the trigger is clicked and the menu overlay was opened
        event.stopPropagation();
    });

    // Define the event listener function
    const clickEventListener = (event) => {
        // Check if the clicked element is inside the current menu overlay
        const isClickInsideMenu = menuOverlay.contains(event.target);

        if (menuBlurredOverlay) {
            const isClickInsideBlurredMenu = menuBlurredOverlay.contains(event.target);

            if (!isClickInsideMenu && !isClickInsideBlurredMenu) {
                menuOverlay.classList.remove('is-target');
                menuBlurredOverlay.classList.remove('is-target');
                menuTrigger.removeAttribute('aria-expanded');
            }
        } else if (!isClickInsideMenu) {
            // If the clicked element is not inside the current menu overlay, close the menu
            menuOverlay.classList.remove('is-target');
            menuTrigger.removeAttribute('aria-expanded');
        } else {
            return;
        }
    };

    // Check if the menu overlay is target and add or remove the click event listener.
    // Otherwise the event listener causes huge problems with the other menu elements, if it's always active.
    // Especially with the filled header when an overlay is opened.
    // This has interfered with the mutation observer in site-header.js
    const observer = new MutationObserver(mutations => {
        for (const mutation of mutations) {
            if (mutation.target.className.includes('is-target')) {
                document.addEventListener('click', clickEventListener);
            } else {
                document.removeEventListener('click', clickEventListener);
            }
        }
    });

    observer.observe(menuOverlay, { attributes: true, attributeFilter: [ 'class' ], childList: false, subtree: false });
};

onPageLoadComplete(() => {
    const mainNavigation = document.querySelector('.c-main-navigation');

    /* eslint-disable */
    // Only observe the menu overlay, when it contains the --pinned-left or --pinned-right classes
    if (mainNavigation.classList.contains('c-main-navigation--pinned-left') || mainNavigation.classList.contains('c-main-navigation--pinned-right')) {
        initializeMenuOverlayClickObserver();
    }
    /* eslint-enable */
});
