(function( $ ) {
    'use strict';

    var SifencyMenuHandler = function( $scope, $ ) {
        
        var $wrapper = $scope.find('.sifency-nav-wrapper');
        var $toggle = $scope.find('.sifency-menu-toggle');
        var $closeBtn = $scope.find('.sifency-mobile-close-btn');
        var $menuContainer = $scope.find('.sifency-nav-menu');
        var $overlay = $scope.find('.sifency-mobile-overlay');
        
        var breakpoint = $wrapper.data('breakpoint') || 1024;

        function checkBreakpoint() {
            var winWidth = $(window).width();
            if (winWidth <= breakpoint) {
                $wrapper.addClass('sifency-mobile-active');
            } else {
                $wrapper.removeClass('sifency-mobile-active');
                $menuContainer.removeClass('is-active');
                $('body').removeClass('sifency-noscroll');
                $scope.find('.sub-menu').removeAttr('style').removeClass('sub-is-open');
            }
        }

        checkBreakpoint();
        $(window).on('resize', checkBreakpoint);

        $toggle.on('click', function(e) {
            e.preventDefault();
            $menuContainer.addClass('is-active');
            $overlay.addClass('is-active');
            $('body').addClass('sifency-noscroll');
        });

        function closeMenu() {
            $menuContainer.removeClass('is-active');
            $overlay.removeClass('is-active');
            $('body').removeClass('sifency-noscroll');
        }

        $closeBtn.on('click', closeMenu);
        
        $overlay.on('click', closeMenu);

        $(document).on('keyup', function(e) {
            if (e.key === "Escape" && $menuContainer.hasClass('is-active')) {
                closeMenu();
            }
        });

        var $dropdownToggle = $scope.find('.menu-item-has-children > a');
        
        $dropdownToggle.off('click').on('click', function(e) {
            if ($wrapper.hasClass('sifency-mobile-active')) {
                e.preventDefault();
                
                var $subMenu = $(this).siblings('.sub-menu');
                var $parentLi = $(this).parent();
                $scope.find('.menu-item-has-children').not($parentLi).find('.sub-menu').slideUp(300).removeClass('sub-is-open');
                $subMenu.stop().slideToggle(300).toggleClass('sub-is-open');
            }
        });

        $scope.find('.sifency-nav-menu a').on('click', function() {
            if ( ! $(this).parent().hasClass('menu-item-has-children') ) {
                if ($wrapper.hasClass('sifency-mobile-active')) {
                    closeMenu();
                }
            }
        });
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency_universal_menu.default', SifencyMenuHandler);
    });

})( jQuery );