"use client"

import { useEffect, useRef, useState } from "react"

function easeOut(t: number): number {
	return 1 - Math.pow(1 - t, 3)
}

export function useCountUp(target: number, duration = 600): number {
	const [value, setValue] = useState(0)
	const prevTargetRef = useRef(target)

	useEffect(() => {
		const from = prevTargetRef.current
		prevTargetRef.current = target

		if (target === from) {
			setValue(target)
			return
		}

		let start: number | null = null
		let rafId: number

		const step = (timestamp: number) => {
			if (start === null) start = timestamp
			const elapsed = timestamp - start
			const progress = Math.min(elapsed / duration, 1)
			setValue(Math.round(from + easeOut(progress) * (target - from)))

			if (progress < 1) {
				rafId = requestAnimationFrame(step)
			}
		}

		rafId = requestAnimationFrame(step)
		return () => cancelAnimationFrame(rafId)
	}, [target, duration])

	return value
}
