"use client";

import { useRef, useEffect } from "react";
import { motion } from "framer-motion";
import { useInView } from "framer-motion";

interface StatItem {
  value: string;
  label: string;
  prefix?: string;
  suffix?: string;
  decimal?: boolean;
}

interface AnimatedStatsProps {
  stats: StatItem[];
  className?: string;
  locale?: "en" | "ar";
}

export function AnimatedStats({ stats, className = "", locale = "en" }: AnimatedStatsProps) {
  const ref = useRef(null);
  const isInView = useInView(ref, { once: true, margin: "0px" });

  return (
    <div ref={ref} className={`flex flex-wrap gap-6 md:gap-8 ${className}`} dir={locale === "ar" ? "rtl" : "ltr"}>
      {stats.map((stat, index) => (
        <motion.div
          key={index}
          initial={{ opacity: 0, scale: 0.9 }}
          animate={isInView ? { opacity: 1, scale: 1 } : { opacity: 0, scale: 0.9 }}
          transition={{ delay: index * 0.1, duration: 0.5 }}
          className="text-center"
        >
          <div className="font-space-grotesk text-2xl md:text-3xl lg:text-4xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-electric-cyan to-soft-emerald">
            <AnimatedValue
              value={stat.value}
              prefix={stat.prefix}
              suffix={stat.suffix}
              decimal={stat.decimal}
              isInView={isInView}
            />
          </div>
          <div className="text-xs md:text-sm text-muted-white mt-1">{stat.label}</div>
        </motion.div>
      ))}
    </div>
  );
}

interface AnimatedValueProps {
  value: string;
  prefix?: string;
  suffix?: string;
  decimal?: boolean;
  isInView: boolean;
}

function AnimatedValue({ value, prefix = "", suffix = "", decimal = false, isInView }: AnimatedValueProps) {
  const displayRef = useRef<HTMLSpanElement>(null);
  const hasAnimated = useRef(false);

  useEffect(() => {
    if (!isInView || hasAnimated.current) return;

    const numericValue = parseFloat(value.replace(/[^0-9.]/g, ""));
    const duration = 2000;
    const startTime = performance.now();
    const hasSuffix = value.includes("%") || value.includes("x") || value.includes("+");

    hasAnimated.current = true;

    const animate = (currentTime: number) => {
      const elapsed = currentTime - startTime;
      const progress = Math.min(elapsed / duration, 1);

      // Easing function for smooth animation
      const easeOut = 1 - Math.pow(1 - progress, 3);
      const current = numericValue * easeOut;

      if (displayRef.current) {
        if (decimal) {
          displayRef.current.textContent = `${prefix}${current.toFixed(1)}${suffix}${hasSuffix ? value.replace(/[^%x+]/g, "") : ""}`;
        } else {
          displayRef.current.textContent = `${prefix}${Math.round(current)}${suffix}${hasSuffix ? value.replace(/[^%x+]/g, "") : ""}`;
        }
      }

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

    requestAnimationFrame(animate);
  }, [isInView, value, prefix, suffix, decimal]);

  return <span ref={displayRef}>{value}</span>;
}
