'use client';

import React, { useEffect, useState } from 'react';
import { useMotionValue, useTransform, animate, useInView, m } from 'framer-motion';

interface AnimatedCounterProps {
  value: number;
  duration?: number;
  delay?: number;
  suffix?: string;
  prefix?: string;
  className?: string;
}

export function AnimatedCounter({
  value,
  duration = 2,
  delay = 0,
  suffix = '',
  prefix = '',
  className = '',
}: AnimatedCounterProps) {
  const count = useMotionValue(0);
  const rounded = useTransform(count, (latest) => {
    // Format with thousands separator
    return new Intl.NumberFormat('de-DE').format(Math.round(latest));
  });

  const ref = React.useRef(null);
  const inView = useInView(ref, { once: true, margin: "-100px" });

  useEffect(() => {
    if (inView) {
      const controls = animate(count, value, {
        duration: duration,
        delay: delay,
        ease: 'easeOut',
      });
      return controls.stop;
    }
  }, [inView, value, duration, delay, count]);

  return (
    <m.span ref={ref} className={className}>
      {prefix}<m.span>{rounded}</m.span>{suffix}
    </m.span>
  );
}
