"use client";
import { useRef, useState, useEffect, useCallback } from "react";
import { motion, useInView, useReducedMotion } from "framer-motion";

const containerVariants = {
  hidden: {},
  visible: {
    transition: { staggerChildren: 0.1 },
  },
};

const itemVariants = {
  hidden: { opacity: 0, y: 20 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { type: "spring" as const, stiffness: 120, damping: 20 },
  },
};

/** Extract leading numeric value and surrounding symbols from a stat string like "98%", "30-60%", "<10s", ">40%" */
function parseStatValue(v: string): {
  prefix: string;
  num: number | null;
  suffix: string;
} {
  const match = v.match(/^([<>]?)(\d+)(.*)$/);
  if (match) {
    return { prefix: match[1], num: parseInt(match[2], 10), suffix: match[3] };
  }
  // Non-numeric (e.g. "30-60%") -- treat as non-animatable
  return { prefix: "", num: null, suffix: v };
}

function easeOutQuart(t: number): number {
  return 1 - Math.pow(1 - t, 4);
}

function AnimatedValue({
  value,
  inView,
  reducedMotion,
}: {
  value: string;
  inView: boolean;
  reducedMotion: boolean;
}) {
  const { prefix, num, suffix } = parseStatValue(value);
  const [display, setDisplay] = useState(
    num !== null && !reducedMotion ? 0 : num,
  );
  const hasAnimated = useRef(false);

  const animate = useCallback(() => {
    if (num === null || hasAnimated.current) return;
    hasAnimated.current = true;
    const duration = 2000;
    let start: number | null = null;

    function step(timestamp: number) {
      if (start === null) start = timestamp;
      const elapsed = timestamp - start;
      const progress = Math.min(elapsed / duration, 1);
      const eased = easeOutQuart(progress);
      setDisplay(Math.floor(num! * eased));
      if (progress < 1) {
        requestAnimationFrame(step);
      } else {
        setDisplay(num!);
      }
    }

    requestAnimationFrame(step);
  }, [num]);

  useEffect(() => {
    if (inView && !hasAnimated.current) {
      if (reducedMotion || num === null) {
        setDisplay(num);
        hasAnimated.current = true;
      } else {
        animate();
      }
    }
  }, [inView, reducedMotion, num, animate]);

  if (num === null) {
    // Non-numeric value -- just show it
    return <>{value}</>;
  }

  return (
    <>
      {prefix}
      {display}
      {suffix}
    </>
  );
}

export default function StatBand({ lang }: { lang: "ar" | "en" }) {
  const ref = useRef<HTMLElement>(null);
  const inView = useInView(ref, { once: true, margin: "-40px" });
  const prefersReducedMotion = useReducedMotion();

  const stats =
    lang === "ar"
      ? [
          { v: "98%", l: "معدلات فتح" },
          { v: "30\u201360%", l: "انخفاض عدم الحضور" },
          { v: "<10s", l: "زمن الرد" },
          { v: ">40%", l: "مدفوع مسبقاً" },
        ]
      : [
          { v: "98%", l: "Open rates" },
          { v: "30\u201360%", l: "No-show drop" },
          { v: "<10s", l: "Reply time" },
          { v: ">40%", l: "Prepaid bookings" },
        ];

  return (
    <section
      ref={ref}
      className="bg-brand-green text-white relative overflow-hidden"
    >
      {/* Gradient sweep overlay */}
      <motion.div
        className="absolute inset-0 pointer-events-none"
        style={{
          background:
            "linear-gradient(90deg, transparent 0%, rgba(255,255,255,0.12) 50%, transparent 100%)",
          width: "200%",
        }}
        initial={{ x: "-100%" }}
        animate={
          inView && !prefersReducedMotion ? { x: "100%" } : { x: "-100%" }
        }
        transition={{ duration: 1.8, ease: "easeInOut", delay: 0.3 }}
      />

      <motion.div
        className="max-w-6xl mx-auto grid grid-cols-2 md:grid-cols-4 gap-6 text-center py-10 relative z-10"
        variants={containerVariants}
        initial="hidden"
        animate={inView ? "visible" : "hidden"}
      >
        {stats.map((s) => (
          <motion.div
            key={s.l}
            className="flex flex-col items-center gap-2"
            variants={itemVariants}
          >
            <div className="text-4xl font-bold">
              <AnimatedValue
                value={s.v}
                inView={inView}
                reducedMotion={!!prefersReducedMotion}
              />
            </div>
            <div className="opacity-90">{s.l}</div>
          </motion.div>
        ))}
      </motion.div>
    </section>
  );
}
