import { useEffect, useRef, useState } from 'react';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

gsap.registerPlugin(ScrollTrigger);

const Stats = () => {
  const sectionRef = useRef<HTMLElement>(null);
  const statsRef = useRef<HTMLDivElement>(null);
  const [counts, setCounts] = useState([0, 0, 0, 0]);

  const stats = [
    { value: 5, suffix: '+', label: 'Years Experience' },
    { value: 50, suffix: '+', label: 'Projects Delivered' },
    { value: 100, suffix: '%', label: 'On-Time Delivery' },
    { value: 24, suffix: '/7', label: 'Support System' },
  ];

  useEffect(() => {
    const ctx = gsap.context(() => {
      // Section entrance
      gsap.fromTo(
        sectionRef.current,
        { opacity: 0 },
        {
          opacity: 1,
          duration: 0.8,
          scrollTrigger: {
            trigger: sectionRef.current,
            start: 'top 80%',
            toggleActions: 'play none none reverse',
          },
        }
      );

      // Stats counter animation
      ScrollTrigger.create({
        trigger: statsRef.current,
        start: 'top 80%',
        onEnter: () => {
          stats.forEach((stat, i) => {
            gsap.to(
              { val: 0 },
              {
                val: stat.value,
                duration: 1.2,
                delay: i * 0.15,
                ease: 'expo.out',
                onUpdate: function () {
                  setCounts((prev) => {
                    const newCounts = [...prev];
                    newCounts[i] = Math.round(this.targets()[0].val);
                    return newCounts;
                  });
                },
              }
            );
          });
        },
        once: true,
      });

      // Stat items entrance
      const statItems = statsRef.current?.querySelectorAll('.stat-item');
      if (statItems) {
        gsap.fromTo(
          statItems,
          {
            rotateX: 90,
            opacity: 0,
          },
          {
            rotateX: 0,
            opacity: 1,
            duration: 0.8,
            stagger: 0.15,
            ease: 'expo.out',
            scrollTrigger: {
              trigger: statsRef.current,
              start: 'top 80%',
              toggleActions: 'play none none reverse',
            },
          }
        );
      }
    }, sectionRef);

    return () => ctx.revert();
  }, []);

  return (
    <section
      ref={sectionRef}
      className="relative py-16 sm:py-20 overflow-hidden"
    >
      {/* Gradient Background */}
      <div className="absolute inset-0 bg-gradient-to-r from-[#3b6aff]/10 via-[#8b5cf6]/10 to-[#06b6d4]/10" />
      
      <div className="relative z-10 section-padding">
        <div className="container-max">
          <div
            ref={statsRef}
            className="grid grid-cols-2 lg:grid-cols-4 gap-8 lg:gap-4"
          >
            {stats.map((stat, i) => (
              <div
                key={i}
                className="stat-item text-center"
                style={{ perspective: '500px' }}
              >
                <div className="relative inline-block">
                  <span className="text-4xl sm:text-5xl lg:text-6xl font-bold text-white font-['Outfit'] text-glow">
                    {counts[i]}{stat.suffix}
                  </span>
                </div>
                <p className="mt-2 text-sm sm:text-base text-[#94a3b8]">
                  {stat.label}
                </p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

export default Stats;
