import { useEffect, useState } from 'react'

const chars = "!<>-_\\/[]{}—=+*^?#________"

export default function GlitchText({ text, interval = 30 }) {
  const [displayText, setDisplayText] = useState(text)
  
  useEffect(() => {
    let timeout
    let frame = 0
    let queue = []
    
    const resolveQueue = () => {
      if (queue.length > 0) {
        setDisplayText(queue.shift())
      }
    }
    
    const glitch = () => {
      const iterations = Math.floor(Math.random() * 5) + 3
      
      for (let i = 0; i < iterations; i++) {
        const start = Math.floor(Math.random() * text.length)
        const end = start + Math.floor(Math.random() * 6)
        queue.push(
          text.substring(0, start) + 
          chars[Math.floor(Math.random() * chars.length)] + 
          text.substring(start + 1)
        )
      }
      
      queue.push(text)
      timeout = setTimeout(resolveQueue, interval)
      frame = requestAnimationFrame(glitch)
    }
    
    glitch()
    return () => {
      cancelAnimationFrame(frame)
      clearTimeout(timeout)
    }
  }, [text, interval])

  return <span className="glitch-text">{displayText}</span>
}