import { useEffect, useState } from 'react'

export function useScoreReveal(score: number) {
  const [displayScore, setDisplayScore] = useState(0)

  useEffect(() => {
    let cancelled = false
    let raf = 0
    let start: number | null = null
    const duration = 1500

    const tick = (now: number) => {
      if (cancelled) return
      if (start === null) start = now
      const t = Math.min(1, (now - start) / duration)
      const eased = 1 - (1 - t) ** 3
      setDisplayScore(Math.round(score * eased))
      if (t >= 1) {
        if (!cancelled) setDisplayScore(score)
        return
      }
      raf = requestAnimationFrame(tick)
    }

    raf = requestAnimationFrame(tick)
    return () => {
      cancelled = true
      cancelAnimationFrame(raf)
    }
  }, [score])

  const showGrade = displayScore >= score

  return {
    displayScore,
    showGrade,
  }
}
