"use client";

import { useEffect, useRef, useState } from "react";
import { animate, useInView } from "framer-motion";

/* Animated counter that counts up to the numeric part of `value` when it
   scrolls into view, preserving any prefix/suffix (e.g. "9+", "∞"). Values
   with no leading number (like "∞") render statically. */
export function CountUp({
  value,
  className,
  duration = 1.6,
}: {
  value: string;
  className?: string;
  duration?: number;
}) {
  const ref = useRef<HTMLSpanElement>(null);
  const inView = useInView(ref, { once: true, margin: "-60px" });
  const match = value.match(/^(\D*)(\d+(?:[.,]\d+)?)(.*)$/);
  const [display, setDisplay] = useState(match ? `${match[1]}0${match[3]}` : value);

  useEffect(() => {
    if (!inView || !match) return;
    const prefix = match[1];
    const target = parseFloat(match[2].replace(",", "."));
    const suffix = match[3];
    const controls = animate(0, target, {
      duration,
      ease: [0.22, 1, 0.36, 1],
      onUpdate: (v) => setDisplay(`${prefix}${Math.round(v)}${suffix}`),
    });
    return () => controls.stop();
  }, [inView, match, duration]);

  return (
    <span ref={ref} className={className}>
      {match ? display : value}
    </span>
  );
}
