/**
 * Navigation — mobile toggle + keyboard support
 *
 * @package Kutby
 */
(function () {
  'use strict';

  var toggle = document.querySelector('[data-kutby-nav-toggle]');
  var menu = document.querySelector('[data-kutby-nav]');
  var mq = window.matchMedia('(max-width: 767px)');

  if (!toggle || !menu) {
    return;
  }

  function setOpen(open) {
    menu.classList.toggle('is-open', open);
    toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
    if (mq.matches) {
      if (open) {
        menu.removeAttribute('hidden');
      } else {
        menu.setAttribute('hidden', '');
      }
    } else {
      menu.removeAttribute('hidden');
      menu.classList.remove('is-open');
      toggle.setAttribute('aria-expanded', 'false');
    }
  }

  function syncForViewport() {
    if (!mq.matches) {
      setOpen(false);
      menu.removeAttribute('hidden');
    } else if (!menu.classList.contains('is-open')) {
      menu.setAttribute('hidden', '');
    }
  }

  syncForViewport();

  toggle.addEventListener('click', function () {
    if (!mq.matches) {
      return;
    }
    setOpen(!menu.classList.contains('is-open'));
  });

  document.addEventListener('keydown', function (event) {
    if (event.key === 'Escape' && menu.classList.contains('is-open')) {
      setOpen(false);
      toggle.focus();
    }
  });

  if (typeof mq.addEventListener === 'function') {
    mq.addEventListener('change', syncForViewport);
  } else if (typeof mq.addListener === 'function') {
    mq.addListener(syncForViewport);
  }
})();
