import { jsx } from 'react/jsx-runtime';
import { useMemo } from 'react';
import { useReducedMotion, motion } from 'motion/react';
import { cn } from '../../../utils/cn.js';
import { useAnimatedContext } from './Animated.js';
import { getAnimationVariants, getExitVariant } from './Animated.animations.js';

const AnimatedItem = ({ animation = 'fadeUp', transition, as = 'div', delay, className, children, ...props }) => {
    const shouldReduceMotion = useReducedMotion();
    const groupContext = useAnimatedContext();
    if (shouldReduceMotion) {
        const Tag = as;
        return (jsx(Tag, { className: className, ...props, children: children }));
    }
    const variants = useMemo(() => getAnimationVariants(animation, transition), [animation, transition]);
    const exitState = useMemo(() => getExitVariant(animation), [animation]);
    const motionProps = {
        variants,
        exit: exitState,
        className: cn(className),
        ...props,
    };
    if (!groupContext) {
        motionProps.initial = 'hidden';
        motionProps.animate = 'visible';
        if (delay != null) {
            motionProps.transition = {
                ...(typeof variants.visible === 'object' && 'transition' in variants.visible
                    ? variants.visible.transition
                    : {}),
                delay,
            };
        }
    }
    const MotionComponent = motion[as];
    return (
    // @ts-expect-error -- polymorphic motion element type mismatch is safe at runtime
    jsx(MotionComponent, { ...motionProps, children: children }));
};

export { AnimatedItem };
