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

export const RotatingText = ({
	texts,
}: {
	texts: { id: number; text: string }[];
}) => {
	const [textIndex, setTextIndex] = useState<number>(0);

	useEffect(() => {
		setTextIndex(0);

		if (texts?.length > 1) {
			const timeout = setInterval(() => {
				setTextIndex((prevIndex) => {
					return prevIndex === texts.length - 1 ? 0 : prevIndex + 1;
				});
			}, 5000);

			return () => clearInterval(timeout);
		}
	}, [texts]);

	if (texts?.length === 1) {
		return (
			<p className="bn-font-normal bn-text-sm bn-text-center bn-text-secondary">
				{texts[textIndex]?.text}
			</p>
		);
	}

	return (
		<AnimatePresence mode="wait">
			<motion.p
				key={texts[textIndex].id}
				initial={{
					opacity: 0,
					y: 10,
				}}
				animate={{
					opacity: 1,
					y: 0,
				}}
				exit={{
					opacity: 0,
				}}
				className="bn-font-normal bn-text-sm bn-text-center bn-text-secondary"
			>
				{texts[textIndex]?.text}
			</motion.p>
		</AnimatePresence>
	);
};
