(function () {
  const button = document.querySelector(".back-to-top");
  const articlePage = document.querySelector(".article-page");
  const articleBody = document.querySelector(".article-content .body");
  if (!button) return;

  const toggleVisibility = () => {
    button.classList.toggle("is-visible", window.scrollY > 200);
  };

  const syncHorizontalPosition = () => {
    if (!articlePage) return;
    const rightGap = Math.max(0, window.innerWidth - articlePage.getBoundingClientRect().right);
    button.style.setProperty("--back-to-top-right", `${rightGap}px`);
  };

  const makeEmbedsResponsive = () => {
    if (!articleBody) return;

    articleBody.querySelectorAll("iframe").forEach((iframe) => {
      const src = (iframe.getAttribute("src") || "").toLowerCase();
      const isFixedRatioPlayer =
        src.includes("youtube.com") ||
        src.includes("youtube-nocookie.com") ||
        src.includes("m.youtube.com") ||
        src.includes("youtu.be") ||
        src.includes("vimeo.com") ||
        src.includes("player.vimeo.com") ||
        src.includes("dailymotion.com");
      const width = Number(iframe.getAttribute("width"));
      const height = Number(iframe.getAttribute("height"));

      iframe.style.width = "100%";
      iframe.style.maxWidth = "100%";

      if (isFixedRatioPlayer) {
        if (width > 0 && height > 0) {
          iframe.style.aspectRatio = `${width} / ${height}`;
        } else {
          iframe.style.aspectRatio = "16 / 9";
        }
        iframe.style.height = "auto";
      } else {
        iframe.style.removeProperty("aspect-ratio");
        iframe.style.removeProperty("height");
      }
    });
  };

  window.addEventListener("scroll", toggleVisibility, { passive: true });
  window.addEventListener("resize", syncHorizontalPosition);

  toggleVisibility();
  syncHorizontalPosition();
  makeEmbedsResponsive();

  if (articleBody && "MutationObserver" in window) {
    const observer = new MutationObserver(() => {
      makeEmbedsResponsive();
    });
    observer.observe(articleBody, { childList: true, subtree: true });
  }

  button.addEventListener("click", function () {
    window.scrollTo({ top: 0, behavior: "smooth" });
  });
})();
