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

declare interface Win extends Window {
  anchorScrollInitialized: boolean;
  pageScrollOffset: number;
  rootcommerce: any;
  disableAnchorScroll: boolean;
}

declare let window: Win;

export default class Scroll extends InobyModule {
  run() {
    this.disableRcAnchorScroll();
  }

  runAsync() {
    this.initAnchorScroll();
    this.scrollToUrlAnchor();
  }

  disableRcAnchorScroll() {
    if (window.rootcommerce?.App) {
      let rcApp = Object.getPrototypeOf(window.rootcommerce.App);
      rcApp.initAnchorScroll = function () {};
    }
  }

  static scrollTo($target: JQuery<HTMLElement> | string, duration = 500) {
    const $item = typeof $target === "string" ? $($target) : $target;
    if ($item.length > 0) {
      $("html,body").animate(
        {
          scrollTop:
            $item.offset().top -
            (window.pageScrollOffset || $("#header").height()),
        },
        duration
      );
    }
  }

  static disableAnchorScrolling() {
    window.disableAnchorScroll = true;
  }

  static enableAnchorScrolling() {
    window.disableAnchorScroll = false;
  }

  private initAnchorScroll() {
    if (!window.anchorScrollInitialized) {
      $('a[href*="#"]').on("click", function (e) {
        if ($(this).attr("href") === "#" || $(this).hasClass("no-scroll")) {
          return;
        }
        var $href = "#" + $(this).attr("href").split("#")[1];
        var $target = $($href);
        if (
          !window.disableAnchorScroll &&
          $target.length &&
          $target.attr("role") !== "tabpanel"
        ) {
          e.preventDefault();
          Scroll.scrollTo($target);
          window.location = $href;
        }
      });
    }
  }

  private scrollToUrlAnchor() {
    if (location.hash) {
      Scroll.scrollTo(location.hash);
    }
  }
}
