/**
 * @file
 * Search functionality
 */

Drupal.behaviors.themekitSearch = {
  attach(context) {
    const { body } = document;
    const header = (context.classList && context.classList.contains('region-header')) ? context : context.querySelector('.region-header');
    if (!header) return;

    const search = header.querySelector('.search-wrapper');
    if (!search) return;

    const buttonToggleSearch = once('search-popup-toggle', header.querySelectorAll('.search-popup-toggle'), context);
    if (buttonToggleSearch.length) {
      buttonToggleSearch.forEach((button) => {
        button.addEventListener('click', (event) => {
          event.preventDefault();
          search.classList.toggle('is-search-open');
          if (!header.querySelector('.navigation-wrapper.is-active')) {
            body.classList.toggle('is-overflow');
          }

          if (search.classList.contains('is-search-open')) {
            event.target.setAttribute('aria-expanded', 'true');
          } else {
            event.target.setAttribute('aria-expanded', 'false');
          }
        });
      });
    }

    const buttonCloseSearch = header.querySelectorAll('.close-popup');
    if (buttonCloseSearch.length) {
      buttonCloseSearch.forEach((button) => {
        button.addEventListener('click', (event) => {
          event.preventDefault();
          search.classList.remove('is-search-open');
          if (!header.querySelector('.navigation-wrapper.is-active')) {
            body.classList.remove('is-overflow');
          }
          search.querySelector('.search-popup-toggle').setAttribute('aria-expanded', 'false');
        });
      });
    }
  },
};
