(function () {
  var header = document.querySelector('[data-site-header]');
  var menu = document.querySelector('[data-mobile-menu]');
  var toggle = document.querySelector('[data-menu-toggle]');
  if (!header || !menu || !toggle) {
    return;
  }

  var closeNodes = menu.querySelectorAll('[data-menu-close]');
  var mobileLinks = menu.querySelectorAll('.mobile-menu__link');

  function setScrollState() {
    if (window.scrollY > 16) {
      header.classList.add('site-header--scrolled');
    } else {
      header.classList.remove('site-header--scrolled');
    }
  }

  function openMenu() {
    menu.classList.add('mobile-menu--open');
    menu.setAttribute('aria-hidden', 'false');
    toggle.setAttribute('aria-expanded', 'true');
    document.body.classList.add('has-mobile-menu');
  }

  function closeMenu() {
    menu.classList.remove('mobile-menu--open');
    menu.setAttribute('aria-hidden', 'true');
    toggle.setAttribute('aria-expanded', 'false');
    document.body.classList.remove('has-mobile-menu');
  }

  toggle.addEventListener('click', function () {
    if (menu.classList.contains('mobile-menu--open')) {
      closeMenu();
      return;
    }
    openMenu();
  });

  closeNodes.forEach(function (node) {
    node.addEventListener('click', closeMenu);
  });

  mobileLinks.forEach(function (link) {
    link.addEventListener('click', closeMenu);
  });

  document.addEventListener('keydown', function (event) {
    if (event.key === 'Escape') {
      closeMenu();
    }
  });

  setScrollState();
  window.addEventListener('scroll', setScrollState, { passive: true });
})();
