'use client'

import { useEffect, useRef } from 'react'
import { useInView, animate } from 'framer-motion'

type Props = {
  value: number
  duration?: number
  suffix?: string
}

export function AnimatedCounter({ value, duration = 2, suffix = '' }: Props) {
  const ref = useRef<HTMLSpanElement>(null)
  const inView = useInView(ref, { once: true, margin: '-50px' })

  useEffect(() => {
    if (inView && ref.current) {
      animate(0, value, {
        duration,
        ease: 'easeOut',
        onUpdate: (latest) => {
          if (ref.current) {
            ref.current.textContent = Math.floor(latest).toString() + suffix
          }
        },
      })
    }
  }, [inView, value, duration, suffix])

  return <span ref={ref}>0{suffix}</span>
}
