"use client";

import { ReactNode, useEffect, useRef, useState } from "react";

interface CountBoxProps {
  stop: number;
  speed?: number;
  suffix?: string;
  className?: string;
  children?: ReactNode;
}

export default function CountBox({
  stop,
  speed = 2000,
  suffix = "",
  className = "",
}: CountBoxProps) {
  const [value, setValue] = useState(0);
  const ref = useRef<HTMLDivElement>(null);
  const started = useRef(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && !started.current) {
          started.current = true;
          const startTime = performance.now();
          const tick = (now: number) => {
            const progress = Math.min((now - startTime) / speed, 1);
            setValue(Math.floor(stop * progress));
            if (progress < 1) requestAnimationFrame(tick);
            else setValue(stop);
          };
          requestAnimationFrame(tick);
          observer.disconnect();
        }
      },
      { threshold: 0.2 }
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, [stop, speed]);

  return (
    <div ref={ref} className={className}>
      {value}
      {suffix}
    </div>
  );
}
