"use client";

import { motion, useInView } from "framer-motion";
import { useRef, useEffect, useState } from "react";
import { useTranslation } from "@/lib/i18n/context";

function CountUp({ target, suffix = "" }: { target: number; suffix?: string }) {
  const [count, setCount] = useState(0);
  const ref = useRef<HTMLSpanElement>(null);
  const inView = useInView(ref, { once: true });

  useEffect(() => {
    if (!inView) return;
    let start = 0;
    const duration = 1800;
    const step = Math.ceil(target / (duration / 16));
    const timer = setInterval(() => {
      start += step;
      if (start >= target) {
        setCount(target);
        clearInterval(timer);
      } else {
        setCount(start);
      }
    }, 16);
    return () => clearInterval(timer);
  }, [inView, target]);

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

const testimonials = [
  {
    name: "Fatima Al-Rashid",
    nameAr: "فاطمة الرشيد",
    role: "Mother of 2",
    roleAr: "أم لطفلين",
    text: "UNIPAM diapers are absolutely amazing! My baby sleeps through the night without any leaks. The soft material is so gentle on sensitive skin.",
    textAr: "حفاضات يونيبام رائعة تماماً! طفلي ينام طوال الليل دون أي تسريب. الخامة الناعمة لطيفة جداً على البشرة الحساسة.",
    stars: 5,
  },
  {
    name: "Ahmed Hassan",
    nameAr: "أحمد حسن",
    role: "Father of 3",
    roleAr: "أب لثلاثة أطفال",
    text: "We switched to UNIPAM and never looked back. The quality is exceptional and the price is very reasonable for premium diapers.",
    textAr: "انتقلنا إلى يونيبام ولم نندم أبداً. الجودة استثنائية والسعر معقول جداً لحفاضات فاخرة.",
    stars: 5,
  },
  {
    name: "Sarah Mohammed",
    nameAr: "سارة محمد",
    role: "Mother & Pediatric Nurse",
    roleAr: "أم وممرضة أطفال",
    text: "As a pediatric nurse, I recommend UNIPAM to all parents. The breathable layers and hypoallergenic materials are perfect for newborns.",
    textAr: "كممرضة أطفال، أنصح جميع الآباء بيونيبام. الطبقات القابلة للتهوية والمواد المضادة للحساسية مثالية لحديثي الولادة.",
    stars: 5,
  },
];

const stats = [
  { value: 10, suffix: "+", labelEn: "Years of Excellence", labelAr: "سنوات من التميز" },
  { value: 15, suffix: "+", labelEn: "Countries Served", labelAr: "دولة نخدمها" },
  { value: 5000000, suffix: "+", labelEn: "Happy Babies", labelAr: "طفل سعيد" },
  { value: 99, suffix: "%", labelEn: "Parent Satisfaction", labelAr: "رضا الوالدين" },
];

const certBadges = [
  { icon: "🏆", labelEn: "ISO 9001 Certified", labelAr: "معتمدة ISO 9001" },
  { icon: "🌿", labelEn: "Eco-Friendly Materials", labelAr: "مواد صديقة للبيئة" },
  { icon: "🔬", labelEn: "Dermatologically Tested", labelAr: "مختبرة جلدياً" },
  { icon: "👶", labelEn: "Pediatrician Approved", labelAr: "معتمدة من أطباء الأطفال" },
];

export function StatsSection() {
  const { dir } = useTranslation();
  const isAr = dir === "rtl";

  return (
    <>
      {/* ── Stats Counter Strip ── */}
      <section className="bg-gradient-to-r from-primary via-primary/90 to-soft-teal py-16" dir={dir}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-8 text-center text-white">
            {stats.map((s, i) => (
              <motion.div
                key={i}
                initial={{ opacity: 0, y: 30 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true }}
                transition={{ duration: 0.5, delay: i * 0.1 }}
                className="flex flex-col items-center"
              >
                <span className="text-4xl md:text-5xl font-black mb-1 drop-shadow">
                  <CountUp target={s.value} suffix={s.suffix} />
                </span>
                <span className="text-sm md:text-base font-semibold text-white/80 uppercase tracking-wider">
                  {isAr ? s.labelAr : s.labelEn}
                </span>
              </motion.div>
            ))}
          </div>
        </div>
      </section>

      {/* ── Trust / Certifications ── */}
      <section className="bg-soft-cream/30 py-12 border-y border-medium-gray/30" dir={dir}>
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex flex-wrap justify-center gap-6 md:gap-10">
            {certBadges.map((b, i) => (
              <motion.div
                key={i}
                initial={{ opacity: 0, scale: 0.8 }}
                whileInView={{ opacity: 1, scale: 1 }}
                viewport={{ once: true }}
                transition={{ duration: 0.4, delay: i * 0.08 }}
                className="flex items-center gap-3 bg-white px-5 py-3 rounded-full shadow-sm border border-medium-gray/20 hover:shadow-md hover:-translate-y-0.5 transition-all"
              >
                <span className="text-2xl">{b.icon}</span>
                <span className="text-sm font-bold text-dark-text/70">{isAr ? b.labelAr : b.labelEn}</span>
              </motion.div>
            ))}
          </div>
        </div>
      </section>

      {/* ── Testimonials ── */}
      <section className="section-padding bg-white" dir={dir}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            className="text-center mb-14"
          >
            <span className="inline-block px-4 py-1.5 mb-4 text-xs font-bold uppercase tracking-widest text-primary bg-primary/10 rounded-full">
              {isAr ? "ماذا يقول عملاؤنا" : "What Parents Say"}
            </span>
            <h2 className="text-3xl md:text-4xl font-black text-dark-text mb-3">
              {isAr ? "قصص نجاح حقيقية" : "Real Success Stories"}
            </h2>
            <p className="text-dark-text/60 max-w-xl mx-auto text-base">
              {isAr
                ? "ثقة الآباء والأمهات حول العالم هي أعظم شهادة لجودة يونيبام."
                : "The trust of parents around the world is the greatest testimony to UNIPAM's quality."}
            </p>
          </motion.div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {testimonials.map((t, i) => (
              <motion.div
                key={i}
                initial={{ opacity: 0, y: 30 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true }}
                transition={{ duration: 0.5, delay: i * 0.12 }}
                className="relative bg-white rounded-3xl p-7 border border-medium-gray/30 shadow-sm hover:shadow-xl hover:-translate-y-1 transition-all duration-300"
              >
                {/* Quote mark */}
                <div className="absolute top-5 end-6 text-6xl leading-none text-primary/10 font-black select-none">"</div>

                {/* Stars */}
                <div className="flex gap-1 mb-4">
                  {Array.from({ length: t.stars }).map((_, s) => (
                    <span key={s} className="text-amber-400 text-lg">★</span>
                  ))}
                </div>

                <p className="text-dark-text/70 text-sm leading-relaxed mb-6 relative z-10">
                  {isAr ? t.textAr : t.text}
                </p>

                <div className="flex items-center gap-3 pt-4 border-t border-medium-gray/20">
                  <div className="w-10 h-10 rounded-full bg-gradient-to-br from-primary to-soft-teal flex items-center justify-center text-white font-black text-sm flex-shrink-0">
                    {(isAr ? t.nameAr : t.name).charAt(0)}
                  </div>
                  <div>
                    <p className="font-bold text-dark-text text-sm">{isAr ? t.nameAr : t.name}</p>
                    <p className="text-xs text-dark-text/50">{isAr ? t.roleAr : t.role}</p>
                  </div>
                </div>
              </motion.div>
            ))}
          </div>
        </div>
      </section>

      {/* ── How It Works ── */}
      <section className="section-padding bg-gradient-to-br from-baby-blue/20 via-soft-cream/30 to-white" dir={dir}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            className="text-center mb-14"
          >
            <span className="inline-block px-4 py-1.5 mb-4 text-xs font-bold uppercase tracking-widest text-primary bg-primary/10 rounded-full">
              {isAr ? "كيف نعمل" : "How It Works"}
            </span>
            <h2 className="text-3xl md:text-4xl font-black text-dark-text mb-3">
              {isAr ? "سهولة الطلب والتوصيل" : "Easy Ordering & Delivery"}
            </h2>
          </motion.div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-8 relative">
            {/* Connector Line (desktop) */}
            <div className="hidden md:block absolute top-10 start-[16.67%] end-[16.67%] h-0.5 bg-gradient-to-r from-primary/20 via-primary to-soft-teal/40" />

            {[
              {
                step: "01",
                icon: "📱",
                titleEn: "Choose Your Size",
                titleAr: "اختر مقاسك",
                descEn: "Browse our range and pick the perfect size for your baby's weight and age.",
                descAr: "تصفح مجموعتنا واختر المقاس المثالي لوزن طفلك وعمره.",
              },
              {
                step: "02",
                icon: "💬",
                titleEn: "Contact via WhatsApp",
                titleAr: "تواصل عبر واتساب",
                descEn: "Send us a quick message on WhatsApp and our team will respond immediately.",
                descAr: "أرسل لنا رسالة سريعة على واتساب وسيرد فريقنا فوراً.",
              },
              {
                step: "03",
                icon: "🚀",
                titleEn: "Fast Delivery",
                titleAr: "توصيل سريع",
                descEn: "Your order is prepared and delivered quickly to your doorstep.",
                descAr: "يتم تجهيز طلبك وتوصيله بسرعة إلى باب منزلك.",
              },
            ].map((item, i) => (
              <motion.div
                key={i}
                initial={{ opacity: 0, y: 30 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true }}
                transition={{ duration: 0.5, delay: i * 0.15 }}
                className="flex flex-col items-center text-center relative"
              >
                <div className="relative mb-6">
                  <div className="w-20 h-20 rounded-2xl bg-white shadow-lg border-2 border-primary/20 flex items-center justify-center text-4xl">
                    {item.icon}
                  </div>
                  <span className="absolute -top-2 -end-2 w-7 h-7 bg-primary text-white text-xs font-black rounded-full flex items-center justify-center">
                    {item.step}
                  </span>
                </div>
                <h3 className="text-lg font-extrabold text-dark-text mb-2">
                  {isAr ? item.titleAr : item.titleEn}
                </h3>
                <p className="text-sm text-dark-text/60 leading-relaxed max-w-xs">
                  {isAr ? item.descAr : item.descEn}
                </p>
              </motion.div>
            ))}
          </div>
        </div>
      </section>
    </>
  );
}
