/**
 * Scroll-to-top button that appears when the user scrolls down.
 *
 * Mirrors the Angular app's scroll-up button behavior.
 *
 * @module
 */

import { type FC, useState, useEffect, useCallback } from "react";
import "./ScrollUpButton.scss";

const SCROLL_THRESHOLD = 300;

export const ScrollUpButton: FC = () => {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      setVisible(window.scrollY > SCROLL_THRESHOLD);
    };

    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  const scrollToTop = useCallback(() => {
    window.scrollTo({ top: 0, behavior: "smooth" });
  }, []);

  if (!visible) return null;

  return (
    <button
      type="button"
      className="scroll-up-button"
      onClick={scrollToTop}
      aria-label="Scroll to top"
      data-testid="scroll-up-button"
    >
      <svg viewBox="0 0 24 24" width="24" height="24">
        <path d="M12 4L4 12H9V20H15V12H20L12 4Z" fill="currentColor" />
      </svg>
    </button>
  );
};
