import { InobyModule } from "@lib/inoby-module";
import * as $ from "jquery";

class StickyScroll extends InobyModule {
  private lastScroll: number = 0;
  private $side: JQuery<HTMLElement>;
  private $header: JQuery<HTMLElement>;

  run() {
    // do nothing
  }

  runAsync() {
    this.$side = $(".sticky-side-menu");
    this.$header = $("#header");

    if (this.$side?.length > 0) {
      this.stickyScroll();

      $(window).on("scroll", () => this.stickyScroll);
      $(window).on("resize", () => this.stickyScroll);
      $(".sticky-side-menu").on("resize", () => this.stickyScroll);
      $(".sticky-side-menu")
        .parent()
        .on("resize", () => this.stickyScroll);
    }
  }

  private stickyScroll() {
    const scroll = $(window).scrollTop();
    const delta = this.lastScroll - scroll;
    this.lastScroll = scroll;

    // disabled on mobile, when sidebar is "opened"
    if (this.$side.hasClass("active")) return;

    if (this.$side.length && this.$header.length) {
      var viewH = $(window).height();
      var sideH = this.$side.height();
      var sideT = this.$side.offset().top;
      var hdrH = this.$header.height();

      var maxT = hdrH;
      var minT = viewH - sideH;
      var proposeTop = hdrH;
      if (sideH + hdrH >= viewH) {
        proposeTop = sideT - scroll + delta;
      }
      var newT = Math.min(maxT, Math.max(minT, proposeTop));

      if (this.$side.length) {
        this.$side.css("top", newT);
      }
    }
  }
}

new StickyScroll().runOnReady();
