import { ArrowUp } from "lucide-react";
import { Button } from "./button";
import { useEffect, useState } from "react";

export default function BackToTop() {
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    const toggleVisibility = () => {
      if (window.scrollY > 300) {
        setIsVisible(true);
      } else {
        setIsVisible(false);
      }
    };

    window.addEventListener("scroll", toggleVisibility);
    return () => window.removeEventListener("scroll", toggleVisibility);
  }, []);

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

  return (
    <div
      className={`fixed bottom-8 right-8 z-50 transition-all duration-300 ${
        isVisible
          ? "translate-y-0 opacity-100"
          : "translate-y-4 opacity-0 pointer-events-none"
      }`}
    >
      <Button
        size="icon"
        onClick={scrollToTop}
        className="rounded-full shadow-lg bg-primary/90 backdrop-blur-sm border border-border/50 hover:bg-primary hover:shadow-xl hover:-translate-y-1 transition-all h-10 w-10"
      >
        <ArrowUp className="h-5 w-5 text-primary-foreground" />
        <span className="sr-only">Back to top</span>
      </Button>
    </div>
  );
}
