---
import IconArrowLeft from "@/assets/icons/IconArrowLeft.svg";
import IconArrowNarrowUp from "@/assets/icons/IconArrowNarrowUp.svg";
import { useTranslations } from "@/i18n";

const t = useTranslations(Astro.currentLocale);
---

<div
  id="btt-btn-container"
  class:list={[
    "fixed inset-e-4 bottom-8 z-50",
    "md:sticky md:inset-e-auto md:float-end md:me-1",
    "translate-y-14 opacity-0 transition duration-500",
  ]}
>
  <button
    data-button="back-to-top"
    class:list={[
      "group bg-background relative px-2 py-1",
      "size-14 rounded-full shadow-xl",
      "md:h-8 md:w-fit md:rounded-md md:shadow-none md:focus-visible:rounded-none",
      "md:bg-background/35 md:bg-clip-padding md:backdrop-blur-lg",
    ]}
  >
    <span
      id="progress-indicator"
      class="absolute inset-0 -z-10 block size-14 scale-110 rounded-full bg-transparent md:hidden md:h-8 md:rounded-md"
    ></span>
    <IconArrowLeft class="inline-block rotate-90 md:hidden" />
    <span class="group-hover:text-accent sr-only text-sm md:not-sr-only">
      <IconArrowNarrowUp class="inline-block size-4" />
      {t.post.backToTop}
    </span>
  </button>
</div>

<script is:inline data-astro-rerun>
  function backToTop() {
    const rootElement = document.documentElement;
    const btnContainer = document.querySelector("#btt-btn-container");
    const backToTopBtn = document.querySelector("[data-button='back-to-top']");
    const progressIndicator = document.querySelector("#progress-indicator");

    if (!rootElement || !btnContainer || !backToTopBtn || !progressIndicator)
      return;

    backToTopBtn.addEventListener("click", () => {
      document.body.scrollTop = 0;
      document.documentElement.scrollTop = 0;
    });

    let lastVisible = null;
    function handleScroll() {
      const scrollTotal = rootElement.scrollHeight - rootElement.clientHeight;
      const scrollTop = rootElement.scrollTop;
      const scrollPercent = Math.floor((scrollTop / scrollTotal) * 100);

      progressIndicator.style.setProperty(
        "background-image",
        `conic-gradient(var(--accent), var(--accent) ${scrollPercent}%, transparent ${scrollPercent}%)`
      );

      const isVisible = scrollTop / scrollTotal > 0.3;

      if (isVisible !== lastVisible) {
        btnContainer.classList.toggle("opacity-100", isVisible);
        btnContainer.classList.toggle("translate-y-0", isVisible);
        btnContainer.classList.toggle("opacity-0", !isVisible);
        btnContainer.classList.toggle("translate-y-14", !isVisible);
        lastVisible = isVisible;
      }
    }

    let ticking = false;
    document.addEventListener("scroll", () => {
      if (!ticking) {
        window.requestAnimationFrame(() => {
          handleScroll();
          ticking = false;
        });
        ticking = true;
      }
    });
  }
  backToTop();
</script>
