import { jsx, jsxs } from 'react/jsx-runtime';
import { useRef, useMemo } from 'react';
import { useReducedMotion, motion } from 'motion/react';
import { tokenTransition, tokenFadeIn } from './StreamingResponse.animations.js';

/**
 * Splits text into tokens (words) preserving whitespace
 */
const tokenize = (text) => {
    if (!text)
        return [];
    // Split on word boundaries, preserving whitespace with each token
    return text.match(/\S+\s*/g) || [];
};
/**
 * AnimatedText renders streaming text with smooth per-token fade-in.
 * For performance, only the last N tokens are animated with motion.span,
 * while older tokens are rendered as static text.
 */
const AnimatedText = ({ text, isStreaming, animateLastN = 12, enabled = true, className, }) => {
    const shouldReduceMotion = useReducedMotion();
    const animate = enabled && !shouldReduceMotion;
    // Track which tokens have already been seen/animated
    const settledCountRef = useRef(0);
    const tokens = useMemo(() => tokenize(text), [text]);
    // Determine how many tokens are "settled" (already animated in)
    // We settle tokens as they age out of the animation window
    if (tokens.length > settledCountRef.current + animateLastN) {
        settledCountRef.current = tokens.length - animateLastN;
    }
    // When streaming stops, settle all tokens
    if (!isStreaming) {
        settledCountRef.current = tokens.length;
    }
    const settledCount = settledCountRef.current;
    const settledText = tokens.slice(0, settledCount).join('');
    const animatedTokens = tokens.slice(settledCount);
    if (!animate || !isStreaming) {
        // No animation: render plain text
        return (jsx("p", { className: className || 'whitespace-pre-wrap wrap-break-word', children: text }));
    }
    return (jsxs("p", { className: className || 'whitespace-pre-wrap wrap-break-word', children: [settledText, animatedTokens.map((token, i) => (jsx(motion.span, { variants: tokenFadeIn, initial: "hidden", animate: "visible", transition: tokenTransition, style: { display: 'inline' }, children: token }, `${settledCount + i}-${token}`)))] }));
};
AnimatedText.displayName = 'AnimatedText';

export { AnimatedText };
