import { useSignal } from "@preact/signals";
import { useEffect } from "preact/hooks";
import { LuArrowUp } from "@preact-icons/lu";

export default function ScrollUpButton() {
  const isVisible = useSignal(false);

  useEffect(() => {
    const checkScroll = () => {
      isVisible.value = globalThis.scrollY > 300;
    };

    checkScroll();

    globalThis.addEventListener("scroll", checkScroll);

    return () => {
      globalThis.removeEventListener("scroll", checkScroll);
    };
  }, []);

  const scrollToTop = () => {
    globalThis.scrollTo({
      top: 0,
      behavior: "smooth",
    });
  };

  return (
    <button
      type="button"
      onClick={scrollToTop}
      class={`fixed bottom-20 right-4 z-20 bg-secondary hover:bg-primary
            p-3 rounded-full shadow-lg transition-all duration-300
            ${
        isVisible.value
          ? "opacity-70 translate-y-0"
          : "opacity-0 translate-y-10 pointer-events-none"
      }`}
      aria-label="Scroll to top"
    >
      <LuArrowUp class="text-lg" />
    </button>
  );
}
