import { useEffect, useState } from 'react'

const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

interface Props {
  text: string
  delay?: number
  className?: string
}

export function HackerText({ text, delay = 0, className }: Props) {
  const [display, setDisplay] = useState(text.replace(/[^ ]/g, () => CHARS[Math.random() * CHARS.length | 0]))
  const [settled, setSettled] = useState(false)

  useEffect(() => {
    let frame = 0
    const maxFrames = text.length * 2
    let timeout: number

    const start = () => {
      const iv = setInterval(() => {
        frame++
        const lockedCount = Math.floor((frame / maxFrames) * text.length)

        setDisplay(
          text.split('').map((ch, i) => {
            if (ch === ' ') return ' '
            if (i < lockedCount) return ch
            return CHARS[Math.random() * CHARS.length | 0]
          }).join('')
        )

        if (lockedCount >= text.length) {
          clearInterval(iv)
          setDisplay(text)
          setSettled(true)
        }
      }, 25)

      return iv
    }

    timeout = window.setTimeout(() => {
      start()
    }, delay)

    return () => {
      clearTimeout(timeout)
    }
  }, [text, delay])

  return <span className={className} data-settled={settled}>{display}</span>
}
