"use client";
import { useEffect, useState } from "react";
import { ChevronUp } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";

export function BackToTop() {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const onScroll = () => setVisible(window.scrollY > 400);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <AnimatePresence>
      {visible && (
        <motion.button
          initial={{ opacity: 0, y: 20, scale: 0.8 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          exit={{ opacity: 0, y: 20, scale: 0.8 }}
          transition={{ duration: 0.25, ease: "easeOut" }}
          whileHover={{ scale: 1.12 }}
          whileTap={{ scale: 0.9 }}
          onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
          className="fixed bottom-24 md:bottom-8 right-5 z-50 w-11 h-11 rounded-full flex items-center justify-center shadow-[0_0_24px_rgba(224,90,104,0.5)] border border-[#e05a68]/40"
          style={{ background: "linear-gradient(135deg, #e05a68, #c93f52)" }}
          aria-label="Retour en haut"
        >
          <ChevronUp size={20} className="text-white" strokeWidth={3} />
        </motion.button>
      )}
    </AnimatePresence>
  );
}
