import { useState, useEffect } from "react";
import { EmojiText } from "../chatbot/EmojiText";

interface TypingTextProps {
  text: string;
  speed?: number;
  onTyping?: () => void;
}

export function TypingText({ text, speed = 30, onTyping }: TypingTextProps) {
  const [displayedText, setDisplayedText] = useState("");
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    if (currentIndex < text.length) {
      const timeout = setTimeout(() => {
        setDisplayedText((prev) => prev + text[currentIndex]);
        setCurrentIndex((prev) => prev + 1);
        if (onTyping) {
          onTyping();
        }
      }, speed);

      return () => clearTimeout(timeout);
    }
  }, [currentIndex, text, speed, onTyping]);

  useEffect(() => {
    setDisplayedText("");
    setCurrentIndex(0);
  }, [text]);

  return (
    <p className="text-white text-sm break-words whitespace-pre-wrap">
      <EmojiText text={displayedText} />
      {currentIndex < text.length && (
        <span className="inline-block w-1 h-4 bg-white/70 ml-0.5 animate-pulse" />
      )}
    </p>
  );
}
