'use client'

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

interface AnimatedCounterProps {
  value: string
  className?: string
}

export default function AnimatedCounter({ value, className = '' }: AnimatedCounterProps) {
  const [display, setDisplay] = useState('0')
  const ref = useRef<HTMLSpanElement>(null)
  const hasAnimated = useRef(false)

  useEffect(() => {
    if (hasAnimated.current) return

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting && !hasAnimated.current) {
          hasAnimated.current = true
          const numericMatch = value.match(/^([\d.]+)/)
          if (!numericMatch) {
            setDisplay(value)
            return
          }
          const target = parseFloat(numericMatch[1])
          const suffix = value.slice(numericMatch[1].length)
          const isFloat = value.includes('.')
          const duration = 1500
          const start = performance.now()

          const animate = (now: number) => {
            const progress = Math.min((now - start) / duration, 1)
            const eased = 1 - Math.pow(1 - progress, 3)
            const current = target * eased
            setDisplay(
              (isFloat ? current.toFixed(1) : Math.floor(current).toLocaleString('de-DE')) + suffix
            )
            if (progress < 1) requestAnimationFrame(animate)
          }
          requestAnimationFrame(animate)
        }
      },
      { threshold: 0.5 }
    )

    if (ref.current) observer.observe(ref.current)
    return () => observer.disconnect()
  }, [value])

  return <span ref={ref} className={className}>{display}</span>
}
