"use client";

import { useEffect, useState } from "react";

/** Floating "back to top" button, shown after the visitor has scrolled down. */
export function ScrollTop({ background, icon, radius, position, label }: { background: string; icon: string; radius: number; position: "left" | "right"; label: string }) {
  const [show, setShow] = useState(false);
  useEffect(() => {
    const on = () => setShow(window.scrollY > 400);
    on();
    window.addEventListener("scroll", on, { passive: true });
    return () => window.removeEventListener("scroll", on);
  }, []);
  if (!show) return null;
  return (
    <button
      type="button"
      aria-label={label}
      onClick={() => window.scrollTo({ top: 0, behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" })}
      style={{ background, color: icon, borderRadius: radius, [position]: 16 }}
      className="fixed bottom-4 z-40 inline-flex size-11 items-center justify-center text-xl shadow-lg"
    >
      <span aria-hidden>↑</span>
    </button>
  );
}
