"use client";

import { AnimatePresence, motion } from "framer-motion";
import { useEffect, useState } from "react";

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

	// 1. Logic to show/hide the button based on scroll position
	useEffect(() => {
		const toggleVisibility = () => {
			// Show button when page is scrolled down 300px
			if (window.scrollY > 300) {
				setIsVisible(true);
			} else {
				setIsVisible(false);
			}
		};

		window.addEventListener("scroll", toggleVisibility);

		// Clean up the event listener on component unmount
		return () => window.removeEventListener("scroll", toggleVisibility);
	}, []);

	// 2. Function to scroll to the top smoothly
	const scrollToTop = () => {
		window.scrollTo({
			top: 0,
			behavior: "smooth",
		});
	};

	return (
		// AnimatePresence allows the component to animate out when removed from the DOM
		<AnimatePresence>
			{isVisible && (
				<motion.button
					animate={{ opacity: 1, scale: 1, y: 0 }}
					// Animation states
					aria-label="Scroll to top"
					className="fixed right-8 bottom-4 z-50 flex size-12 cursor-pointer items-center justify-center rounded-full bg-primary text-white shadow-lg transition-colors hover:bg-primary-dark focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2"
					exit={{ opacity: 0, scale: 0.5, y: 20 }}
					initial={{ opacity: 0, scale: 0.5, y: 20 }}
					// Tailwind styling
					onClick={scrollToTop}
					transition={{ duration: 0.3 }}
				>
					{/* Simple SVG Arrow Icon */}
					<svg
						className="h-6 w-6"
						fill="none"
						stroke="currentColor"
						strokeWidth={2.5}
						viewBox="0 0 24 24"
						xmlns="http://www.w3.org/2000/svg"
					>
						<title>Scroll to top</title>
						<path
							d="M4.5 15.75l7.5-7.5 7.5 7.5"
							strokeLinecap="round"
							strokeLinejoin="round"
						/>
					</svg>
				</motion.button>
			)}
		</AnimatePresence>
	);
}
