const menuButton = document.querySelector('.menu-button');
const siteNav = document.querySelector('.site-nav');

if (menuButton && siteNav) {
  const menuLabel = menuButton.querySelector('.sr-only');
  const desktopViewport = window.matchMedia('(min-width: 761px)');

  const setMenuState = (isOpen) => {
    siteNav.classList.toggle('open', isOpen);
    menuButton.setAttribute('aria-expanded', String(isOpen));
    if (menuLabel) menuLabel.textContent = isOpen ? 'Close navigation' : 'Open navigation';
  };

  menuButton.addEventListener('click', () => {
    setMenuState(!siteNav.classList.contains('open'));
  });

  siteNav.querySelectorAll('a').forEach((link) => {
    link.addEventListener('click', () => setMenuState(false));
  });

  document.addEventListener('keydown', (event) => {
    if (event.key === 'Escape' && siteNav.classList.contains('open')) {
      setMenuState(false);
      menuButton.focus();
    }
  });

  desktopViewport.addEventListener('change', (event) => {
    if (event.matches) setMenuState(false);
  });

  setMenuState(false);
}

const year = document.getElementById('year');
if (year) year.textContent = new Date().getFullYear();
