"use client";

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

type Stat = {
  label: string;
  value: number;
  suffix: string;
  decimals?: number;
};

const STATS: Stat[] = [
  { label: "Vehicles Registered", value: 50000, suffix: "+" },
  { label: "Successful Connections", value: 200000, suffix: "+" },
  { label: "Emergency Alerts Delivered", value: 10000, suffix: "+" },
  { label: "Platform Availability", value: 99.9, suffix: "%", decimals: 1 },
];

function formatValue(n: number, decimals: number) {
  if (decimals > 0) return n.toFixed(decimals);
  return Math.round(n).toLocaleString("en-US");
}

function useCountUp(target: number, start: boolean, duration = 1800) {
  const [value, setValue] = useState(0);
  const frame = useRef<number | null>(null);

  useEffect(() => {
    if (!start) return;
    let startTime: number | null = null;

    const tick = (now: number) => {
      if (startTime === null) startTime = now;
      const progress = Math.min((now - startTime) / duration, 1);
      // easeOutExpo for a snappy finish
      const eased = progress === 1 ? 1 : 1 - Math.pow(2, -10 * progress);
      setValue(target * eased);
      if (progress < 1) frame.current = requestAnimationFrame(tick);
    };

    frame.current = requestAnimationFrame(tick);
    return () => {
      if (frame.current) cancelAnimationFrame(frame.current);
    };
  }, [target, start, duration]);

  return value;
}

function StatCard({ stat, start }: { stat: Stat; start: boolean }) {
  const value = useCountUp(stat.value, start);
  return (
    <div className="glass card-hover rounded-3xl p-7 text-center">
      <p className="font-display text-4xl font-extrabold text-white sm:text-5xl">
        <span className="text-gradient">
          {formatValue(value, stat.decimals ?? 0)}
        </span>
        <span className="text-gradient">{stat.suffix}</span>
      </p>
      <p className="mt-2 text-sm text-white/60">{stat.label}</p>
    </div>
  );
}

export default function Stats() {
  const sectionRef = useRef<HTMLDivElement | null>(null);
  const [start, setStart] = useState(false);

  useEffect(() => {
    const el = sectionRef.current;
    if (!el || typeof IntersectionObserver === "undefined") {
      setStart(true);
      return;
    }
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setStart(true);
          observer.disconnect();
        }
      },
      { threshold: 0.3 }
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  return (
    <section id="stats" className="relative py-20">
      <div
        ref={sectionRef}
        className="mx-auto max-w-7xl px-5 sm:px-8"
      >
        <div className="grid grid-cols-2 gap-5 lg:grid-cols-4">
          {STATS.map((stat) => (
            <StatCard key={stat.label} stat={stat} start={start} />
          ))}
        </div>
      </div>
    </section>
  );
}
