document.addEventListener('DOMContentLoaded', () => {
  const menuToggle = document.getElementById('menu-toggle');
  const menuOverlay = document.getElementById('menu-overlay');
  const menuPanel = document.getElementById('menu-panel');

  function toggleMenu() {
    if (!menuOverlay || !menuPanel) return;

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

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

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

  function closeMenu() {
    if (!menuOverlay || menuOverlay.classList.contains('opacity-0')) return;
    toggleMenu();
  }

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

  // Close menu when clicking on the overlay
  if (menuOverlay) {
    menuOverlay.addEventListener('click', (e) => {
      if (e.target === menuOverlay) {
        closeMenu();
      }
    });
  }

  // Close menu when clicking menu items
  const menuLinks = document.querySelectorAll('#menu-panel a, #menu-panel button');
  menuLinks.forEach(link => {
    link.addEventListener('click', closeMenu);
  });

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