/**
 * Advanced Mega Menu JavaScript
 * Handles all interactive functionality for the mega menu component
 */

(function($) {
    'use strict';

    /**
     * Advanced Mega Menu Class
     */
    class AdvancedMegaMenu {
        constructor(element) {
            this.$element = $(element);
            this.widgetId = this.$element.data('widget-id');
            this.$hamburger = this.$element.find('.adv-mega-menu__hamburger-toggle');
            this.$mobileMenu = this.$element.find('.adv-mega-menu__mobile-menu');
            this.$closeButton = this.$element.find('.adv-mega-menu__mobile-close');
            this.$overlay = this.$element.find('.adv-mega-menu__mobile-overlay');
            this.$menuItems = this.$element.find('.adv-mega-menu__item');
            this.hoverTimeout = null;
            this.isRTL = $('html').attr('dir') === 'rtl';
            
            this.init();
        }

        /**
         * Initialize the menu
         */
        init() {
            this.bindEvents();
            this.setupAccessibility();
            this.handleResize();
        }

        /**
         * Bind all event handlers
         */
        bindEvents() {
            // Mobile menu toggle
            this.$hamburger.on('click.megamenu', (e) => this.toggleMobileMenu(e));
            this.$closeButton.on('click.megamenu', () => this.closeMobileMenu());
            this.$overlay.on('click.megamenu', () => this.closeMobileMenu());

            // Desktop hover effects
            this.$menuItems.on('mouseenter.megamenu', (e) => this.showSubmenu(e));
            this.$menuItems.on('mouseleave.megamenu', (e) => this.hideSubmenu(e));

            // Mobile submenu toggles
            this.$element.find('.adv-mega-menu__mobile-nav .has-submenu > a')
                .on('click.megamenu', (e) => this.toggleMobileSubmenu(e));

            // Keyboard navigation
            $(document).on('keydown.megamenu', (e) => this.handleKeyboard(e));

            // Close dropdowns on outside click
            $(document).on('click.megamenu', (e) => this.handleOutsideClick(e));

            // Window resize handler
            $(window).on('resize.megamenu', () => this.handleResize());
        }

        /**
         * Toggle mobile menu
         */
        toggleMobileMenu(e) {
            e.preventDefault();
            e.stopPropagation();
            
            if (this.$mobileMenu.hasClass('active')) {
                this.closeMobileMenu();
            } else {
                this.openMobileMenu();
            }
        }

        /**
         * Open mobile menu
         */
        openMobileMenu() {
            this.$mobileMenu.addClass('active');
            $('body').css('overflow', 'hidden');
            
            // Focus management
            this.$closeButton.focus();
            
            // Trap focus within mobile menu
            this.trapFocus(this.$mobileMenu);
        }

        /**
         * Close mobile menu
         */
        closeMobileMenu() {
            this.$mobileMenu.removeClass('active');
            $('body').css('overflow', '');
            
            // Return focus to hamburger button
            this.$hamburger.focus();
            
            // Remove focus trap
            this.removeFocusTrap();
        }

        /**
         * Show submenu on hover
         */
        showSubmenu(e) {
            const $item = $(e.currentTarget);
            const $submenu = $item.children('.adv-mega-menu__submenu, .adv-mega-menu__megamenu');
            
            if ($submenu.length) {
                clearTimeout(this.hoverTimeout);
                
                // Position submenu if needed
                this.positionSubmenu($submenu);
                
                $submenu.stop(true, true).fadeIn(200);
            }
        }

        /**
         * Hide submenu on mouse leave
         */
        hideSubmenu(e) {
            const $item = $(e.currentTarget);
            const $submenu = $item.children('.adv-mega-menu__submenu, .adv-mega-menu__megamenu');
            
            if ($submenu.length) {
                this.hoverTimeout = setTimeout(() => {
                    $submenu.stop(true, true).fadeOut(200);
                }, 100);
            }
        }

        /**
         * Toggle mobile submenu
         */
        toggleMobileSubmenu(e) {
            const $link = $(e.currentTarget);
            const $submenu = $link.next('ul');
            
            if ($submenu.length) {
                e.preventDefault();
                
                const $parent = $link.parent();
                const isOpen = $parent.hasClass('open');
                
                if (isOpen) {
                    $submenu.slideUp(300);
                    $parent.removeClass('open');
                } else {
                    $submenu.slideDown(300);
                    $parent.addClass('open');
                }
            }
        }

        /**
         * Handle keyboard navigation
         */
        handleKeyboard(e) {
            switch (e.key) {
                case 'Escape':
                    if (this.$mobileMenu.hasClass('active')) {
                        this.closeMobileMenu();
                    } else {
                        // Close any open desktop submenus
                        this.$element.find('.adv-mega-menu__submenu, .adv-mega-menu__megamenu')
                            .fadeOut(200);
                    }
                    break;
                    
                case 'Tab':
                    // Handle tab navigation within mobile menu
                    if (this.$mobileMenu.hasClass('active')) {
                        this.handleTabNavigation(e);
                    }
                    break;
            }
        }

        /**
         * Handle outside clicks
         */
        handleOutsideClick(e) {
            if (!$(e.target).closest('.adv-mega-menu').length) {
                this.$element.find('.adv-mega-menu__submenu, .adv-mega-menu__megamenu')
                    .fadeOut(200);
            }
        }

        /**
         * Handle window resize
         */
        handleResize() {
            // Close mobile menu on resize to desktop
            if ($(window).width() > 992 && this.$mobileMenu.hasClass('active')) {
                this.closeMobileMenu();
            }
        }

        /**
         * Position submenu to prevent overflow
         */
        positionSubmenu($submenu) {
            if (!$submenu.hasClass('adv-mega-menu__megamenu')) {
                return; // Only position mega menus
            }
            
            const submenuWidth = $submenu.outerWidth();
            const windowWidth = $(window).width();
            const submenuOffset = $submenu.offset();
            
            // Check if submenu overflows viewport
            if (submenuOffset && (submenuOffset.left + submenuWidth > windowWidth)) {
                if (this.isRTL) {
                    $submenu.css('right', 'auto').css('left', '0');
                } else {
                    $submenu.css('left', 'auto').css('right', '0');
                }
            }
        }

        /**
         * Setup accessibility features
         */
        setupAccessibility() {
            // Add ARIA attributes
            this.$hamburger.attr({
                'aria-expanded': 'false',
                'aria-controls': `mobile-menu-${this.widgetId}`,
                'aria-label': 'Toggle navigation menu'
            });
            
            this.$mobileMenu.attr({
                'id': `mobile-menu-${this.widgetId}`,
                'aria-hidden': 'true'
            });
            
            // Update ARIA states on mobile menu toggle
            this.$mobileMenu.on('transitionend', () => {
                const isActive = this.$mobileMenu.hasClass('active');
                this.$hamburger.attr('aria-expanded', isActive.toString());
                this.$mobileMenu.attr('aria-hidden', (!isActive).toString());
            });
        }

        /**
         * Trap focus within an element
         */
        trapFocus($container) {
            const focusableElements = $container.find(
                'a[href], button, textarea, input[type="text"], input[type="radio"], input[type="checkbox"], select'
            ).filter(':visible');
            
            if (focusableElements.length === 0) return;
            
            const firstElement = focusableElements.first();
            const lastElement = focusableElements.last();
            
            $container.on('keydown.focustrap', (e) => {
                if (e.key === 'Tab') {
                    if (e.shiftKey) {
                        if (document.activeElement === firstElement[0]) {
                            e.preventDefault();
                            lastElement.focus();
                        }
                    } else {
                        if (document.activeElement === lastElement[0]) {
                            e.preventDefault();
                            firstElement.focus();
                        }
                    }
                }
            });
        }

        /**
         * Remove focus trap
         */
        removeFocusTrap() {
            this.$mobileMenu.off('keydown.focustrap');
        }

        /**
         * Handle tab navigation
         */
        handleTabNavigation(e) {
            const focusableElements = this.$mobileMenu.find(
                'a[href], button, textarea, input[type="text"], input[type="radio"], input[type="checkbox"], select'
            ).filter(':visible');
            
            const firstElement = focusableElements.first()[0];
            const lastElement = focusableElements.last()[0];
            
            if (e.shiftKey) {
                if (document.activeElement === firstElement) {
                    e.preventDefault();
                    lastElement.focus();
                }
            } else {
                if (document.activeElement === lastElement) {
                    e.preventDefault();
                    firstElement.focus();
                }
            }
        }

        /**
         * Destroy the menu instance
         */
        destroy() {
            // Remove all event listeners
            this.$element.off('.megamenu');
            $(document).off('.megamenu');
            $(window).off('.megamenu');
            
            // Clean up
            this.closeMobileMenu();
            this.removeFocusTrap();
        }
    }

    /**
     * jQuery Plugin
     */
    $.fn.advancedMegaMenu = function(options) {
        return this.each(function() {
            const $this = $(this);
            let instance = $this.data('advancedMegaMenu');
            
            if (!instance) {
                instance = new AdvancedMegaMenu(this);
                $this.data('advancedMegaMenu', instance);
            }
            
            if (typeof options === 'string' && instance[options]) {
                instance[options]();
            }
        });
    };

    /**
     * Auto-initialize on DOM ready
     */
    $(document).ready(function() {
        // Initialize all mega menus
        $('.adv-mega-menu[data-widget-id]').advancedMegaMenu();
        
        // Re-initialize on Elementor frontend reload
        if (typeof elementorFrontend !== 'undefined') {
            elementorFrontend.hooks.addAction('frontend/element_ready/megamenukaveh.default', function($scope) {
                $scope.find('.adv-mega-menu[data-widget-id]').advancedMegaMenu();
            });
        }
    });

})(jQuery);