import $ from 'jquery';

class IHKSidebar {
  constructor(sidebar) {
    this.sidebar = sidebar.addClass('initiated');
    this.timer = null;

    const observer = new ResizeObserver((entries) => {
      this.handleResize();
    })
    observer.observe(sidebar.get(0));

    $(window).on('resize', () => {
      this.handleResize();
    })
  }

  handleResize() {
    if (this.timer) {
      clearTimeout(this.timer);
    }

    this.timer = window.setTimeout(() => {
      if (this.sidebar.outerHeight() < $(window).height() - 40) {
        this.sidebar.addClass('sticky');
      }
      else {
        this.sidebar.removeClass('sticky');
      }
    }, 250)
  }
}

export default IHKSidebar;

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