// Header Module - Enhanced Features (Loads Async)
// Only non-critical enhancements that can load after page render

(function() {
  'use strict';
  
  // Only initialize if header exists
  const header = document.querySelector('.site-header');
  if (!header) return;
  
  // Desktop dropdown side-placement (flip near the right edge).
  function setupDropdowns() {
    // Only apply to desktop
    if (window.innerWidth < 993) return;

    // TOP-LEVEL items only — placeDropdowns() must measure/flip only the L2
    // panels, never L2 items inside a dropdown or L3 fly-outs.
    const menuDropdowns = header.querySelectorAll('.menu-primary > .menu-item.has-children');

    // HubSpot native menus — top-level only too
    const hubspotDropdowns = header.querySelectorAll('.main-menu > ul > li.hs-item-has-children');

    const allDropdowns = [...menuDropdowns, ...hubspotDropdowns];

    // L2 dropdown show/hide is owned entirely by CSS `:hover` on the <li> (each
    // panel is a flush DOM child, so no JS gap-bridging is needed). The old JS
    // hover system held the previous panel visible for 300 ms after hover-out —
    // a sub-second double-panel — so it was removed (Batch 2d). placeDropdowns()
    // below is the only behaviour still needed.

    // Decide each dropdown's side BEFORE it is ever hovered, so a near-edge
    // panel opens leftward immediately — no per-hover style mutation, no
    // scrollbar flash, no jump. Re-check on resize and after webfonts load.
    function placeDropdowns() {
      const vw = document.documentElement.clientWidth; // excludes scrollbar
      allDropdowns.forEach((dropdown) => {
        const submenu = dropdown.querySelector(
          ':scope > .submenu, :scope > .menu-item-content + .submenu, :scope > .hs-menu-children-wrapper'
        );
        if (!submenu) return;
        submenu.classList.remove('submenu--flip');
        // Desktop CSS keeps dropdowns display:block (hidden via opacity/visibility),
        // so offsetWidth is measurable while the panel is closed.
        const width = submenu.offsetWidth || 200;
        const anchorLeft = dropdown.getBoundingClientRect().left;
        submenu.classList.toggle('submenu--flip', anchorLeft + width > vw);
      });
    }
    placeDropdowns();
    window.addEventListener('load', placeDropdowns); // re-measure after webfonts
    let placeTimer;
    window.addEventListener('resize', () => {
      clearTimeout(placeTimer);
      placeTimer = setTimeout(placeDropdowns, 150);
    });
  }
  
  // Accessibility Enhancements (non-critical)
  function setupAccessibility() {
    // Add current page indicator
    const currentLink = header.querySelector('.active a');
    if (currentLink) {
      currentLink.setAttribute('aria-current', 'page');
    }
    
    // Label navigation regions
    const mainNav = header.querySelector('.main-menu');
    if (mainNav) {
      mainNav.setAttribute('aria-label', 'Main navigation');
    }
    
    const userNav = header.querySelector('.membership-menu');
    if (userNav) {
      userNav.setAttribute('aria-label', 'User navigation');
    }
    
    // Focus trap for mobile menu (if open)
    const navMenu = header.querySelector('.nav-menu');
    if (navMenu) {
      const focusableElements = navMenu.querySelectorAll(
        'a, button, input, select, textarea, [tabindex]:not([tabindex="-1"])'
      );
      
      if (focusableElements.length > 0) {
        const firstFocusable = focusableElements[0];
        const lastFocusable = focusableElements[focusableElements.length - 1];
        
        navMenu.addEventListener('keydown', (e) => {
          if (!navMenu.classList.contains('open')) return;
          
          if (e.key === 'Tab') {
            if (e.shiftKey) {
              // Shift + Tab
              if (document.activeElement === firstFocusable) {
                e.preventDefault();
                lastFocusable.focus();
              }
            } else {
              // Tab
              if (document.activeElement === lastFocusable) {
                e.preventDefault();
                firstFocusable.focus();
              }
            }
          }
        });
      }
    }
  }
  
  // Initialize non-critical features when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      setupDropdowns();
      setupAccessibility();
    });
  } else {
    setupDropdowns();
    setupAccessibility();
  }
})();