import { motion } from "framer-motion";
import { type JSX, useEffect, useState } from "react";
import { useSelector } from "react-redux";

import { ScreenTab } from "@store/globalSlice";
import type { ReduxStateType } from "@store/types";
import { MantleBanner } from "./Banners/Mantle2Banner";

export const CampaignBanners = () => {
	const screenTab = useSelector(
		(state: ReduxStateType) => state.global.screenTab,
	);

	const [currentBanner, setCurrentBanner] = useState(0);
	const banners = [
		<motion.div
			key="gnosis"
			initial={{ x: "100%", opacity: 0 }}
			animate={{ x: 0, opacity: 1 }}
			exit={{ x: "-100%", opacity: 0 }}
			transition={{ duration: 0.5 }}
		>
			<MantleBanner />
		</motion.div>,
	];

	useEffect(() => {
		const interval = setInterval(() => {
			setCurrentBanner((prev) => (prev + 1) % banners.length);
		}, 10000);
		return () => clearInterval(interval);
	}, []);

	if (screenTab !== ScreenTab.HOME) return <></>;

	return (
		<div className="bn-relative">
			<CarouselButtons
				banners={banners}
				currentBanner={currentBanner}
				setCurrentBanner={setCurrentBanner}
			/>
			<div className="bn-h-[142px]">{banners[currentBanner]}</div>
		</div>
	);
};

const CarouselButtons = ({
	banners,
	currentBanner,
	setCurrentBanner,
}: {
	banners: JSX.Element[];
	currentBanner: number;
	setCurrentBanner: React.Dispatch<React.SetStateAction<number>>;
}) => {
	return (
		<div className="bn-flex bn-items-center bn-justify-center bn-mt-2">
			{banners.map((banner, index) => (
				<button
					key={banner.key}
					type="button"
					// biome-ignore format:
					className={`bn-size-2 rounded-full ${
            currentBanner === index ? "bn-bg-theme" : "bn-bg-[#373A3E]"
          } bn-mx-1`}
					onClick={() => setCurrentBanner(index)}
					onKeyUp={(e) => {
						if (e.key === "Enter" || e.key === " ") {
							setCurrentBanner(index);
						}
					}}
					tabIndex={0}
				/>
			))}
		</div>
	);
};
