const mobileToggle = document.querySelector('.mobile-toggle');
const navWrap = document.querySelector('.nav-wrap');
const backdrop = document.querySelector('.menu-backdrop');
const navItems = document.querySelectorAll('.nav-item.has-submenu');

if (mobileToggle && navWrap) {
  mobileToggle.addEventListener('click', () => {
    navWrap.classList.toggle('show');
    backdrop?.classList.toggle('show');
  });
}

backdrop?.addEventListener('click', () => {
  navWrap?.classList.remove('show');
  backdrop.classList.remove('show');
  navItems.forEach((item) => item.classList.remove('open'));
});

navItems.forEach((item) => {
  const trigger = item.querySelector('.nav-link');
  trigger?.addEventListener('click', (event) => {
    if (window.innerWidth > 980) return;
    event.preventDefault();
    const isOpen = item.classList.contains('open');
    navItems.forEach((other) => other.classList.remove('open'));
    if (!isOpen) item.classList.add('open');
  });
});

window.addEventListener('resize', () => {
  if (window.innerWidth > 980) {
    navWrap?.classList.remove('show');
    backdrop?.classList.remove('show');
    navItems.forEach((item) => item.classList.remove('open'));
  }
});
