import { motion } from "framer-motion";
import { useState, useEffect } from "react";

interface TypingTextProps {
  text: string;
  msPerChar?: number; // milliseconds per character
  delayMs?: number; // milliseconds to delay before typing starts
  textAlign?: "left" | "center" | "right"; // text alignment
}

export default function TypingText({ text, msPerChar: speed = 100, delayMs = 0, textAlign = "left" }: TypingTextProps) {
  const [displayedText, setDisplayedText] = useState<string>("");
  const [isComplete, setIsComplete] = useState(false);

  useEffect(() => {
    setDisplayedText("");
    setIsComplete(false);
    let index = 0;
    
    // Set up initial delay timeout
    const delayTimeout = setTimeout(() => {
      const interval = setInterval(() => {
        if (index < text.length) {
          setDisplayedText(text.substring(0, index + 1));
          index++;
          if (index === text.length) {
            setIsComplete(true);
            clearInterval(interval);
          }
        }
      }, speed);

      return () => clearInterval(interval);
    }, delayMs);

    return () => clearTimeout(delayTimeout);
  }, [text, speed, delayMs]);

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.5 }}
      style={{
        whiteSpace: "pre-wrap",
        overflowWrap: "break-word",
        wordWrap: "break-word",
        width: "100%",
        position: "relative",
        textAlign: textAlign
      }}
    >
      {/* Transparent placeholder - reserves space without causing layout shift */}
      <div style={{ color: "transparent", pointerEvents: "none" }}>
        {text}
      </div>
      
      {/* Positioned absolutely over placeholder to show revealed text */}
      <div style={{ 
        position: "absolute", 
        top: 0, 
        left: textAlign === "right" ? "auto" : 0,
        right: textAlign === "right" ? 0 : "auto",
        width: textAlign === "center" ? "100%" : "auto",
        textAlign: textAlign
      }}>
        {displayedText}
        {/* blinking cursor - shows while typing or delaying, hides when complete */}
        {!isComplete && (
          <motion.span
            animate={{ opacity: [0, 1, 0] }}
            transition={{ repeat: Infinity, duration: 1 }}
            style={{
              display: "inline-block",
              width: "4px",
              height: "1em",
              backgroundColor: "currentColor",
              marginLeft: "4px",
              verticalAlign: "middle"
            }}
          />
        )}
      </div>
    </motion.div>
  );
}
