/**
 * Elementor frontend handler for the Mega Menu widget.
 *
 * Handles the mobile hamburger drawer, click / hover panel triggers and the
 * mobile inline-accordion behaviour, with full keyboard and pointer dismissal
 * ( Escape, click-outside ). Uses matchMedia against the configured breakpoint
 * so desktop and mobile behave correctly and re-sync on resize. Dependency-free
 * with an editor-safe teardown.
 *
 * @package captain-widgets-kit
 * @since   1.6.0
 */

(function ($) {
    'use strict';

    /**
     * Per-instance handler — called by Elementor for every widget instance.
     *
     * @param {jQuery} $scope - The widget wrapper element.
     */
    var CaptwikiMegaMenuHandler = function ($scope) {

        var root = $scope[0].querySelector('.captwiki-mega');
        if (!root) {
            return;
        }

        // Re-run safe: tear down a previous controller on editor re-render.
        if (root._cwkMegaTeardown) {
            root._cwkMegaTeardown();
        }

        var nav = root.querySelector('.captwiki-mega__nav');
        var toggle = root.querySelector('.captwiki-mega__toggle');
        var items = Array.prototype.slice.call(root.querySelectorAll('.captwiki-mega__item--mega'));

        var trigger = root.getAttribute('data-trigger') === 'click' ? 'click' : 'hover';
        var breakpoint = parseInt(root.getAttribute('data-breakpoint'), 10) || 1024;
        var mql = window.matchMedia('(max-width: ' + breakpoint + 'px)');

        var handlers = [];

        /**
         * Bind an event and remember it for teardown.
         *
         * @param {EventTarget} el   - Target element.
         * @param {string}      evt  - Event name.
         * @param {Function}    fn   - Callback.
         * @param {boolean}     capt - Capture flag.
         */
        var on = function (el, evt, fn, capt) {
            el.addEventListener(evt, fn, !!capt);
            handlers.push(function () {
                el.removeEventListener(evt, fn, !!capt);
            });
        };

        var isMobile = function () {
            return mql.matches;
        };

        /**
         * Close every open mega panel.
         *
         * @param {Element} [except] - An item to leave open.
         */
        var closeAll = function (except) {
            items.forEach(function (item) {
                if (item === except) {
                    return;
                }
                item.classList.remove('is-open');
                var link = item.querySelector('.captwiki-mega__link');
                if (link) {
                    link.setAttribute('aria-expanded', 'false');
                }
            });
        };

        /**
         * Toggle a single mega item open / closed.
         *
         * @param {Element} item - The mega list item.
         */
        var toggleItem = function (item) {
            var willOpen = !item.classList.contains('is-open');
            closeAll(item);
            item.classList.toggle('is-open', willOpen);
            var link = item.querySelector('.captwiki-mega__link');
            if (link) {
                link.setAttribute('aria-expanded', willOpen ? 'true' : 'false');
            }
        };

        /**
         * Open / close the mobile drawer.
         *
         * @param {boolean} open - Desired state.
         */
        var setDrawer = function (open) {
            root.classList.toggle('is-drawer-open', open);
            if (toggle) {
                toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
            }
            if (!open) {
                closeAll();
            }
        };

        /* ── Mobile hamburger ──────────────────────────────── */
        if (toggle) {
            on(toggle, 'click', function (e) {
                e.preventDefault();
                setDrawer(!root.classList.contains('is-drawer-open'));
            });
        }

        /* ── Per-item triggers ─────────────────────────────── */
        items.forEach(function (item) {
            var link = item.querySelector('.captwiki-mega__link');
            if (!link) {
                return;
            }

            // Click / tap: active on mobile always, and on desktop in click mode.
            on(link, 'click', function (e) {
                if (isMobile() || trigger === 'click') {
                    e.preventDefault();
                    toggleItem(item);
                }
            });

            // Hover mode on desktop is CSS-driven; keep aria in sync for a11y.
            on(item, 'mouseenter', function () {
                if (!isMobile() && trigger === 'hover') {
                    link.setAttribute('aria-expanded', 'true');
                }
            });
            on(item, 'mouseleave', function () {
                if (!isMobile() && trigger === 'hover') {
                    link.setAttribute('aria-expanded', 'false');
                }
            });
        });

        /* ── Dismissal: click-outside & Escape ─────────────── */
        var onDocClick = function (e) {
            if (!root.contains(e.target)) {
                closeAll();
                if (isMobile()) {
                    setDrawer(false);
                }
            }
        };
        on(document, 'click', onDocClick);

        var onKeyDown = function (e) {
            if (e.key === 'Escape') {
                closeAll();
                if (isMobile()) {
                    setDrawer(false);
                    if (toggle) {
                        toggle.focus();
                    }
                }
            }
        };
        on(document, 'keydown', onKeyDown);

        /* ── Breakpoint sync ───────────────────────────────── */
        var applyMode = function () {
            if (isMobile()) {
                root.classList.add('is-mobile');
            } else {
                root.classList.remove('is-mobile');
                setDrawer(false);
            }
            closeAll();
        };

        // addEventListener on MediaQueryList isn't available everywhere.
        if (typeof mql.addEventListener === 'function') {
            mql.addEventListener('change', applyMode);
            handlers.push(function () {
                mql.removeEventListener('change', applyMode);
            });
        } else if (typeof mql.addListener === 'function') {
            mql.addListener(applyMode);
            handlers.push(function () {
                mql.removeListener(applyMode);
            });
        }

        applyMode();

        /* ── Teardown ──────────────────────────────────────── */
        root._cwkMegaTeardown = function () {
            handlers.forEach(function (off) {
                off();
            });
            handlers = [];
            root.classList.remove('is-drawer-open', 'is-mobile');
            root._cwkMegaTeardown = null;
        };
    };

    /* ── Register with Elementor frontend ───────────────────── */
    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/captwiki-mega-menu.default',
            CaptwikiMegaMenuHandler
        );
    });

})(jQuery);
