import { motion, useInView, useSpring } from 'framer-motion';
import { useEffect, useRef, useState } from 'react';

type Props = {
  value: number;
  suffix?: string;
  prefix?: string;
};

export function AnimatedCounter({ value, suffix = '', prefix = '' }: Props) {
  const ref = useRef<HTMLSpanElement>(null);
  const inView = useInView(ref, { once: true, margin: '-10%' });
  const spring = useSpring(0, { stiffness: 80, damping: 22 });
  const [text, setText] = useState(`${prefix}0${suffix}`);

  useEffect(() => {
    if (inView) {
      spring.set(value);
    }
  }, [inView, value, spring]);

  useEffect(() => {
    return spring.on('change', (v) => {
      setText(`${prefix}${Math.round(v).toLocaleString('id-ID')}${suffix}`);
    });
  }, [spring, prefix, suffix]);

  return (
    <span ref={ref} className="tabular-nums">
      <motion.span>{text}</motion.span>
    </span>
  );
}
