import React, { useState, useEffect, useRef } from 'react';
import { motion } from 'framer-motion';

interface TypewriterTextProps {
  text: string;
  stableId: string;
}

export const TypewriterText: React.FC<TypewriterTextProps> = ({ text, stableId }) => {
  const [displayState, setDisplayState] = useState({
    displayText: '',
    isTyping: false,
    isComplete: false
  });
  
  const animationRef = useRef<NodeJS.Timeout | null>(null);
  
  // 重置动画的函数
  const startTypingAnimation = () => {
    if (!text || !stableId) {
      return;
    }
    
    // 清除现有的动画
    if (animationRef.current) {
      clearTimeout(animationRef.current);
    }
    
    setDisplayState({
      displayText: '',
      isTyping: true,
      isComplete: false
    });
    
    let currentIndex = 0;
    
    const typeNextChar = () => {
      let addRandom = Math.floor(Math.random() * 10);
      if (currentIndex < text.length) {
        const newText = text.slice(0, currentIndex + addRandom);
        setDisplayState({
          displayText: newText,
          isTyping: true,
          isComplete: false
        });
        currentIndex += addRandom;
        animationRef.current = setTimeout(typeNextChar, 100);
      } else {
        setDisplayState({
          displayText: text,
          isTyping: false,
          isComplete: true
        });
      }
    };
    
    animationRef.current = setTimeout(typeNextChar, 100);
  };
  
  // 当 text 或 stableId 变化时重新开始动画
  useEffect(() => {
    startTypingAnimation();
    
    return () => {
      if (animationRef.current) {
        clearTimeout(animationRef.current);
      }
    };
  }, [text, stableId]);
  
  // 如果没有文本，直接返回 null
  if (!text) {
    return null;
  }
  
  return (
    <span className="relative inline-block">
      {displayState.displayText}
      {displayState.isTyping && (
        <motion.span
          className="inline-block w-0.5 h-4 bg-current ml-1 align-middle"
          animate={{ opacity: [0, 1, 0] }}
          transition={{ duration: 0.8, repeat: Infinity }}
        />
      )}
    </span>
  );
}; 