import IHK from '../ihk';
const $ = require('jquery');
class Accordion {
  constructor(section) {
    this.section = section.addClass('initiated');
    this.section.find('.accordion-toggler').on('click', (e) => {
      e.preventDefault();
      const item = $(e.currentTarget).closest('li');
      item.toggleClass('open').find('.accordion-content').stop().slideToggle(400, 'easeOutQuad');
      if (this.section.data('single-open') !== false) {
        item.siblings('.open').removeClass('open').find('.accordion-content').slideUp(400, '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();
      const a = $(this);
      a.siblings('.referee-details').slideToggle(400, 'easeOutQuad');
    })
  };

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

    if ($queryParamEvent.length) {
      // open if the url params have the terminId
      $queryParamEvent.show().closest('li').addClass('open');
    } else {
      // open the first item as fallback
      $events.first().show().closest('li').addClass('open');
    }
  }
}

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