import { Text } from "@mantine/core";
import { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import classes from "./TextVariator.module.css";

interface TextVariatorProps {
    variants: string[];
    seconds?: number;
}

export function TextVariator(props: TextVariatorProps) {
    const { variants } = props;
    const [currentVariant, setCurrentVariant] = useState(variants[0]);

    useEffect(() => {
        const interval = setInterval(() => {
            setCurrentVariant((prev) => {
                const currentIndex = variants.indexOf(prev);
                const nextIndex = (currentIndex + 1) % variants.length;
                return variants[nextIndex];
            });
        }, props.seconds ? props.seconds : 2 * 1000); // Change variant every 2 seconds if interval not passed

        return () => clearInterval(interval);
    }, [variants]);

    return (
        <AnimatePresence>
            <motion.div
            key={currentVariant}
            initial={{ opacity: 0, y: -20, position: 'absolute' }}
            animate={{ opacity: 1, y: 0, position: 'relative' }}
            exit={{ opacity: 0, y: 20, position: 'absolute' }}
            transition={{ duration: 0.5 }}
            className={classes.slide}
            >
            <Text component="span" variant="gradient" gradient={{ from: 'blue', to: 'cyan' }} inherit>
            {currentVariant}
            </Text>
            </motion.div>
        </AnimatePresence>
    );
}