"use client";

import { useEffect, useRef, useState } from "react";
import { useReducedMotion } from "framer-motion";
import { ShieldCheck, Star, Wrench } from "lucide-react";
import { cn } from "@/lib/utils";

const stats = [
  {
    icon: ShieldCheck,
    value: 10000,
    suffix: "+",
    label: "Vehicles Serviced",
    note: "Doorstep jobs completed for busy vehicle owners",
  },
  {
    icon: Wrench,
    value: 1500,
    suffix: "+",
    label: "Verified Mechanics",
    note: "Trained hands for bikes and cars",
  },
  {
    icon: Star,
    value: 4.8,
    suffix: "/5",
    decimals: 1,
    label: "Customer Rating",
    note: "Based on real service feedback",
  },
];

type TrustStatsSectionProps = {
  className?: string;
};

function CountUpValue({
  value,
  suffix = "",
  decimals = 0,
}: {
  value: number;
  suffix?: string;
  decimals?: number;
}) {
  const ref = useRef<HTMLSpanElement>(null);
  const shouldReduceMotion = useReducedMotion();
  const [displayValue, setDisplayValue] = useState(0);

  useEffect(() => {
    const node = ref.current;

    if (!node || shouldReduceMotion) {
      setDisplayValue(value);
      return;
    }

    let frameId = 0;
    let startTime: number | null = null;
    const duration = 1400;

    const animate = (time: number) => {
      startTime ??= time;
      const progress = Math.min((time - startTime) / duration, 1);
      const easedProgress = 1 - Math.pow(1 - progress, 4);

      setDisplayValue(value * easedProgress);

      if (progress < 1) {
        frameId = requestAnimationFrame(animate);
      }
    };

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (!entry?.isIntersecting) return;
        frameId = requestAnimationFrame(animate);
        observer.disconnect();
      },
      { threshold: 0.2 },
    );

    observer.observe(node);

    return () => {
      observer.disconnect();
      cancelAnimationFrame(frameId);
    };
  }, [shouldReduceMotion, value]);

  const formattedValue = displayValue.toLocaleString("en-IN", {
    maximumFractionDigits: decimals,
    minimumFractionDigits: decimals,
  });

  return (
    <span ref={ref} className="font-bold tracking-tight">
      {formattedValue}
      <span className="ml-0.5 text-primary">{suffix}</span>
    </span>
  );
}

export function TrustStatsSection({ className }: TrustStatsSectionProps) {
  return (
    <section
      data-section="trust-stats"
      className={cn(
        "relative overflow-hidden border-y border-border bg-foreground py-12 font-['Space_Grotesk'] text-background md:py-14 2xl:py-16",
        className,
      )}
    >
      <div className="relative z-10 mx-auto max-w-7xl px-6 lg:px-8">
        <div className="grid overflow-hidden rounded-md border border-background/12 bg-background/[0.06] md:grid-cols-3">
          {stats.map((item) => {
            const IconComponent = item.icon;
            return (
              <div
                key={item.label}
                className={cn(
                  "group relative min-h-[178px] p-5 sm:p-6 lg:p-7",
                  "border-b border-background/12 last:border-b-0 md:border-b-0 md:border-r md:last:border-r-0",
                  "transition-colors duration-300 hover:bg-background/[0.08]",
                )}
              >
                <div className="flex items-center gap-4">
                  <span
                    className={cn(
                      "grid h-12 w-12 shrink-0 place-items-center rounded-md",
                      "border border-primary/25 bg-primary/10 text-primary",
                      "transition-colors duration-300 group-hover:bg-primary group-hover:text-primary-foreground",
                    )}
                  >
                    <IconComponent className="h-5 w-5" />
                  </span>

                  <p className="text-sm font-semibold leading-5 text-background/65">{item.note}</p>
                </div>

                <div className="mt-7">
                  <h3 className="text-4xl font-black leading-none tracking-tight text-background lg:text-5xl">
                    <CountUpValue
                      value={item.value}
                      suffix={item.suffix}
                      decimals={item.decimals}
                    />
                  </h3>

                  <p className="mt-3 text-base font-black uppercase tracking-[0.12em] text-primary">
                    {item.label}
                  </p>
                </div>

                <div className="absolute inset-x-5 bottom-0 h-[3px] scale-x-0 rounded-full bg-primary transition-transform duration-300 group-hover:scale-x-100 sm:inset-x-6 lg:inset-x-7" />
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}
