(function (global) {
  const app = (global.EpicrisisApp = global.EpicrisisApp || {});

  let observer = null;

  function init() {
    if (!document.body.classList.contains("epicrisis-page")) return;

    const button = document.getElementById("epicrisis_scroll_top_btn");
    const sentinel = document.getElementById("epicrisis_top_sentinel");
    if (!button || !sentinel) return;

    document.body.classList.add("epicrisis-scroll-top-managed");

    if (observer) {
      observer.disconnect();
      observer = null;
    }

    if (!("IntersectionObserver" in global)) {
      button.classList.add("epicrisis-scroll-top--visible");
      return;
    }

    observer = new IntersectionObserver(
      (entries) => {
        const entry = entries[0];
        button.classList.toggle("epicrisis-scroll-top--visible", !entry?.isIntersecting);
      },
      {
        root: null,
        threshold: 0,
      },
    );

    observer.observe(sentinel);
  }

  app.scrollTop = {
    init,
  };
})(globalThis);
