import React, { useRef, useEffect, useState } from 'react';
import { gsap, ScrollTrigger } from '../../lib/gsap.ts';
import { useReducedMotion } from '../../hooks/useReducedMotion.ts';

interface CountUpProps {
  value: number;
  suffix?: string;
  label: string;
}

export const CountUp: React.FC<CountUpProps> = ({ value, suffix = '', label }) => {
  const ref = useRef<HTMLDivElement>(null);
  const [display, setDisplay] = useState(0);
  const reduced = useReducedMotion();

  useEffect(() => {
    if (reduced) {
      setDisplay(value);
      return;
    }
    const el = ref.current;
    if (!el) return;

    const ctx = gsap.context(() => {
      gsap.to(
        { val: 0 },
        {
          val: value,
          duration: 2,
          snap: { val: 1 },
          onUpdate: function () {
            setDisplay(Math.round(this.targets()[0].val));
          },
          scrollTrigger: { trigger: el, start: 'top 80%' },
        }
      );
    }, el);

    return () => ctx.revert();
  }, [value, reduced]);

  return (
    <div ref={ref} className="text-center">
      <div className="text-4xl font-bold font-display text-[var(--brand-500)]">
        {display}{suffix}
      </div>
      <div className="text-sm text-[var(--ink-muted)] mt-1">{label}</div>
    </div>
  );
};