'use client'
// src/components/ui/CounterValue.tsx
// Input: value (target number), digits (decimal places), className
// Output: animated number that ramps from 0 → value in 800ms
// Rationale: used in Stat cards and panels for visual impact at load

import { useEffect, useRef, useState } from 'react'
import { cn } from '@/lib/utils'

export interface CounterValueProps {
  value: number
  digits?: number
  className?: string
  duration?: number
}

export function CounterValue({ value, digits = 0, className, duration = 800 }: CounterValueProps) {
  const [displayed, setDisplayed] = useState(0)
  const rafRef = useRef<number | null>(null)
  const startRef = useRef<number | null>(null)

  useEffect(() => {
    const start = 0
    const end = value

    function step(timestamp: number) {
      if (startRef.current === null) startRef.current = timestamp
      const elapsed = timestamp - startRef.current
      const progress = Math.min(elapsed / duration, 1)
      setDisplayed(start + (end - start) * progress)
      if (progress < 1) {
        rafRef.current = requestAnimationFrame(step)
      }
    }

    rafRef.current = requestAnimationFrame(step)
    return () => {
      if (rafRef.current !== null) cancelAnimationFrame(rafRef.current)
      startRef.current = null
    }
  }, [value, duration])

  const formatted = digits === 0
    ? Math.round(displayed).toLocaleString('fr-FR')
    : displayed.toLocaleString('fr-FR', { minimumFractionDigits: digits, maximumFractionDigits: digits })

  return (
    <span className={cn('font-mono tabular-nums', className)}>
      {formatted}
    </span>
  )
}
