import $ from "jquery";

class IHKMagazineHeader {
  constructor(header) {
    this.header = header.addClass('initiated');
    this.gradient = header.find('.gradient');
    this.title = header.find('.title');
    this.window = $(window);
    this.minScale = 0;
    this.preventResize = false;

    this.initSizeObserver();
    this.initScroll();

    $('body')
      .on('overlay-open', () => {
        this.preventResize = true;
      })
      .on('overlay-close', () => {
        this.preventResize = false;
      })
  }

  initSizeObserver() {
    const observer = new ResizeObserver(() => {
      this.getMinScale();
    })
    observer.observe(this.header.get(0));
  }

  initScroll() {
    window.addEventListener("scroll", () => {
      window.requestAnimationFrame( () => {
        if (!this.preventResize) {
          this.checkScroll();
        }
      })
    },{passive: true});

    this.checkScroll();
  };

  checkScroll() {
    const st = this.window.scrollTop();
    let scale = 1 - Math.round(st / 4) / 100;
    const opacity = 1 - Math.round(st / 2) / 100;

    if (scale < 0) {
      scale = 0;
    }

    this.gradient.css({'transform': 'scale(1, ' + (scale > this.minScale ? scale : this.minScale) + ')'});
    this.title.css({
      'transform': 'translate(-50%, -50%) scale(' + scale + ')',
      'opacity': opacity > 0 ? opacity : 0
    })
  }

  getMinScale() {
    this.minScale = Math.round(1000 / this.header.outerHeight()) / 100;
  }
}

export default IHKMagazineHeader;

$('body').on('ihk-init dynamic-component-loaded gfi-dynamic-init', function () {
  const body = $(this);
  $('.magazine-header:not(.initiated)').each(function(i) {
    new IHKMagazineHeader($(this));
  });
})
