jQuery(document).ready(function($) {
    'use strict';

    // ===============================
    // ELEMENTOR EDITOR SUPPORT
    // ===============================
    if (window.elementorFrontend && elementorFrontend.isEditMode()) {
        elementorFrontend.hooks.addAction('frontend/element_ready/sitsel_mega_menu_widget.default', function($scope) {
            initMegaMenu($scope);
        });
    }
    
    initMegaMenu();
    
    // ===============================
    // MAIN INITIALIZATION FUNCTION
    // ===============================
    function initMegaMenu($scope) {
        var $widgets = $scope ? $scope.find('.sitsel-mega-menu-widget') : $('.sitsel-mega-menu-widget');

        // ===============================
        // WIDGET-SPECIFIC INITIALIZATION
        // ===============================
        $widgets.each(function() {
			var $widget = $(this);

			// Skip if already initialized
			if ($widget.data('sitsel-menu-initialized')) {
				return;
			}
			$widget.data('sitsel-menu-initialized', true);

			// Generate unique widget ID
			var widgetId = $widget.attr('id') || 'megamenu-' + Math.random().toString(36).substr(2, 9);
			$widget.attr('id', widgetId);
            
            var resizeTimer;
            var overlayHideTimer = null;
            
            // Cache DOM elements
            // var $storage = $widget.find('.sitsel-mega-menu-template-storage');
            // Cache DOM elements - SCOPED TO THIS WIDGET
			var $toggle = $widget.find('.sitsel-mega-menu-toggle');
		
            $toggle.css({ display: 'none', visibility: 'hidden', opacity: 0 });
			var $mainWrapper = $widget.find('.sitsel-mega-menu-main-wrapper');
			var $offcanvasClose = $widget.find('.sitsel-offcanvas-close');
            
            // Get settings
            var breakpoint = parseInt($widget.data('mobile-breakpoint')) || 0;
            var hasBreakpoint = breakpoint > 0;
            var showMobile = $widget.data('show-mobile') === 'yes';
            var mobileDisplay = $widget.data('mobile-display') || 'dropdown';
            var mobileStretch = $widget.data('mobile-stretch') || 'default';
            var mobileBackMenu = $widget.data('mobile-back-menu') || 'default';
            var isBackMode = mobileBackMenu === 'back';
            var isDefaultMode = mobileBackMenu === 'default';
            var submenuTrigger = $widget.data('submenu-trigger') || 'hover';
            var menuLayout = $widget.data('layout') || 'horizontal';
            
             var dropdownPosition = $widget.data('dropdown_position_from') || 'menu';
			// console.log("text " + dropdownPosition);
			var showOffcanvasClose = $widget.data('show-offcanvas-close') === 'yes';
            var offcanvasClosePosition = $widget.data('offcanvas-close-position') || 'top-right';
            var offcanvasDirection = $widget.data('offcanvas-direction') || 'left';
            
            // Scoped resize handler
            $(window).on('resize.megamenu.' + widgetId, function() {
                clearTimeout(resizeTimer);
                
                resizeTimer = setTimeout(function() {
                    // Close all menus on resize
                    $widget.find('.sitsel-sub-menu').hide().css({
                        opacity: '', visibility: '', position: '', top: '', left: '',
                        width: '', height: '', 'max-height': '', 'overflow-y': '',
                        'z-index': '', transform: '', transition: '', display: ''
                    });
                    $widget.find('.sitsel-mobile-template').remove();
                    
                    // Remove all open states
                    $widget.find('.sitsel-sub-open, .sitsel-mobile-template-open').removeClass('sitsel-sub-open sitsel-mobile-template-open');
                    
                    // Reset off-canvas
                    $widget.removeClass('sitsel-mm-offcanvas-open');
                    $widget.find('[aria-expanded]').attr('aria-expanded', 'false');
                    
                    if (!isSmall()) {
                        resetOffcanvasStyles();
                    }
                }, 150);
            });
            // Add this after the resize handler (after the $(window).on('resize.megamenu...) block)
            $(window).on('scroll.megamenu.' + widgetId, function() {
    // Close desktop mega menus on scroll
    if ($widget.find('.sitsel-mega-open').length) {
        $widget.find('.sitsel-mega-open').each(function() {
            closeMegaMenu($(this), true);
        });
    }
    // Update mobile dropdown top on scroll so it follows the widget
    if (isSmall() && mobileDisplay === 'dropdown' && $widget.hasClass('sitsel-mm-open')) {
        var widgetRect = $widget[0].getBoundingClientRect();
        $mainWrapper.css('top', widgetRect.bottom + 'px');
    }
});
            
          

function resetOffcanvasStyles() {
    $mainWrapper.css({
        transform: '',
        width: '',
        left: '',
        position: '',
        top: '',
        'max-height': '',
        'overflow-y': ''
    });
    $widget.css('position', '');
}

            function getViewportWidth() {
                if (window.elementorFrontend && elementorFrontend.isEditMode()) {
                    var $previewWrapper = $('#elementor-preview-iframe').contents().find('body');
                    if ($previewWrapper.length) {
                        return $previewWrapper.width();
                    }
                }
                return $(window).width();
            }

//             function getHeaderHeight() {
//     			return $widget.outerHeight() || 72;
//     		}
            
//             function updateHeaderHeightVar() {
// 				var h = getHeaderHeight();
// 				$widget[0].style.setProperty('--header-height', h + 'px');
// 			}
            
//             updateHeaderHeightVar();
//             $(window).on('resize.megamenu.' + widgetId, updateHeaderHeightVar);

            function getHeaderMenuHeight() {
    			return $widget.outerHeight() || 72;
    		}
            
            function updateHeaderMenuHeightVar() {
				var hm = getHeaderMenuHeight();
				$widget[0].style.setProperty('--headermenu-height', hm + 'px');
			}
             updateHeaderMenuHeightVar();
            
            function getHeaderHeight() {
                var $header = $('.elementor-location-header');
            
                // If Elementor header exists, use it
                if ($header.length) {
                    return $header.outerHeight();
                }
            
                // Fallback to native <header>
                var $nativeHeader = $('header');
                if ($nativeHeader.length) {
                    return $nativeHeader.outerHeight();
                }
            
                return 72; // fallback
            }
        
            function updateHeaderHeightVar() {
                var h = getHeaderHeight();
                document.documentElement.style.setProperty('--header-height', h + 'px');
            }
            
            $(window).on('resize.megamenu.' + widgetId, updateHeaderMenuHeightVar);
            $(window).on('load resize scroll', function () {
                updateHeaderHeightVar();
            });

            function isSmall() {
                return hasBreakpoint && getViewportWidth() <= breakpoint;
            }

            function updateMobileClass() {
                var isMobile = isSmall();
                $widget.toggleClass('sitsel-mobile-version', isMobile);
                $widget.toggleClass('sitsel-mobile-back-mode', isMobile && isBackMode);
                $widget.toggleClass('sitsel-mobile-default-mode', isMobile && isDefaultMode);
            }

            updateMobileClass();
            $(window).on('resize.megamenu.' + widgetId, updateMobileClass);
            
            if (window.elementorFrontend && elementorFrontend.isEditMode()) {
                elementor.on('preview:loaded', updateMobileClass);
                $('#elementor-preview-iframe').on('load', function() {
                    $(this.contentWindow).on('resize', updateMobileClass);
                });
            }

            function hideOverlay() {
                clearTimeout(overlayHideTimer);
            }

            function hasMegaMenu($li) {
                return $li.find('> .sitsel-sub-menu.sitsel-mega-sub-menu').length > 0;
            }
            
            function getMegaMenuTemplateId($li) {
                var $submenu = $li.find('> .sitsel-sub-menu.sitsel-mega-sub-menu');
                if ($submenu.length) {
                    return $submenu.data('template-id') || $submenu.find('[data-template-id]').first().data('template-id');
                }
                return null;
            }

            // ===============================
            // MEGA MENU DISPLAY FUNCTIONS
            // ===============================
            

function showMegaMenuForLi($li) {
    var $megaSubmenu = $li.find('> .sitsel-sub-menu.sitsel-mega-sub-menu');
    if (!$megaSubmenu.length) return;

    clearTimeout($li.data('hideTimer'));

    $widget.find('.sitsel-has-children.sitsel-sub-open').not($li).each(function() {
        closeMegaMenu($(this), true);
    });
    $widget.find('.sitsel-sub-menu').not('.sitsel-mega-sub-menu').hide();

    $li.addClass('sitsel-sub-open sitsel-mega-open');
    $li.find('> a').attr('aria-expanded', 'true');

    // ── NEW: same header positioning as mobile dropdown ──
    var $clswidget = $widget.closest('.elementor-widget');
    $clswidget.css('position', 'static');
    var $parentHeader = $clswidget.closest('header');
    $parentHeader.css('position', 'relative');
    $parentHeader.find('header').not($parentHeader).css('position', 'static');
    // ─────────────────────────────────────────────────────

    var isNested = $li.parents('.sitsel-sub-menu').length > 0;
    var cssBase = { display: 'block', visibility: 'visible', opacity: 0, 'z-index': 97 };

    if (isNested) {
        var nestedTop = $widget[0].getBoundingClientRect().bottom;
        $megaSubmenu.css($.extend(cssBase, { position: 'fixed', top: nestedTop + 'px', left: '0', width: '100vw' }));
    } else if (menuLayout === 'vertical') {
        $megaSubmenu.css($.extend(cssBase, { position: 'relative' }));
    // } else {
    //     var widgetBottom = $widget[0].getBoundingClientRect().bottom;
    //     $megaSubmenu.css($.extend(cssBase, { position: 'fixed', top: widgetBottom + 'px', left: '0', width: '100vw' }));
    // }
    } else {
            var liRect = $li[0].getBoundingClientRect();
                 if (dropdownPosition === 'menu') {
                    // Position from menu item bottom
                    // console.log("menu");
                    $megaSubmenu.css($.extend(cssBase, { 
                        position: 'fixed',
                        top: liRect.bottom + 'px',
                        left: '0',
                        width: '100vw'
                    }));
                } else {
                    // Position from header bottom
                    // console.log("header");
                    $megaSubmenu.css($.extend(cssBase, { 
                        position: 'fixed',
                        top: getHeaderHeight() + 'px',
                        left: '0',
                        width: '100vw'
                    }));
                }
        
            }

    $megaSubmenu.css({ transition: 'none' });
    requestAnimationFrame(function() {
        requestAnimationFrame(function() {
            $megaSubmenu.css({ opacity: 1, transition: 'opacity 0.4s ease-in-out' });
        });
    });
}

           

// REPLACE closeMegaMenu with this (fixes glitch on fast hover-out):
function closeMegaMenu($li, immediate) {
    $li.removeClass('sitsel-sub-open sitsel-mega-open');
    $li.find('> a').attr('aria-expanded', 'false');

    var $megaSubmenu = $li.children('.sitsel-sub-menu.sitsel-mega-sub-menu');
    if (!$megaSubmenu.length) return;

    $megaSubmenu.find('.sitsel-has-children.sitsel-sub-open').removeClass('sitsel-sub-open sitsel-mega-open');

    var resetCss = { opacity: '', visibility: '', position: '', top: '', left: '', width: '', 'z-index': '', transition: '', display: '' };

    var doReset = function() {
        // ── NEW: restore header positioning only if no other mega menus are open ──
        if (!$widget.find('.sitsel-mega-open').length) {
            var $clswidget = $widget.closest('.elementor-widget');
            $clswidget.css('position', '');
            $clswidget.closest('header').css('position', '');
        }
        // ──────────────────────────────────────────────────────────────────────────
    };

    if (immediate) {
        $megaSubmenu.hide().css(resetCss);
        doReset();
    } else {
        $megaSubmenu.css({ opacity: 0, transition: 'opacity 0.15s ease' });
        setTimeout(function() {
            if (!$li.hasClass('sitsel-mega-open')) {
                $megaSubmenu.hide().css(resetCss);
                doReset();
            }
        }, 220);
    }
}
            // ===============================
            // SUBMENU FUNCTIONS
            // ===============================
            function openSubmenu($li) {
                var isMobile = isSmall();
                var isMegaMenu = hasMegaMenu($li);
                
                if (isMobile && isMegaMenu) {
                    var templateId = getMegaMenuTemplateId($li);
                    openMobileTemplateForLi(templateId, $li);
                    return;
                }
                
                // Close sibling submenus
                $li.siblings('.sitsel-sub-open').each(function() {
                    closeSubmenu($(this), true);
                });

                hideOverlay();

                $li.addClass('sitsel-sub-open');
                $li.find('> a').attr('aria-expanded', 'true');

                var $submenu = $li.children('.sitsel-sub-menu');
                if (!$submenu.length) return;

                if (!isMobile) {
                    var isNestedSubmenu = $li.parents('.sitsel-sub-menu').length > 0;
                    
                    if (isNestedSubmenu) {
                        // Reset positioning
                        $submenu.css({
                            left: '',
                            right: '',
                            transform: ''
                        });
                    
                        // Temporarily show submenu to measure width
                        var cssConfig = menuLayout === "vertical" ? {
                            position: 'relative',
                            visibility: 'hidden',
                            display: 'block'
                        } : {
                            position: 'absolute',
                            top: '0',
                            visibility: 'hidden',
                            display: 'block'
                        };
                        
                        $submenu.css(cssConfig);
                    
                        var submenuWidth = $submenu.outerWidth();
                        var parentRect = $li[0].getBoundingClientRect();
                        var viewportWidth = window.innerWidth;
                    
                        // Check if submenu overflows right side
                        var willOverflowRight = parentRect.right + submenuWidth > viewportWidth;
                    
                        if (menuLayout === "vertical") {
                            $submenu.css({ transform: 'translateX(0)' });
                        } else {
                            if (willOverflowRight) {
                                // Open to LEFT
                                $submenu.css({
                                    right: '0',
                                    left: 'auto',
                                    transform: 'translateX(-100%)'
                                });
                            } else {
                                // Open to RIGHT
                                $submenu.css({
                                    left: '0',
                                    right: 'auto',
                                    transform: 'translateX(100%)'
                                });
                            }
                        }
                    
                       
                        $submenu.stop(true, true).css({
                            visibility: 'visible',
                            opacity: 0,
                            'z-index': 97
                        }).animate({ opacity: 1 }, 200);
                    
                    } else {
                        // Top-level submenu
                        if (menuLayout === "vertical") {
                            $submenu.css({
                                position: 'relative',
                                visibility: 'visible',
                                display: 'block'
                            }).animate({ opacity: 1 }, 200);
                        // } else {
                        //     $submenu.stop(true, true).css({
                        //     position: 'absolute',
                        //     top: getHeaderHeight() + 'px',
                        //     left: 'auto',
                        //     display: 'block',
                        //     visibility: 'visible',
                        //     opacity: 0
                        // }).animate({ opacity: 1 }, 200);
                        // }
                        
                        } else {
                                var liRect = $li[0].getBoundingClientRect();
                            
                                if (dropdownPosition === 'menu') {
                                    // Position from the menu item bottom
                                    $submenu.stop(true, true).css({
                                        position: 'absolute',
                                        top: $li.outerHeight() + 'px', // relative to li
                                        left: 0,
                                        display: 'block',
                                        visibility: 'visible',
                                        opacity: 0,
                                        'z-index': 97
                                    }).animate({ opacity: 1 }, 200);
                                } else {
                                    // Position from header bottom
                                    
                                    $submenu.stop(true, true).css({
                                        position: 'fixed',
                                        top: getHeaderHeight() + 'px',
                                        left: 'auto',
                                        display: 'block',
                                        visibility: 'visible',
                                        opacity: 0,
                                        'z-index': 97
                                    }).animate({ opacity: 1 }, 200);
                                }
                            }
                        
                        
                    }
                    
                    return;
                }

                // Mobile submenu handling
                if (isDefaultMode) {
                    $submenu.css({
                        position: 'relative',
                        top: 0,
                        width: '100%',
                        height: '100%',
                        'max-height': '100%',
                        'overflow-y': 'auto',
                        display: 'block',
                        visibility: 'visible',
                        opacity: 1,
                        transform: 'translateX(0)',
                        'z-index': 10
                    });
                } else if (isBackMode) {
                    // Add back button if not exists
                    if (!$submenu.find('.sitsel-mobile-back-submenu').length) {
                        var $backBtn = $('<button type="button" class="sitsel-mobile-back-submenu" aria-label="Back">← Back</button>');
                        $submenu.prepend($backBtn);
                    }

                    $submenu.css({
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        width: '100%',
                        height: '100%',
                        'max-height': '100%',
                        'overflow-y': 'auto',
                        display: 'block',
                        visibility: 'visible',
                        opacity: 1,
                        transform: 'translateX(0)',
                        'z-index': 10
                    });
                }
            }

            function closeSubmenu($li, immediate) {
                $li.removeClass('sitsel-sub-open');
                $li.find('> a').attr('aria-expanded', 'false');
              
                var $submenu = $li.children('.sitsel-sub-menu');
                if (!$submenu.length) return;

                // Close nested submenus
                $submenu.find('.sitsel-has-children.sitsel-sub-open').each(function() {
                    $(this).removeClass('sitsel-sub-open');
                    $(this).find('> a').attr('aria-expanded', 'false');
                });

                if (immediate) {
                    $submenu.hide().css({
                        transform: '',
                        opacity: '',
                        visibility: '',
                        position: '',
                        top: '',
                        left: '',
                        width: '',
                        height: '',
                        'max-height': '',
                        'overflow-y': '',
                        'z-index': ''
                    });
                    $submenu.find('.sitsel-mobile-back-submenu').remove();
                } else {
                    var isMobile = isSmall();
                    
                    if (isMobile && isBackMode) {
                        $submenu.css({ 
                            transform: 'translateX(100%)',
                            opacity: 0 
                        });
                        setTimeout(function() { 
                            $submenu.hide().css({
                                transform: '',
                                opacity: '',
                                visibility: '',
                                position: '',
                                top: '',
                                left: '',
                                width: '',
                                height: '',
                                'max-height': '',
                                'overflow-y': '',
                                'z-index': ''
                            });
                            $submenu.find('.sitsel-mobile-back-submenu').remove();
                        }, 320);
                    } else {
                        // $submenu.animate({ opacity: 0 }, 200, function() { 
                        //     $(this).hide().css('opacity', ''); 
                        // });
                        $submenu.stop(true).animate({ opacity: 0 }, 200, function() { 
                            $(this).hide().css('opacity', ''); 
                        });
                    }
                }
            }

            function closeAllMenus() {
                hideOverlay();
                
                // Close regular submenus - SCOPED TO THIS WIDGET
                $widget.find('.sitsel-has-children.sitsel-sub-open').not('.sitsel-mega-open').each(function() {
                    closeSubmenu($(this), true);
                });
                
                // Close mega menus
                $widget.find('.sitsel-mega-open').each(function() {
                    closeMegaMenu($(this), true);
                });
                
                // Remove mobile templates
                $widget.find('.sitsel-mobile-template').remove();
                $widget.find('.sitsel-mobile-template-open').removeClass('sitsel-mobile-template-open');
                $widget.find('a[aria-expanded]').attr('aria-expanded', 'false');
            }

            // ===============================
            // MOBILE TEMPLATE FUNCTIONS
            // ===============================
            function removeTemplate($tpl) {
                if (!$tpl || !$tpl.length) return;
                
                if (isBackMode) {
                    $tpl.css({ transform: 'translateX(100%)', opacity: 0 });
                    setTimeout(function() { $tpl.remove(); }, 320);
                } else if (isDefaultMode) {
                    $tpl.css({ opacity: 0, visibility: 'hidden' });
                    setTimeout(function() { $tpl.remove(); }, 200);
                } else {
                    $tpl.slideUp(200, function() { $(this).remove(); });
                }
            }

            function openMobileTemplateForLi(templateId, $li) {
                if (!isSmall()) return;

                var $submenu = $li.find('> .sitsel-sub-menu.sitsel-mega-sub-menu');
                if (!$submenu.length) return;

                // Remove other templates
                var $others = $widget.find('.sitsel-mobile-template').not($li.find('.sitsel-mobile-template'));
                $others.each(function() { removeTemplate($(this)); });
                
                // Close other submenus
                $widget.find('.sitsel-has-children.sitsel-sub-open').not($li).each(function() {
                    closeSubmenu($(this), true);
                });

                // Toggle if already open
                var $existing = $li.children('.sitsel-mobile-template');
                if ($existing.length) {
                    removeTemplate($existing);
                    $li.removeClass('sitsel-mobile-template-open');
                    $li.find('> a').attr('aria-expanded', 'false');
                    return;
                }

                // Create new template
                var $new = $('<div class="sitsel-mobile-template" />');
                $new.html($submenu.html());

                // Convert links to spans
                $new.find('> a').each(function() {
                    var $a = $(this);
                    if ($a.hasClass('sitsel-mobile-back')) return;
                    
                    var $span = $('<span/>');
                    var $contents = $a.contents().clone(); 
                    $span.append($contents);
                    
                    var classes = $a.attr('class');
                    if (classes) $span.attr('class', classes + ' sitsel-mobile-link');
                    
                    var style = $a.attr('style');
                    if (style) $span.attr('style', style);
                    
                    // Copy data attributes
                    $.each(this.attributes, function(i, attr) {
                        if (attr && attr.name && attr.name.indexOf('data-') === 0) {
                            $span.attr(attr.name, attr.value);
                        }
                    });
                    
                    $a.replaceWith($span);
                });

                // Add back button if back mode
                if (isBackMode) {
                    var $backBtn = $('<button type="button" class="sitsel-mobile-back" aria-label="Back to menu">← Back</button>');
                    $new.prepend($backBtn);
                }

                $li.append($new);

                // Open off-canvas if needed
                if (mobileDisplay === 'off_canvas' && !$widget.hasClass('sitsel-mm-offcanvas-open')) {
                    $widget.addClass('sitsel-mm-offcanvas-open');
                    $toggle.attr('aria-expanded', 'true');
                }

                $new.toggleClass('sitsel-mobile-transform', isBackMode);
                if (isBackMode) void $new[0].offsetWidth;

                $li.addClass('sitsel-mobile-template-open');
                $li.find('> a').attr('aria-expanded', 'true');

                // Show template with appropriate animation
                if (isBackMode) {
                    $new.css({ visibility: 'visible', opacity: 1, transform: 'translateX(0)' });
                } else if (isDefaultMode) {
                    $new.css({ visibility: 'visible', opacity: 1 });
                } else {
                    if (mobileDisplay === 'off_canvas') {
                        $new.css({ visibility: 'visible', opacity: 1 }).show();
                    } else {
                        $new.hide().slideDown(200);
                    }
                }
            }

            function closeMobileTemplateForLi($li) {
                var $tpl = $li.children('.sitsel-mobile-template');
                if ($tpl.length) {
                    removeTemplate($tpl);
                    $li.removeClass('sitsel-mobile-template-open');
                    $li.find('> a').attr('aria-expanded', 'false');
                }
                
                // Close off-canvas if no templates left
                if (mobileDisplay === 'off_canvas') {
                    var $anyMobile = $widget.find('.sitsel-mobile-template');
                    if ($anyMobile.length === 0) {
                        $widget.removeClass('sitsel-mm-offcanvas-open');
                        $toggle.attr('aria-expanded', 'false');
                    }
                }
            }

            // ===============================
            // RESPONSIVE LAYOUT HANDLER
            // ===============================
            function handleResponsive() {
                if (document.readyState === 'complete') {
        $toggle.css({
            'visibility': 'visible',
            'opacity': '1',
            'margin-left': 'auto',
            'align-self': 'flex-end',
            'transition': 'opacity 0.2s ease'
        });
    } else {
        $(window).on('load', function() {
            $toggle.css({
                'visibility': 'visible',
                'opacity': '1',
                'margin-left': 'auto',
                'align-self': 'flex-end',
                'transition': 'opacity 0.2s ease'
            });
        });
    }
				if (!showMobile || !hasBreakpoint) {
					$toggle.hide();
					$offcanvasClose.hide();
					$widget.removeClass('sitsel-mm-mobile');
					return;
				}

                if (isSmall()) {
                    $toggle.show();
                    $widget.addClass('sitsel-mm-mobile');

                    if (!$widget.hasClass('sitsel-mm-offcanvas-open') && !$widget.hasClass('sitsel-mm-open')) {
                        $toggle.attr('aria-expanded', 'false');
                        $toggle.find('.sitsel-icon-open').show();
                        $toggle.find('.sitsel-icon-close').hide();
                    }

                     if (!$widget.hasClass('sitsel-mm-offcanvas-open') && !$widget.hasClass('sitsel-mm-open')) {
                        if (mobileDisplay !== 'off_canvas') {
                            $mainWrapper.hide();
                        } else {
                            $mainWrapper.css('display', ''); // let CSS/transform control offcanvas
                        }
                    }

                    if (mobileDisplay === 'off_canvas') {
                        $widget.addClass('sitsel-mm-offcanvas');
                        // $('sitsel-mega-menu-main').css({'padding-top': getHeaderHeight + 'px'});
                        if (mobileStretch === 'full') {
                            $mainWrapper.css({ width: getViewportWidth() + 'px' });
                            $widget.addClass('sitsel-mm-offcanvas-stretch-full');
                        } else {
                            $mainWrapper.css({ width: '' });
                            $widget.removeClass('sitsel-mm-offcanvas-stretch-full');
                        }
                    } else {
                        $widget.removeClass('sitsel-mm-offcanvas sitsel-mm-offcanvas-stretch-full');
                    }
                    $offcanvasClose.hide();
                  
                
                        if (mobileDisplay === 'dropdown') {
                        var widgetRect = $widget[0].getBoundingClientRect();
                        $mainWrapper.css({
                            position:     'fixed',
                            top:          widgetRect.bottom + 'px',
                            left:         '0',
                            width:        '100vw',
                            'max-height': '80vh',
                            'overflow-y': 'auto',
                            'z-index':    96
                        });
                    }

                } else {
					$toggle.hide();
					$offcanvasClose.hide();
					$widget.removeClass('sitsel-mm-mobile sitsel-mm-offcanvas sitsel-mm-offcanvas-open sitsel-mm-open');
                
                    closeAllMenus();
                    resetOffcanvasStyles();
                    $mainWrapper.show();
                     $mainWrapper.css({ position: '', top: '', left: '', width: '', 'max-height': '', 'overflow-y': '', 'z-index': '' }); // ← add this
                     $('.sitsel-mega-menu-main').css({
                                'padding-top': ''
                            });
                }
            }

            handleResponsive();
            $(window).on('resize.megamenu.' + widgetId, handleResponsive);
            
            if (window.elementorFrontend && elementorFrontend.isEditMode()) {
                elementor.on('preview:loaded', handleResponsive);
            }

            // ===============================
            // EVENT HANDLERS
            // ===============================
            
            // Toggle button click
            $toggle.on('click', function(e) {
                e.preventDefault();

                var isOpen = $(this).attr('aria-expanded') === 'true';

                // Toggle aria & icons
                $(this).attr('aria-expanded', !isOpen);
                $(this).find('.sitsel-icon-open').toggle(isOpen);
                $(this).find('.sitsel-icon-close').toggle(!isOpen);

                if (mobileDisplay === 'off_canvas') {
                    // Toggle offcanvas class
                    $widget.toggleClass('sitsel-mm-offcanvas-open');
                    var isPanelOpen = $widget.hasClass('sitsel-mm-offcanvas-open');

                    if (isSmall()) {
                        // Mobile only
                        // if (isPanelOpen) {
                        //     // Open
                        //     var width = mobileStretch === 'full' ? getViewportWidth() + 'px' : '320px';
                        //    var translateOpen  = 'translateX(0)';
                        //     var translateClose = offcanvasDirection === 'right' ? 'translateX(100%)' : 'translateX(-100%)';
                        //     $mainWrapper.css({ transform: translateOpen });
                        //     $('.sitsel-mega-menu-main').css({
                        //         'padding-top': getHeaderHeight() + 'px'
                        //     });
                            
                        // } else {
                        //     // Close
                        //     closeAllMenus();
                        //   $mainWrapper.css({ transform: translateClose });
                        // }
                        var translateClose = offcanvasDirection === 'right' ? 'translateX(100%)' : 'translateX(-100%)';
                        if (isPanelOpen) {
                            $mainWrapper.css({ transform: 'translateX(0)' });
                            // $('.sitsel-mega-menu-main').css({ 'padding-top': getHeaderHeight() + 'px' });
                        } else {
                            closeAllMenus();
                            $mainWrapper.css({ transform: translateClose });
                        }
                    } else {
                        // Desktop reset
                        $mainWrapper.css({
                            width: '',
                            transform: ''
                        });
                         $('.sitsel-mega-menu-main').css({
                                'padding-top': ''
                            });
                    }
                } else {
                    // Dropdown mode
                    var isDropdownOpen = $widget.hasClass('sitsel-mm-open');

                    if (isDropdownOpen) {
                        $widget.removeClass('sitsel-mm-open');
                        $mainWrapper.slideUp(200);
                        closeAllMenus();
                   
                   } else {
    $widget.addClass('sitsel-mm-open');

    if (isSmall() && mobileDisplay === 'dropdown') {

        var $clswidget = $(this).closest('.elementor-widget');

// Set widget position
$clswidget.css('position', 'static');

// Get closest e-con-inner
var $parentInner = $clswidget.closest('header');

// Set this one relative
$parentInner.css('position', 'relative');

// Set all OTHER inner e-con-inner to static
$parentInner.find('header').not($parentInner).css('position', 'static');

// Get parent height
var parentHeight = $clswidget.outerHeight();

        // Apply dropdown position
    
var widgetRect = $widget[0].getBoundingClientRect();
$mainWrapper.css({
    position:     'fixed',
    top:          widgetRect.bottom + 'px',
    left:         '0',
    width:        '100vw',
    'max-height': '80vh',
});
    }

    $mainWrapper
        .slideDown(200)
        .css({ visibility: 'visible', opacity: 1 });
}
                }
            });
			
			// Off-canvas close button click
			$offcanvasClose.on('click', function(e) {
				e.preventDefault();

				$widget.removeClass('sitsel-mm-offcanvas-open');
				$toggle.attr('aria-expanded', 'false');
				$toggle.find('.sitsel-icon-open').show();
				$toggle.find('.sitsel-icon-close').hide();

				closeAllMenus();
				var translateClose = offcanvasDirection === 'right' ? 'translateX(100%)' : 'translateX(-100%)';
                $mainWrapper.css({ transform: translateClose });
			});

            // Mega menu handlers (desktop hover)
            if (submenuTrigger === 'hover') {
                $widget.on('mouseenter', '.sits-menu-item', function() {
                if (isSmall()) return;
                var $li = $(this);
                clearTimeout($li.data('hideTimer'));
                if (!hasMegaMenu($li)) return;
                showMegaMenuForLi($li);
            });

            // Also cancel hide when cursor enters the submenu itself
            $widget.on('mouseenter', '.sitsel-mega-sub-menu', function() {
                if (isSmall()) return;
                var $li = $(this).closest('.sits-menu-item');
                clearTimeout($li.data('hideTimer'));
            });
            // Trap scroll inside mega menu so page doesn't scroll underneath it
            $widget.on('wheel.megamenu', '.sitsel-mega-sub-menu', function(e) {
                if (isSmall()) return;
                var el = this;
                var deltaY = e.originalEvent.deltaY;
                var atTop = el.scrollTop === 0;
                var atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight;

                // Only block page scroll if the panel itself can't scroll further in that direction
                if ((deltaY < 0 && atTop) || (deltaY > 0 && atBottom)) {
                    e.preventDefault();
                } else if (el.scrollHeight > el.clientHeight) {
                    // Panel is scrollable — let it scroll, stop propagation to page
                    e.stopPropagation();
                } else {
                    // Panel not scrollable — block page scroll entirely while inside
                    e.preventDefault();
                }
            });

$widget.on('mouseleave', '.sits-menu-item, .sitsel-mega-sub-menu', function(e) {
    if (isSmall()) return;
    var $li = $(this).hasClass('sits-menu-item') ? $(this) : $(this).closest('.sits-menu-item');
    if (!hasMegaMenu($li)) return;
    clearTimeout($li.data('hideTimer'));
    var hideTimer = setTimeout(function() {
        var relatedTarget = e.relatedTarget || e.toElement;
        var insideLi = relatedTarget && ($li[0].contains(relatedTarget));
        var insideMega = relatedTarget && $li.find('.sitsel-mega-sub-menu')[0] && $li.find('.sitsel-mega-sub-menu')[0].contains(relatedTarget);
        if (!insideLi && !insideMega) {
            closeMegaMenu($li);
        }
    }, 400);
    $li.data('hideTimer', hideTimer);
});
            } else {
                // Mega menu click handler (desktop)
                $widget.on('click', '.sits-menu-item > a', function(e) {
                    if (isSmall()) return;
                    
                    var $li = $(this).closest('.sits-menu-item');
                    if (!hasMegaMenu($li)) return;
                    
                    e.preventDefault();
                    e.stopPropagation();
                    
                    // Close other menus
                    $widget.find('.sitsel-has-children.sitsel-sub-open').not($li).each(function() {
                        if (hasMegaMenu($(this))) {
                            closeMegaMenu($(this), true);
                        } else {
                            closeSubmenu($(this), true);
                        }
                    });
                    
                    // Toggle current menu
                    if ($li.hasClass('sitsel-mega-open')) {
                        closeMegaMenu($li);
                    } else {
                        showMegaMenuForLi($li);
                    }
                });
            }

            // Mobile mega menu click
            $widget.on('click', '.sits-menu-item > a', function(e) {
                if (!isSmall()) return;
                
                var $li = $(this).closest('.sits-menu-item');
                if (!hasMegaMenu($li)) return;
                
                e.preventDefault();
                e.stopPropagation();
                
                // Close all other menus
                $widget.find('.sits-menu-item').not($li).each(function() {
                    var $otherLi = $(this);
                    
                    if ($otherLi.hasClass('sitsel-mobile-template-open')) {
                        closeMobileTemplateForLi($otherLi);
                    }
                    
                    if ($otherLi.hasClass('sitsel-sub-open')) {
                        closeSubmenu($otherLi, true);
                    }
                });
                
                var templateId = getMegaMenuTemplateId($li);
                openMobileTemplateForLi(templateId, $li);
            });

            // Back button handlers
            $widget.on('click', '.sitsel-mobile-back', function(e) {
                e.preventDefault();
                var $li = $(this).closest('li');
                closeMobileTemplateForLi($li);
            });

            $widget.on('click', '.sitsel-mobile-back-submenu', function(e) {
                e.preventDefault();
                var $submenu = $(this).closest('.sitsel-sub-menu');
                var $li = $submenu.closest('.sitsel-has-children');
                closeSubmenu($li);
            });

            // Regular submenu hover handlers
            if (submenuTrigger === 'hover') {
                $widget.on('mouseenter', '.sitsel-has-children', function() {
                    if (isSmall()) return;
                    
                    var $li = $(this);
                    if (hasMegaMenu($li)) return;
                    
                    clearTimeout($li.data('hideTimer'));
                    
                    // Close mega menus
                    $widget.find('.sitsel-mega-open').each(function() {
                        closeMegaMenu($(this), true);
                    });
                    
                    // Close sibling submenus
                    $li.siblings('.sitsel-sub-open').each(function() {
                        closeSubmenu($(this), true);
                    });
                    
                    openSubmenu($li);
                });

                $widget.on('mouseleave', '.sitsel-has-children', function() {
                    if (isSmall()) return;
                    
                    var $li = $(this);
                    if (hasMegaMenu($li)) return;
                    
                    var hideTimer = setTimeout(function() {
                        closeSubmenu($li);
                    }, 150);
                    $li.data('hideTimer', hideTimer);
                });
            }
            
            // Click handler for submenus (both mobile and click mode)
            $widget.on('click', '.sitsel-has-children > a', function(e) {
                var $li = $(this).closest('.sitsel-has-children');
                if (hasMegaMenu($li)) return;

                if (isSmall() || submenuTrigger === 'click') {
                    e.preventDefault();
                    e.stopPropagation();

                    var $parentUl = $li.parent(); 

                    // Close only siblings at same level + their nested children
                    $parentUl.children('.sitsel-has-children').not($li).each(function() {
                        var $sibling = $(this);

                        if ($sibling.hasClass('sitsel-sub-open')) {
                            // Close all nested submenus inside sibling first
                            $sibling.find('.sitsel-has-children.sitsel-sub-open').each(function() {
                                closeSubmenu($(this), true);
                            });
                            
                            // Then close the sibling itself
                            closeSubmenu($sibling, true);
                        }
                    });

                    // Close mega menus only if they are NOT ancestors
                    $widget.find('.sitsel-mega-open').not($li.parents()).each(function() {
                        closeMegaMenu($(this), true);
                    });

                    // Mobile template close (safe)
                    $widget.find('.sits-menu-item.sitsel-mobile-template-open')
                        .not($li.parents())
                        .each(function() {
                            closeMobileTemplateForLi($(this));
                        });

                    // Toggle current item
                    if ($li.hasClass('sitsel-sub-open')) {
                        // Close all nested submenus inside current item first
                        $li.find('.sitsel-has-children.sitsel-sub-open').each(function() {
                            closeSubmenu($(this), true);
                        });
                        
                        // Then close the current item
                        closeSubmenu($li);
                    } else {
                        openSubmenu($li);
                    }
                }
            });
            
            
            // ===============================
            // GLOBAL EVENT HANDLERS (SCOPED)
            // ===============================
            
            // Close on outside click
           
// 			$(document).on('click.megamenu.' + widgetId, function(e) {
// 				if (!$(e.target).closest('#' + widgetId).length) {
// 					closeAllMenus();
// 					$widget.removeClass('sitsel-mm-offcanvas-open sitsel-mm-open');

// 					// Reset toggle icons
// 					$toggle.attr('aria-expanded', 'false');
// 					$toggle.find('.sitsel-icon-open').show();
// 					$toggle.find('.sitsel-icon-close').hide();
// 				}
// 			});

$(document).on('click.megamenu.' + widgetId, function(e) {
    if (!$(e.target).closest('#' + widgetId).length) {
        closeAllMenus();
        $widget.removeClass('sitsel-mm-offcanvas-open sitsel-mm-open');

        // Reset toggle icons
        $toggle.attr('aria-expanded', 'false');
        $toggle.find('.sitsel-icon-open').show();
        $toggle.find('.sitsel-icon-close').hide();

       
        if (mobileDisplay === 'off_canvas' && isSmall()) {
            var translateClose = offcanvasDirection === 'right' ? 'translateX(100%)' : 'translateX(-100%)';
            $mainWrapper.css({ transform: translateClose });
        }
       
        if (mobileDisplay === 'dropdown' && isSmall()) {
            $widget.removeClass('sitsel-mm-open');
            $mainWrapper.hide().css({ transform: '' });
        }
    }
});

            // Close on Escape key
            
// 			$(document).on('keyup.megamenu.' + widgetId, function(e) {
// 				if (e.key === 'Escape' || e.which === 27) {
// 					closeAllMenus();
// 					$widget.removeClass('sitsel-mm-offcanvas-open sitsel-mm-open');

// 					// Reset toggle icons
// 					$toggle.attr('aria-expanded', 'false');
// 					$toggle.find('.sitsel-icon-open').show();
// 					$toggle.find('.sitsel-icon-close').hide();
// 				}
// 			});

$(document).on('keyup.megamenu.' + widgetId, function(e) {
    if (e.key === 'Escape' || e.which === 27) {
        closeAllMenus();
        $widget.removeClass('sitsel-mm-offcanvas-open sitsel-mm-open');

        $toggle.attr('aria-expanded', 'false');
        $toggle.find('.sitsel-icon-open').show();
        $toggle.find('.sitsel-icon-close').hide();

        
        if (mobileDisplay === 'off_canvas' && isSmall()) {
            var translateClose = offcanvasDirection === 'right' ? 'translateX(100%)' : 'translateX(-100%)';
            $mainWrapper.css({ transform: translateClose });
        }
        if (mobileDisplay === 'dropdown') {
            $mainWrapper.hide().css({ transform: '' });
        }
    }
});
            
            // Store cleanup function
            $widget.data('megamenu-cleanup', function() {
                $(window).off('resize.megamenu.' + widgetId);
                $(window).off('scroll.megamenu.' + widgetId);
                $(document).off('click.megamenu.' + widgetId);
                $(document).off('keyup.megamenu.' + widgetId);
                $widget.off('wheel.megamenu'); 
            });
        });
    }
});