"use client";

import { useEffect, useRef, useState } from "react";
import { motion, useInView } from "framer-motion";
import { stats } from "@/constants";

function AnimatedNumber({ value, suffix = "" }: { value: number; suffix?: string }) {
  const [displayValue, setDisplayValue] = useState(0);
  const [hasStarted, setHasStarted] = useState(false);
  const ref = useRef<HTMLSpanElement>(null);
  const isInView = useInView(ref, { once: true, margin: "-100px" });

  useEffect(() => {
    if (isInView && !hasStarted) {
      setHasStarted(true);
      const duration = 2000; // 2 seconds
      const steps = 60;
      const stepValue = value / steps;
      let current = 0;

      const timer = setInterval(() => {
        current += stepValue;
        if (current >= value) {
          setDisplayValue(value);
          clearInterval(timer);
        } else {
          setDisplayValue(Math.floor(current));
        }
      }, duration / steps);

      return () => clearInterval(timer);
    }
  }, [isInView, hasStarted, value]);

  return (
    <span ref={ref}>
      {displayValue.toLocaleString()}
      {suffix}
    </span>
  );
}

export default function Stats() {
  return (
    <section aria-label="Impact at a glance" className="relative z-10">
      <motion.div
        className="container-x -mt-16 sm:-mt-20"
        initial={{ opacity: 0, y: 50 }}
        whileInView={{ opacity: 1, y: 0 }}
        viewport={{ once: true, margin: "-100px" }}
        transition={{ duration: 0.8, ease: [0.25, 0.1, 0.25, 1] }}
      >
        <dl className="grid grid-cols-2 gap-px overflow-hidden rounded-2xl bg-navy-100 shadow-card ring-1 ring-navy-100 lg:grid-cols-4">
          {stats.map((stat, index) => {
            // Extract numeric value and suffix
            const numericValue = parseFloat(stat.value.replace(/[^\d.,]/g, "").replace(/,/g, ""));
            const suffix = stat.value.replace(/[\d.,]/g, "");

            return (
              <motion.div
                key={stat.label}
                className="flex flex-col items-center gap-1 bg-white px-6 py-8 text-center sm:py-10"
                initial={{ opacity: 0, y: 20 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true }}
                transition={{
                  duration: 0.6,
                  delay: index * 0.1,
                  ease: [0.25, 0.1, 0.25, 1]
                }}
                whileHover={{
                  y: -4,
                  transition: { duration: 0.2 }
                }}
              >
                <dt className="sr-only">{stat.label}</dt>
                <dd className="text-4xl font-extrabold tracking-tightest text-navy sm:text-5xl">
                  <span className="text-gold">
                    <AnimatedNumber value={numericValue} />
                  </span>
                  <span className="text-navy">{suffix}</span>
                </dd>
                <p className="mt-1 text-sm font-medium text-navy-500">
                  {stat.label}
                </p>
              </motion.div>
            );
          })}
        </dl>
      </motion.div>
    </section>
  );
}
