import animationData from "@assets/lottie/moments/football/bouncingBall.json";
import { twMerge } from "@utils/tailwindMerge";
import { useEffect, useRef, useState } from "react";
import Lottie from "react-lottie";

const lottieOptions = {
	loop: false,
	autoplay: true,
	animationData,
	renderSettings: {
		preserveAspectRatio: "xMidyMid slice",
	},
};

export const BouncingBall = ({ classNames }: { classNames?: string }) => {
	const [key, setKey] = useState(0);
	const [shouldPlay, setShouldPlay] = useState(false);
	const intervalRef = useRef<number | null>(null);
	const timeoutRef = useRef<number | null>(null);

	useEffect(() => {
		// Initial delay of 10 seconds before first animation
		timeoutRef.current = setTimeout(() => {
			setShouldPlay(true);
			setKey(1); // Start the first animation

			// Set up interval for subsequent animations every 10 seconds
			intervalRef.current = setInterval(() => {
				setKey((prev) => prev + 1);
			}, 10000);
		}, 10000);

		return () => {
			if (timeoutRef.current) {
				clearTimeout(timeoutRef.current);
			}
			if (intervalRef.current) {
				clearInterval(intervalRef.current);
			}
		};
	}, []);

	const style = twMerge(
		"bn-absolute bn-w-full bn-h[55px] bn-top-0 bn-left-0 bn-pointer-events-none",
		classNames,
	);

	return (
		<div className={style}>
			{shouldPlay && (
				<Lottie key={key} options={lottieOptions} isClickToPauseDisabled />
			)}
		</div>
	);
};
