/* Minimal Main JavaScript - Only essentials, ~1KB gzipped */
(function() {
  'use strict';
  
  // Cache DOM queries
  const elements = {
    nav: null,
    navToggle: null,
    closeToggle: null,
    menuItems: null
  };
  
  // Initialize when DOM ready
  function init() {
    // Get elements
    elements.nav = document.querySelector('.header__navigation');
    elements.navToggle = document.querySelector('.header__navigation--toggle');
    elements.closeToggle = document.querySelector('.header__close--toggle');
    elements.menuItems = document.querySelectorAll('.menu__item--has-submenu');
    
    if (!elements.nav) return;
    
    // Mobile menu toggle
    if (elements.navToggle) {
      elements.navToggle.addEventListener('click', toggleNav, { passive: true });
    }
    
    if (elements.closeToggle) {
      elements.closeToggle.addEventListener('click', closeNav, { passive: true });
    }
    
    // Desktop dropdown menus (keyboard accessible)
    elements.menuItems.forEach(item => {
      const link = item.querySelector('.menu__link');
      const toggle = item.querySelector('.menu__child-toggle');
      
      // Keyboard navigation
      if (link) {
        link.addEventListener('focus', () => openSubmenu(item));
        link.addEventListener('blur', (e) => {
          if (!item.contains(e.relatedTarget)) {
            closeSubmenu(item);
          }
        });
      }
      
      // Mobile submenu toggle
      if (toggle) {
        toggle.addEventListener('click', (e) => {
          e.preventDefault();
          item.classList.toggle('menu__item--open');
        });
      }
    });
    
    // Close mobile menu on escape
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && elements.nav.classList.contains('open')) {
        closeNav();
      }
    });
    
    // Close mobile menu when clicking outside
    document.addEventListener('click', (e) => {
      if (elements.nav.classList.contains('open') && 
          !elements.nav.contains(e.target) && 
          !elements.navToggle.contains(e.target)) {
        closeNav();
      }
    });
  }
  
  function toggleNav() {
    elements.nav.classList.toggle('open');
    elements.closeToggle.classList.toggle('show');
    document.body.style.overflow = elements.nav.classList.contains('open') ? 'hidden' : '';
  }
  
  function closeNav() {
    elements.nav.classList.remove('open');
    elements.closeToggle.classList.remove('show');
    document.body.style.overflow = '';
  }
  
  function openSubmenu(item) {
    item.classList.add('menu__item--open');
  }
  
  function closeSubmenu(item) {
    item.classList.remove('menu__item--open');
  }
  
  // Initialize when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();