import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { ArrowUp } from "lucide-react";
import { useTranslation } from "react-i18next";

// A floating "back to top" button that fades in once the current page's scroll container is
// scrolled past a threshold, and smooth-scrolls it back to the top. Every page scrolls inside its
// own <main class="overflow-y-auto"> (the normal pages share App's; the channel page has its own),
// so it targets the live <main> and re-binds whenever `dep` changes (i.e. on navigation). Portaled
// to <body> so its fixed position is viewport-relative regardless of transformed ancestors.
export default function BackToTop({ dep, threshold = 600 }: { dep?: unknown; threshold?: number }) {
  const { t } = useTranslation();
  const [show, setShow] = useState(false);
  const scrollerRef = useRef<HTMLElement | null>(null);

  useEffect(() => {
    const el = document.querySelector("main");
    scrollerRef.current = el;
    if (!el) {
      setShow(false);
      return;
    }
    const onScroll = () => setShow(el.scrollTop > threshold);
    onScroll(); // a freshly-bound page starts at the top → hidden
    el.addEventListener("scroll", onScroll, { passive: true });
    return () => el.removeEventListener("scroll", onScroll);
  }, [dep, threshold]);

  const toTop = () => scrollerRef.current?.scrollTo({ top: 0, behavior: "smooth" });

  // No aria-label/title attributes: ad-block "annoyance" cosmetic filters (e.g. Brave Shields)
  // commonly hide floating corner buttons via attribute selectors like [aria-label="Back to top"].
  // The accessible name comes from a visually-hidden child instead, which those selectors can't match.
  return createPortal(
    <button
      onClick={toTop}
      className={`fixed bottom-5 right-5 z-30 inline-flex items-center justify-center w-11 h-11 rounded-full bg-card border border-border text-fg shadow-lg hover:border-accent hover:text-accent transition-all duration-200 ${
        show ? "opacity-100 translate-y-0" : "opacity-0 translate-y-3 pointer-events-none"
      }`}
    >
      <ArrowUp className="w-5 h-5" aria-hidden="true" />
      <span className="sr-only">{t("common.backToTop")}</span>
    </button>,
    document.body
  );
}
