/**
 * @file
 * Mobile navigation toggle for Gutenberg Base theme.
 */

(function (Drupal, once) {
  'use strict';

  function closeNav(header, button) {
    button.setAttribute('aria-expanded', 'false');
    header.classList.remove('is-nav-open');
  }

  Drupal.behaviors.gutenbergBaseNavToggle = {
    attach: function (context) {
      once('nav-toggle', '.nav-toggle', context).forEach(function (button) {
        var header = button.closest('.site-header');
        if (!header) {
          return;
        }

        // Toggle on button click.
        button.addEventListener('click', function () {
          var expanded = button.getAttribute('aria-expanded') === 'true';
          button.setAttribute('aria-expanded', String(!expanded));
          header.classList.toggle('is-nav-open');
        });

        // Close on ESC key.
        document.addEventListener('keydown', function (e) {
          if (e.key === 'Escape' && header.classList.contains('is-nav-open')) {
            closeNav(header, button);
            button.focus();
          }
        });

        // Close when clicking outside the header.
        document.addEventListener('click', function (e) {
          if (header.classList.contains('is-nav-open') && !header.contains(e.target)) {
            closeNav(header, button);
          }
        });
      });
    },
  };
})(Drupal, once);
