import React, { useEffect, useRef, useState } from 'react';
import Box from '@mui/material/Box';
import useMediaQuery from '@mui/material/useMediaQuery';
import { SxProps, useTheme } from '@mui/material/styles';

import './Beta.css';

type BetaProps = {
    adaptive?: boolean;
    onClick?: (event?: React.MouseEvent<HTMLElement>) => void;
    sx?: SxProps;
}

const Beta: React.FC<BetaProps> = (props : BetaProps) => {
    const { onClick, adaptive = true, sx = {} } = props;
    const betaRef = useRef<HTMLElement | null>(null);
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    const [animationKey, setAnimationKey] = useState<number>(0);
    const [firstPass, setFirstPass] = useState<boolean>(true);

    useEffect(() => {
        // Initial animation trigger
        if (firstPass && betaRef.current) {
            triggerAnimation();
            setFirstPass(false);
        }
    }, [firstPass]);
    
    const triggerAnimation = (): void => {
        if (!betaRef.current) return;
        
        // Increment animation key to force React to recreate the element
        setAnimationKey(prevKey => prevKey + 1);
        
        // Ensure the animate class is present
        betaRef.current.classList.add('animate');
    };
    
    return (
        <Box sx={sx} className={`beta-clipper ${adaptive && isMobile && "mobile"}`} onClick={(e) => { onClick && onClick(e); }}>
            <Box ref={betaRef} className={`beta-label ${adaptive && isMobile && "mobile"}`}>
                <Box key={animationKey} className="particles"></Box>
                <Box>BETA</Box>
            </Box>
        </Box>
    );
};

export {
    Beta
};