/**
 * Mobile Menu Dropdown Fix
 * Ensures mobile submenus work properly
 */

(function() {
  'use strict';

  function initMobileDropdowns() {
    const mobileMenu = document.querySelector('.header-mobile-menu');
    if (!mobileMenu) return;

    // Find all menu items with submenus - use direct child selector
    const menuItems = mobileMenu.querySelectorAll('> ul > li.has-submenu');
    
    if (menuItems.length === 0) {
      // Fallback: try without direct child selector
      const fallbackItems = mobileMenu.querySelectorAll('li.has-submenu');
      if (fallbackItems.length > 0) {
        setupDropdownHandlers(fallbackItems);
      }
      return;
    }
    
    setupDropdownHandlers(menuItems);
  }
  
  function setupDropdownHandlers(menuItems) {
    menuItems.forEach(function(menuItem) {
      // Get the first direct child anchor tag
      const menuLink = menuItem.firstElementChild;
      if (!menuLink || menuLink.tagName !== 'A') return;

      // Remove old listener by checking attribute
      if (menuLink.getAttribute('data-dropdown-handler')) {
        return; // Already initialized
      }
      
      menuLink.setAttribute('data-dropdown-handler', 'true');

      menuLink.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();

        // Check if this menu is already active
        const isActive = menuItem.classList.contains('active');

        // Close all other menus
        menuItems.forEach(function(item) {
          if (item !== menuItem) {
            item.classList.remove('active');
          }
        });

        // Toggle current menu
        if (isActive) {
          menuItem.classList.remove('active');
        } else {
          menuItem.classList.add('active');
        }
      });
    });
  }

  // Initialize on page load
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
      setTimeout(initMobileDropdowns, 100);
    });
  } else {
    setTimeout(initMobileDropdowns, 100);
  }

  // Also initialize when mobile menu opens
  const mobileMenuBtn = document.querySelector('.header-mobile-menu-btn');
  if (mobileMenuBtn) {
    mobileMenuBtn.addEventListener('click', function() {
      setTimeout(function() {
        initMobileDropdowns();
      }, 200);
    });
  }

  // Re-initialize when menu becomes visible
  const observer = new MutationObserver(function(mutations) {
    const mobileMenu = document.querySelector('.header-mobile-menu');
    if (mobileMenu && mobileMenu.classList.contains('active')) {
      initMobileDropdowns();
    }
  });

  const mobileMenu = document.querySelector('.header-mobile-menu');
  if (mobileMenu) {
    observer.observe(mobileMenu, {
      attributes: true,
      attributeFilter: ['class']
    });
  }

})();

