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

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

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

    // Add a click event listener to the document object
    document.addEventListener('click', function(event) {
        // Check if the clicked element is inside the menu
        const isClickInsideMenu = menuOverlay.contains(event.target);

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

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

    // 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();
    }
});
