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

class IHKAccordion {
  constructor(section) {
    this.section = section.addClass('initiated');
    this.section.find('.accordion-toggler').parent('li').attr('aria-label', 'Klappmenü geschlossen');

    this.section.find('.accordion-toggler').off('click').on('click', (e) => {
      e.preventDefault();
      const item = $(e.currentTarget).closest('li');
      item.toggleClass('open').find('.accordion-content').stop().slideToggle(300, 'easeOutQuad');
      if(item.hasClass('open')){
        item.attr('aria-label', 'Klappmenü geöffnet');
      }
      else{
        item.attr('aria-label', 'Klappmenü geschlossen');
      }
      if (this.section.data('single-open') !== false) {
        const siblingsToClose = item.siblings('.open');
        siblingsToClose.attr('aria-label', 'Klappmenü geschlossen');
        siblingsToClose.removeClass('open').find('.accordion-content').slideUp(300, 'easeOutQuad');
      }
    });

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

  initEvent() {
    this.openEvent();
    this.section.find('.referee-details').hide();
    this.section.find('.referees > li > a').on('click', function (e) {
      e.preventDefault();
      $(this).siblings('.referee-details').slideToggle(300, 'easeOutQuad');
    })
    this.section.find('.referees .referee-details a.btn').on('click', function (e) {
      e.preventDefault();
      $(this).closest('.referee-details').slideUp(300, 'easeOutQuad');
    })
  };

  openEvent() {
    const t = this;
    const vars = getUrlVars();
    const $events = t.section.find('.accordion-content');
    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 IHKAccordion;

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