
export class MtcMobileMenu {
    constructor(options = {}) {
        this.defaults = {
            flyout_wrapper: '.flyoutWrap',
            clone: true,
            submenu_selector: '.childMenu',
            is_fixed: true,
            position: 'right',
            move_site: true
        };
        this.settings = { ...this.defaults, ...options };
        this.flyoutWrapper = document.querySelector(this.settings.flyout_wrapper);

        if (!this.flyoutWrapper) {
            console.error(`No elements found for ${this.settings.flyout_wrapper}`);
            return;
        }

        this.initClasses();
        this.initEvents();
        this.onResize();
        window.addEventListener('resize', this.onResize.bind(this));
        window.addEventListener('orientationchange', this.onResize.bind(this));
    }

    initClasses() {
        document.body.classList.add('flyoutInitialised');
        if (this.settings.move_site) document.body.classList.add('flyoutMove');

        switch (this.settings.position) {
            case 'left':
                document.body.classList.add('flyoutLeft');
                break;
            case 'top':
                document.body.classList.add('flyoutTop');
                break;
            default:
                document.body.classList.add('flyoutRight');
        }

        if (this.settings.is_fixed) {
            document.body.classList.add('fixedFlyout');
        }

        this.init();
    }

    init() {
        const submenus = this.flyoutWrapper.querySelectorAll('.childMenu');
        submenus.forEach(li => {
            const submenu = li.querySelector(this.settings.submenu_selector);
            const link = li.querySelector('a');
            if (submenu && link) {
                link.classList.add('js_mobileSubmenu');
                if (this.settings.clone) {
                    const clone = link.cloneNode(true);
                    clone.classList.add('clone');
                    const wrapperLi = document.createElement('li');
                    wrapperLi.appendChild(clone);
                    submenu.insertBefore(wrapperLi, submenu.firstChild);
                }
            }
        });
    }

    destroy() {
        document.querySelectorAll('.js_mobileSubmenu').forEach(el => el.classList.remove('js_mobileSubmenu'));
        this.flyoutWrapper.querySelectorAll(this.settings.submenu_selector).forEach(ul => {
            ul.style.display = '';
        });
        this.flyoutWrapper.querySelectorAll('.clone').forEach(clone => clone.parentNode.remove());
        document.body.classList.remove('flyoutInitialised', 'flyoutActive');
    }

    kill() {
        this.destroy();
        document.body.classList.remove('fixedFlyout', 'flyoutLeft', 'flyoutRight', 'flyoutTop', 'flyoutMove');
        const flyoutButton = document.querySelectorAll('.js_flyoutToggleButton');
        if (flyoutButton) {
            flyoutButton.forEach(button => {
                button.removeEventListener('click', this.toggleFlyout);
            })
        }
        window.removeEventListener('resize', this.onResize);
        window.removeEventListener('orientationchange', this.onResize);
    }

    toggleFlyout = (e) => {
        e.preventDefault();
        document.body.classList.toggle('flyoutActive');

        if (this.settings.is_fixed) {
            if (document.body.classList.contains('flyoutActive')) {
                this.scrollOnOpen = window.scrollY;
                document.body.dataset.storedScroll = this.scrollOnOpen;
            } else {
                window.scrollTo(0, document.body.dataset.storedScroll || 0);
            }
        }
    }

    onResize = () => {
        const shouldBeActive = window.matchMedia(`(max-width: ${window.breakpoints?.flyout || 768}px)`).matches;
        if (shouldBeActive && !document.body.classList.contains('flyoutInitialised')) {
            this.init();
        } else if (!shouldBeActive && document.body.classList.contains('flyoutInitialised')) {
            this.destroy();
        }
    }

    bindSubmenuEvents() {
        document.body.addEventListener('click', (e) => {
            if (e.target.classList.contains('js_mobileSubmenu')) {
                e.preventDefault();
                const parent = e.target.closest('li');
                const submenu = parent.querySelector(this.settings.submenu_selector);

                // Close siblings
                parent.parentElement.querySelectorAll('.open').forEach(openItem => {
                    if (openItem !== parent) {
                        openItem.classList.remove('open');
                        const openSubmenu = openItem.querySelector(this.settings.submenu_selector);
                        if (openSubmenu) openSubmenu.style.display = 'none';
                    }
                });

                parent.classList.toggle('open');
                submenu.style.display = submenu.style.display === 'block' ? 'none' : 'block';
            }
        });
    }

    bindFlyoutEvents(){
        const flyoutButton = document.querySelectorAll('.js_flyoutToggleButton');
        if (flyoutButton) {
            flyoutButton.forEach(button => {
                button.addEventListener('click', this.toggleFlyout);
            })
        }
    }

    initEvents() {
        this.bindSubmenuEvents();
        this.bindFlyoutEvents();
    }
}
