jQuery(document).ready(function($) {

    // Mobile Mega Menu
    var $toggleButton = $('.gw-mm__toggle');

    $toggleButton.on('click', function() {
        $('body').toggleClass('mobile-mega-menu-open');
    });

  // ****************
  // Desktop Mega Menu
  // ****************

  // Toggle dropdown menu when clicking the parent item
  $('.gw-mm-item.has-children .gw-mm-item__link').click(function() {
    var dropdownWrapper = $(this).siblings('.gw-mm-item__dropdown-wrapper');
    dropdownWrapper.toggleClass('active');
    $(this).find('.gw-mm-item__toggle').toggleClass('active');

    // Add active class to the <a href> element just before the button
    var anchorElement = $(this).find('a');
    if (anchorElement.length) {
        anchorElement.toggleClass('active');
    }

    // Add class to body when toggle is active
    if ($(this).find('.gw-mm-item__toggle').hasClass('active')) {
      $('body').addClass('mega-menu-open');
    } else {
      $('body').removeClass('mega-menu-open');
    }

    // Hide other dropdown menus except the one being clicked
    $('.gw-mm-item__dropdown-wrapper').not(dropdownWrapper).removeClass('active');
    $('.gw-mm-item__toggle').not($(this).find('.gw-mm-item__toggle')).removeClass('active');
    $('.gw-mm-item__link a').not(anchorElement).removeClass('active');

  });

  // Prevent default link behavior
  $('.gw-mm-item.has-children .gw-mm-item__link').on('click', function(e) {
    e.preventDefault();
  });

  // Close dropdown menu when clicking outside the mega menu
  $(document).on('click', function(e) {
    if (!$(e.target).closest('.gw-mm').length) {
      $('.gw-mm-item__dropdown-wrapper').removeClass('active');
      $('.gw-mm-item__toggle').removeClass('active');
      $('.gw-mm-item__link a').removeClass('active');
      $('body').removeClass('mega-menu-open');
    }
  });


});


