'use client';

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

interface Props {
  end: number;
  suffix?: string;
  label: string;
  decimals?: number;
  duration?: number;
}

export default function StatsCounter({
  end,
  suffix = '',
  label,
  decimals = 0,
  duration = 2,
}: Props) {
  const ref = useRef<HTMLDivElement>(null);
  const inView = useInView(ref, { once: true, margin: '-40px' });
  const [value, setValue] = useState(0);

  useEffect(() => {
    if (!inView) return;
    const start = 0;
    const startTime = performance.now();

    const tick = (now: number) => {
      const elapsed = (now - startTime) / 1000;
      const progress = Math.min(elapsed / duration, 1);
      // ease out cubic
      const eased = 1 - Math.pow(1 - progress, 3);
      setValue(start + (end - start) * eased);
      if (progress < 1) requestAnimationFrame(tick);
    };

    requestAnimationFrame(tick);
  }, [inView, end, duration]);

  return (
    <motion.div
      ref={ref}
      initial={{ opacity: 0, y: 30 }}
      whileInView={{ opacity: 1, y: 0 }}
      viewport={{ once: true }}
      transition={{ duration: 0.5 }}
      style={{ textAlign: 'center' }}
    >
      <div
        style={{
          fontSize: 48,
          fontWeight: 700,
          color: '#fff',
          lineHeight: 1.2,
        }}
      >
        {value.toFixed(decimals)}
        <span style={{ fontSize: 24, marginLeft: 4 }}>{suffix}</span>
      </div>
      <div
        style={{
          fontSize: 15,
          color: 'rgba(255,255,255,0.6)',
          marginTop: 8,
        }}
      >
        {label}
      </div>
    </motion.div>
  );
}
