import $ from 'jquery';

class IHKContact {
  constructor(wrapper) {
    this.wrapper = wrapper;
    this.wrapper = wrapper.addClass('initiated');
    this.contactsWrapper = wrapper.find('.contacts');
    this.contacts = this.contactsWrapper.find('.contact-person');
    this.current = 0;
    this.tabStyle = wrapper.data('tab-style');
    this.TABS_CLOSED = "closed";
    this.TABS_OPEN = "open";

    this.initTabs();
    this.initSizeObserver();
  }

  initTabs() {
    if (this.tabStyle === this.TABS_OPEN || this.contacts.length < 2) {
      this.contacts.addClass('active');
      return;
    }

    this.tabs = $('<ul />').addClass('tab-buttons').insertBefore(this.contactsWrapper);

    this.contacts.each((i, el) => {
      const c = $(el);
      const a = $('<a href="' + c.attr('id') + '" />').attr('data-index', i).text(c.data('contact-tab'));
      a.addClass('btn').addClass('btn-small');
      if (!c.data('contact-tab')) {
        a.text( i < 9 ? '0' + (i + 1) : i + 1 );
      }
      $('<li />').append(a).appendTo(this.tabs);
    });

    const tabAnchors = this.tabs.find('a');

    tabAnchors.on('click', (e) => {
      e.preventDefault();
      const btn = $(e.currentTarget);
      const index = parseInt(btn.attr('data-index'));
      this.contacts.eq(index).addClass('active').siblings('.active').removeClass('active');
      btn.parent('li').addClass('active').siblings('.active').removeClass('active');
      this.changeHeight(this.current, index);
      this.current = index;
    });

    if(this.tabStyle !== this.TABS_CLOSED){
      tabAnchors.first().trigger('click');
    }
  }

  changeHeight(prev, next) {
    if (prev === next) {
      return;
    }

    this.contactsWrapper.css('height', this.contacts.eq(prev).outerHeight() + 'px');

    setTimeout(() => {
      this.contactsWrapper.css('height', this.contacts.eq(next).outerHeight() + 'px');
    }, 40)
    setTimeout(() => {
      this.contactsWrapper.removeAttr('style').trigger('resize');
    }, 500)
  }

  initSizeObserver() {
    const observer = new ResizeObserver((entries) => {
      entries.map((entry) => {
        const w = entry.borderBoxSize[0].inlineSize;
        const wrapper = this.wrapper.get(0);
        if (w < 500) {
          wrapper.dataset.size = 'sm';
        } else if (w < 1000) {
          wrapper.dataset.size = 'md';
        } else {
          wrapper.dataset.size = 'lg';
        }
      })
    })

    observer.observe(this.wrapper.get(0));
  }
}

export default IHKContact;

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