"use client";

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

/* ---------------------------
   Animated Counter Hook
---------------------------- */
function useCountUp(target: number, duration = 2000) {
  const [count, setCount] = useState(0);
  const ref = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;

    let started = false;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting && !started) {
          started = true;
          let start = 0;
          const step = Math.ceil(target / (duration / 16));

          const interval = setInterval(() => {
            start += step;
            if (start >= target) {
              setCount(target);
              clearInterval(interval);
            } else {
              setCount(start);
            }
          }, 16);
        }
      },
      { threshold: 0.5 }
    );

    observer.observe(el);
    return () => observer.disconnect();
  }, [target, duration]);

  return { count, ref };
}

export default function GrowthStats() {
  return (
    <section className="py-10 bg-white">
      <div className="container mx-auto px-4">
        {/* STATS COUNTERS */}
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-4 text-center gap-y-8">
          <Stat label="Growth" value={200} suffix="%" />
          <Stat label="Established" value={2021} />
          <Stat label="Successful Projects" value={100} suffix="+" />
          <Stat label="Users Impacted" value={10} suffix="M+" />
        </div>
      </div>
    </section>
  );
}


/* ---------------------------
   Stat Component
---------------------------- */
function Stat({
  label,
  value,
  suffix = "",
}: {
  label: string;
  value: number;
  suffix?: string;
}) {
  const { count, ref } = useCountUp(value);

  return (
    <div
      ref={ref}
      className="
        px-0 sm:px-5
        border-[#202020]/50
        border-b-0 sm:border-b-0
        lg:border-r
        last:border-0
      "
    >
      <p className="text-md lg:text-lg font-medium text-[#202020]">{label}</p>
      <p className="text-2xl md:text-[48px] font-bold text-[#202020]">
        {count}
        {suffix}
      </p>
    </div>
  );
}
