$(document).ready(function() {
    // Initialize variables
    var lastWidth = $(window).width();
    var mobileMenu = null;

    // MobileNav class for handling menu interactions
    function MobileNav(options) {
        this.curItem = null;
        this.curLevel = 0;
        this.transitionTime = 0.2;

        // Default settings for MobileNav
        var defaults = {
            initElem: "nav",
            menuTitle: "Menu"
        };

        // Merge custom options with defaults
        this.options = $.extend({}, defaults, options);

        // Initialize the menu
        this.init();
    }

    // Initialize the MobileNav
    MobileNav.prototype.init = function() {
        this.setUpMenuHandlers();
    };

    // Set up menu click handlers for mobile navigation
    MobileNav.prototype.setUpMenuHandlers = function() {
        var _this = this;

        // Handle click on main menu items with submenus
        $(this.options.initElem).on('click', '.menu-item-has-children > a', function(e) {
            e.preventDefault();
            _this.curItem = $(this).parent();
            _this.toggleSubMenu();
        });

        // Handle the back button click
        $(this.options.initElem).on('click', '.nav-toggle', function() {
            _this.goBack();
        });
    };

    // Toggle the visibility of submenus
    MobileNav.prototype.toggleSubMenu = function() {
        var _this = this;

        if (this.curItem.hasClass('nav-dropdown-open')) {
            this.curItem.removeClass('nav-dropdown-open nav-dropdown-active');
            this.curLevel -= 1;
        } else {
            this.curItem.addClass('nav-dropdown-open nav-dropdown-active');
            this.curLevel += 1;
        }

        // Update the menu title based on the current level
        this.updateMenuTitle();

        // Slide the menu
        this.slideMenu();
    };

    // Go back to the previous menu
    MobileNav.prototype.goBack = function() {
        if (this.curLevel > 0) {
            this.curItem.removeClass('nav-dropdown-open nav-dropdown-active');
            this.curItem = this.curItem.parent().closest('li');
            this.curItem.addClass('nav-dropdown-open nav-dropdown-active');
            this.curLevel -= 1;
            this.updateMenuTitle();
            this.slideMenu();
        }
    };

    // Slide the menu based on the current level (translateX)
    MobileNav.prototype.slideMenu = function() {
        $(this.options.initElem).find('ul').css({
            'transform': 'translateX(-' + (this.curLevel * 100) + '%)',
            'transition': 'transform ' + this.transitionTime + 's ease'
        });
    };

    // Update the menu title based on the current item
    MobileNav.prototype.updateMenuTitle = function() {
        var title = this.options.menuTitle;
        if (this.curLevel > 0) {
            title = this.curItem.children('a').text();
            $(this.options.initElem).find('.nav-toggle').addClass('back-visible');
        } else {
            $(this.options.initElem).find('.nav-toggle').removeClass('back-visible');
        }
        $('.nav-title').text(title);
    };

    // Enable mobile navigation
    function enableMobileNav() {
        if ($(window).width() <= 991) {
            // Initialize the MobileNav instance for mobile navigation
            mobileMenu = new MobileNav({
                initElem: 'nav',       // The element for the menu (use "nav" or the main wrapper element)
                menuTitle: 'Menus'     // The initial title for the menu
            });

            // Handle toggle button click
            $('.js-nav-toggle').on('click', function(e) {
                e.preventDefault();
                $(this).toggleClass('nav-close');
                $('.nav-wrapper').toggleClass('show-menu');
                updateNavWrapperHeight();
            });
        }
    }

    // Disable mobile navigation (for larger screens)
    function disableMobileNav() {
        if (mobileMenu) {
            $(mobileMenu.options.initElem).off('click');
            mobileMenu = null;
        }
    }

    // Update the height of the nav wrapper based on visible menu items
    function updateNavWrapperHeight() {
        var navWrapper = $('.nav-wrapper');
        if (navWrapper.hasClass('show-menu')) {
            var totalHeight = 0;
            $('nav > ul > li:visible').each(function() {
                totalHeight += $(this).outerHeight(true);
            });

            if ($('.nav-toggle').is(':visible')) {
                totalHeight += $('.nav-toggle').outerHeight(true);
            }

            totalHeight += 5; // Extra margin
            navWrapper.height(totalHeight);
        } else {
            navWrapper.height(0);
        }
    }

    // Handle resizing and window width change
    function checkWidthChange() {
        var width = $(window).width();
        if ((lastWidth <= 991 && width > 991) || (lastWidth > 991 && width <= 991)) {
            if (width <= 991) {
                enableMobileNav();
            } else {
                disableMobileNav();
            }
        }
        lastWidth = width;
    }

    // Initial setup for mobile navigation
    if ($(window).width() <= 991) {
        enableMobileNav();
    }

    // Resize handler with debounce
    var resizeTimer;
    $(window).resize(function() {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(checkWidthChange, 250);
    });

});
