import { useEffect, useRef, useState } from 'react';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { Globe } from 'lucide-react';
import { LANDING_ICON_PRIMARY } from './landing-constants';

gsap.registerPlugin(ScrollTrigger);

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

const stats: StatItem[] = [
  { value: 25, suffix: '+', label: 'years of expertise in institutional investment technology' },
  { value: 80, suffix: '%', label: 'of the top 20 investment consultants rely on us' },
  { value: 50, suffix: '', label: 'of the top 100 asset managers use our data and analytics' },
];

// Odometer counter component
function OdometerCounter({ 
  value, 
  suffix, 
  prefix = '',
  duration = 2 
}: { 
  value: number; 
  suffix: string; 
  prefix?: string;
  duration?: number;
}) {
  const [displayValue, setDisplayValue] = useState(0);
  const hasAnimated = useRef(false);
  const counterRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting && !hasAnimated.current) {
            hasAnimated.current = true;
            
            // Animate counter
            const startTime = Date.now();
            const startValue = 0;
            const endValue = value;
            
            const animate = () => {
              const elapsed = (Date.now() - startTime) / 1000;
              const progress = Math.min(elapsed / duration, 1);
              
              // Easing function for smooth animation
              const easeOutQuart = 1 - Math.pow(1 - progress, 4);
              const currentValue = Math.floor(startValue + (endValue - startValue) * easeOutQuart);
              
              setDisplayValue(currentValue);
              
              if (progress < 1) {
                requestAnimationFrame(animate);
              } else {
                setDisplayValue(endValue);
              }
            };
            
            animate();
          }
        });
      },
      { threshold: 0.5 }
    );

    if (counterRef.current) {
      observer.observe(counterRef.current);
    }

    return () => {
      if (counterRef.current) {
        observer.unobserve(counterRef.current);
      }
    };
  }, [value, duration]);

  return (
    <div ref={counterRef} className="flex items-baseline justify-center gap-1">
      {prefix && <span className="text-5xl lg:text-6xl font-bold text-[#0a0a0a]">{prefix}</span>}
      <span className={`text-5xl lg:text-6xl font-heading font-bold tabular-nums ${LANDING_ICON_PRIMARY}`}>
        {displayValue}
      </span>
      {suffix && <span className="text-5xl lg:text-6xl font-bold text-[#0a0a0a]">{suffix}</span>}
    </div>
  );
}

export default function Stats() {
  const sectionRef = useRef<HTMLElement>(null);
  const contentRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const ctx = gsap.context(() => {
      gsap.fromTo(
        contentRef.current,
        { y: 32, opacity: 0 },
        {
          y: 0,
          opacity: 1,
          duration: 0.8,
          ease: 'power3.out',
          scrollTrigger: { trigger: sectionRef.current, start: 'top 82%' },
        }
      );
      gsap.utils.toArray<HTMLElement>('.stats-item').forEach((el, i) => {
        gsap.fromTo(
          el,
          { y: 24, opacity: 0 },
          {
            y: 0,
            opacity: 1,
            duration: 0.6,
            ease: 'power2.out',
            scrollTrigger: { trigger: el, start: 'top 88%' },
            delay: i * 0.12,
          }
        );
      });
    }, sectionRef);

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

  return (
    <section
      ref={sectionRef}
      className="relative py-12 lg:py-16 bg-white overflow-hidden border-t border-slate-200/80"
    >
      <div className="landing-container relative z-10">
        <div ref={contentRef} className="text-center">
          <div className="flex items-center justify-center gap-2 mb-3">
            <Globe size={18} className={LANDING_ICON_PRIMARY} aria-hidden />
            <p className="landing-section-eyebrow">[ Worldwide ]</p>
          </div>
          <h2 className="landing-section-title mb-8 lg:mb-10">
            Trusted By Institutional Investors And Advisors Worldwide
          </h2>

          <div className="grid md:grid-cols-3 gap-8 lg:gap-10">
            {stats.map((stat, index) => (
              <div
                key={index}
                className="stats-item flex flex-col items-center"
              >
                <OdometerCounter
                  value={stat.value}
                  suffix={stat.suffix}
                  prefix={stat.prefix}
                  duration={2.5}
                />
                <p className="mt-3 text-base lg:text-lg text-slate-600 max-w-xs text-center leading-relaxed">
                  {stat.label}
                </p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}
