document.addEventListener('DOMContentLoaded', function() { 
  const body = document.body; 
  const header = document.getElementById('site-header-main'); 
  const mobileMenuToggle = document.getElementById('mobile-menu-toggle'); 
  const dropdownItems = document.querySelectorAll('.hs-item-has-children'); 

  // Function to close all open sub-menu dropdowns 
  const closeAllDropdowns = () => { 
    dropdownItems.forEach(item => { 
      item.classList.remove('is-open'); 
    }); 
  }; 

  // --- Mobile Menu (Hamburger) Toggle --- 
  if (mobileMenuToggle) { 
    mobileMenuToggle.addEventListener('click', function(e) { 
      e.stopPropagation(); 
      body.classList.toggle('mobile-menu-active'); 
      const isExpanded = body.classList.contains('mobile-menu-active'); 
      mobileMenuToggle.setAttribute('aria-expanded', isExpanded); 
    }); 
  } 

  // --- Sub-Menu Dropdown Click Logic (for both Desktop and Mobile) --- 
  dropdownItems.forEach(item => { 
    const link = item.querySelector('a'); 
    if (link) { 
      link.addEventListener('click', function(e) { 
        // For items with children, prevent navigation and toggle the accordion
        e.preventDefault(); 
        e.stopPropagation(); 

        const wasOpen = item.classList.contains('is-open'); 
        
        // Close any other open dropdowns before opening the new one
        closeAllDropdowns(); 
         
        // If it wasn't already open, open it now
        if (!wasOpen) { 
          item.classList.add('is-open'); 
        } 
      }); 
    } 
  }); 

  // --- Global Click Listener to Close Menus --- 
  document.addEventListener('click', function(e) {
    // Check if the click happened on the toggle button or inside the header.
    // If so, let the other listeners handle it and do nothing here.
    if (mobileMenuToggle.contains(e.target) || (header && header.contains(e.target))) {
      return;
    }
    
    // If the click was outside, then close everything.
    closeAllDropdowns(); 
  
    if (body.classList.contains('mobile-menu-active')) { 
      body.classList.remove('mobile-menu-active'); 
      mobileMenuToggle.setAttribute('aria-expanded', 'false'); 
    } 
  });
    
  // --- Cleanup on Window Resize --- 
  window.addEventListener('resize', function() { 
    if (window.innerWidth > 991) { 
      body.classList.remove('mobile-menu-active'); 
      if (mobileMenuToggle) { 
        mobileMenuToggle.setAttribute('aria-expanded', 'false'); 
      } 
      closeAllDropdowns(); 
    } 
  }); 
});