/**
 * Animated Label Component
 * 
 * Shows typewriter animation when field is focused.
 * The label text changes dynamically with a typing effect.
 */

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

interface AnimatedLabelProps {
  /** Default label text */
  defaultText: string
  /** Text to show when focused */
  focusText?: string
  /** Whether the field is currently focused */
  isFocused: boolean
  /** Whether the field is required */
  isRequired?: boolean
  /** Animation speed in ms per character */
  speed?: number
  /** Show typing cursor */
  showCursor?: boolean
  /** Custom required asterisk color */
  requiredColor?: string
  /** Custom cursor color */
  cursorColor?: string
  /** Custom class name */
  className?: string
}

export function AnimatedLabel({
  defaultText,
  focusText,
  isFocused,
  isRequired = false,
  speed = 30,
  showCursor = true,
  requiredColor,
  cursorColor,
  className = '',
}: AnimatedLabelProps) {
  const [displayText, setDisplayText] = useState(defaultText)
  const [isTyping, setIsTyping] = useState(false)

  useEffect(() => {
    // If no focus text, just use default
    if (!focusText) {
      setDisplayText(defaultText)
      return
    }

    if (isFocused && focusText !== displayText) {
      // Start typing animation to focus text
      setIsTyping(true)
      const targetText = focusText
      let index = 0

      // First, quickly clear current text
      setDisplayText('')

      const typingInterval = setInterval(() => {
        if (index < targetText.length) {
          setDisplayText(targetText.slice(0, index + 1))
          index++
        } else {
          clearInterval(typingInterval)
          setIsTyping(false)
        }
      }, speed)

      return () => clearInterval(typingInterval)
    } else if (!isFocused && displayText !== defaultText) {
      // Instantly revert to default when losing focus
      setDisplayText(defaultText)
      setIsTyping(false)
    }
  }, [isFocused, focusText, defaultText, speed])

  return (
    <span className={`inline-flex items-center gap-1 ${className}`}>
      <span className="transition-all duration-200">
        {displayText}
      </span>
      
      {/* Required asterisk */}
      {isRequired && (
        <span className="mr-0.5" style={{ color: requiredColor || '#EF4444' }}>*</span>
      )}
      
      {/* Typing cursor */}
      {isTyping && showCursor && (
        <motion.span
          className="inline-block w-0.5 h-4 mr-0.5"
          style={{ backgroundColor: cursorColor || '#3BC2D0' }}
          animate={{ opacity: [1, 0] }}
          transition={{ 
            duration: 0.5, 
            repeat: Infinity,
            repeatType: 'reverse'
          }}
        />
      )}
    </span>
  )
}

export default AnimatedLabel








