document.addEventListener('DOMContentLoaded', () => {
  // Get the menu toggle button and overlay
  const menuToggle = document.getElementById('menu-toggle');
  const menuOverlay = document.getElementById('menu-overlay');

  /**
   * Toggle menu visibility and state
   */
  function toggleMenu() {
    const overlay = document.getElementById('menu-overlay');
    const menuPanel = document.querySelector('[x-ref="menuPanel"]');

    if (!overlay || !menuPanel) return;

    // Toggle overlay visibility classes
    overlay.classList.toggle('opacity-0');
    overlay.classList.toggle('invisible');

    // Toggle menu panel translation
    menuPanel.classList.toggle('translate-x-full');

    // Control body overflow
    const isMenuOpen = !overlay.classList.contains('opacity-0');
    document.body.style.overflow = isMenuOpen ? 'hidden' : '';
  }

  // Toggle menu when clicking the hamburger button
  if (menuToggle) {
    menuToggle.addEventListener('click', toggleMenu);
  }

  // Close menu when clicking on the overlay (but not the panel itself)
  if (menuOverlay) {
    menuOverlay.addEventListener('click', (e) => {
      // Only close if clicking the overlay itself, not the menu panel
      if (e.target === menuOverlay) {
        toggleMenu();
      }
    });
  }

  // Close menu on Escape key
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      const overlay = document.getElementById('menu-overlay');
      if (overlay && !overlay.classList.contains('opacity-0')) {
        toggleMenu();
      }
    }
  });
});
