/**
 * hamburger.js
 * Hamburger menu toggle with focus trap and keyboard navigation
 */

export function initHamburger() {
  'use strict';

  const hamburgerBtn = document.getElementById('hamburger-btn');
  const menuOverlay = document.getElementById('menu-overlay');
  const menuLinks = document.querySelectorAll('.menu-links a');
  const themeSwitch = document.getElementById('theme-switch');

  if (!hamburgerBtn || !menuOverlay) return;

  // Toggle menu on hamburger click
  hamburgerBtn.addEventListener('click', () => {
    const isOpen = hamburgerBtn.getAttribute('aria-expanded') === 'true';
    setMenuOpen(!isOpen);
  });

  // Close menu on overlay click
  menuOverlay.addEventListener('click', (e) => {
    if (e.target === menuOverlay) {
      setMenuOpen(false);
    }
  });

  // Close menu on menu link click
  menuLinks.forEach((link) => {
    link.addEventListener('click', () => {
      setMenuOpen(false);
    });
  });

  // Close menu on Escape key
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      setMenuOpen(false);
    }
  });

  // Focus trap: Tab through menu items and theme switch
  menuOverlay.addEventListener('keydown', (e) => {
    if (e.key !== 'Tab') return;

    const focusableElements = Array.from(
      menuOverlay.querySelectorAll('a, button')
    );
    const firstElement = focusableElements[0];
    const lastElement = focusableElements[focusableElements.length - 1];

    if (e.shiftKey) {
      if (document.activeElement === firstElement) {
        lastElement.focus();
        e.preventDefault();
      }
    } else {
      if (document.activeElement === lastElement) {
        firstElement.focus();
        e.preventDefault();
      }
    }
  });

  function setMenuOpen(isOpen) {
    hamburgerBtn.setAttribute('aria-expanded', isOpen);
    hamburgerBtn.classList.toggle('active', isOpen);
    menuOverlay.classList.toggle('active', isOpen);

    if (isOpen) {
      document.body.style.overflow = 'hidden';
      // Focus the first menu link
      const firstLink = menuLinks[0];
      if (firstLink) {
        setTimeout(() => firstLink.focus(), 100);
      }
    } else {
      document.body.style.overflow = '';
      hamburgerBtn.focus();
    }
  }
}
