import {getUrlVars} from "../../_global/scripts/helpers";
const $ = global.$;

class IHKSearchAccordion {
  constructor(section) {
    this.section = section.addClass('initiated');
    // this.section.find('#search-term').attr('aria-label', 'Klappmenü geschlossen');

    const openSearchHandler = (e) => {
      e.preventDefault();
      section.addClass('open');
      if(section.hasClass('open')){
        // section.attr('aria-label', 'Klappmenü geöffnet');
      }
      else{
        // section.attr('aria-label', 'Klappmenü geschlossen');
      }
      if (this.section.data('single-open') !== false) {
        section.siblings('.open').removeClass('open').find('.tiles').slideUp(300, 'easeOutQuart');
      }
    }

    this.section.find('#search-term')
        .off('click focus')
        .on('click focus', openSearchHandler);

    /* CLOSE */
    this.section.find('.close-search').off('click').on('click', (e) => {
      e.preventDefault();
      var heightOffset = section.get(0).offsetHeight;
      var existingStyleBlock = document.getElementById('dynamic-style');
      if (existingStyleBlock) {
        existingStyleBlock.parentNode.removeChild(existingStyleBlock);
      }
      var style = document.createElement('style');
      style.id = 'dynamic-style';
      //style.innerHTML = `section.marketingheader .search.open {max-height: ${heightOffset}px !important;}`;
      document.body.appendChild(style);

      setTimeout(() => {
        section.removeClass('open');
        if(section.hasClass('open')){
          // section.attr('aria-label', 'Klappmenü geschlossen');
        }
        else{
          // section.attr('aria-label', 'Klappmenü geöffnet');
        }
      }, 100);
    });

    if (section.attr('data-type') === 'event') {
      this.initEvent();
    }
  }

  initEvent() {
    this.openEvent();
    this.section.find('.tiles').hide();
  };

  openEvent() {
    const t = this;
    const vars = getUrlVars();
    const $events = t.section.find('.tiles');
    const $queryParamEvent = $('#js-event-' + vars['terminId']);

    if ($queryParamEvent.length) {
      $queryParamEvent.show().closest('li').addClass('open');
    } else {
      $events.first().show().closest('li').addClass('open');
    }
  }
}

export default IHKSearchAccordion;

$('body').on('ihk-init dynamic-component-loaded gfi-dynamic-init', function () {
  $('.marketingheader > .search:not(.initiated)').each(function (i) {
    new IHKSearchAccordion($(this));
  });
});

