import { useEffect, useRef } from 'react';
import { gsap } from 'gsap';
import Container from '../container';
import PrimaryButton from '../primary-button';
import AIParticles from '../ai-particles';
import LightningIcon from '../../icons/lightning-icon';
import TargetIcon from '../../icons/target-icon';
import UsersIcon from '../../icons/users-icon';
import BrainIcon from '../../icons/brain-icon';

export default function AIMidCTA() {
  const sectionRef = useRef<HTMLElement>(null);
  const cardsRef = useRef<HTMLDivElement[]>([]);
  const ctaRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!sectionRef.current) return;

    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          // Cards animation
          gsap.fromTo(cardsRef.current,
            {
              opacity: 0,
              y: 50,
              scale: 0.9
            },
            {
              opacity: 1,
              y: 0,
              scale: 1,
              duration: 0.8,
              stagger: 0.2,
              ease: "back.out(1.7)"
            }
          );

          // CTA animation
          gsap.fromTo(ctaRef.current,
            {
              opacity: 0,
              y: 30,
              scale: 0.95
            },
            {
              opacity: 1,
              y: 0,
              scale: 1,
              duration: 1,
              delay: 0.6,
              ease: "back.out(1.7)"
            }
          );
        }
      },
      { threshold: 0.2 }
    );

    observer.observe(sectionRef.current);
    return () => observer.disconnect();
  }, []);

  const addToRefs = (el: HTMLDivElement) => {
    if (el && !cardsRef.current.includes(el)) {
      cardsRef.current.push(el);
    }
  };

  const aiCapabilities = [
    {
      title: 'Mapa Geolocalizado',
      desc: 'Visualización interactiva de proyectos de innovación educativa con filtros inteligentes',
      icon: <LightningIcon className="w-10 h-10 sm:w-12 sm:h-12" />,
      color: 'bg-emerald-500',
      bgGlow: 'group-hover:shadow-emerald-500/20',
      metric: '17+ proyectos'
    },
    {
      title: 'Análisis IA de Metodologías',
      desc: 'Algoritmos que identifican patrones y sugieren colaboraciones entre investigadores',
      icon: <TargetIcon className="w-10 h-10 sm:w-12 sm:h-12" />,
      color: 'bg-emerald-600',
      bgGlow: 'group-hover:shadow-emerald-600/20',
      metric: 'Conexiones automáticas'
    },
    {
      title: 'Comunidad Colaborativa',
      desc: 'Plataforma para investigadores que facilita el intercambio de metodologías y resultados',
      icon: <UsersIcon className="w-10 h-10 sm:w-12 sm:h-12" />,
      color: 'bg-emerald-700',
      bgGlow: 'group-hover:shadow-emerald-700/20',
      metric: 'Licencia CC'
    }
  ];

  return (
    <section
      ref={sectionRef}
      className="py-16 sm:py-20 lg:py-24 bg-white dark:bg-slate-800 relative overflow-hidden"
    >
      {/* Background Effects */}
      <div className="absolute inset-0">
        <div className="absolute top-1/4 left-1/4 w-64 h-64 sm:w-96 sm:h-96 bg-emerald-500/10 dark:bg-emerald-500/5 rounded-full blur-3xl animate-pulse"></div>
        <div className="absolute bottom-1/4 right-1/4 w-64 h-64 sm:w-96 sm:h-96 bg-emerald-600/10 dark:bg-emerald-600/5 rounded-full blur-3xl animate-pulse"></div>
      </div>

      {/* AI Particles */}
      <AIParticles density={20} />

      <Container className="relative z-10">
        {/* Section Header */}
        <div className="text-center space-y-4 sm:space-y-6 mb-12 sm:mb-16">
          <div className="inline-flex items-center gap-2 sm:gap-3 rounded-full bg-emerald-50 dark:bg-emerald-900/30 px-4 sm:px-6 py-2 sm:py-3 border border-emerald-300 dark:border-emerald-700 backdrop-blur-sm">
            <div className="w-2 h-2 bg-emerald-600 dark:bg-emerald-400 rounded-full animate-pulse"></div>
            <span className="text-emerald-800 dark:text-emerald-300 text-xs sm:text-sm font-semibold">🌍 Tecnología Educativa Avanzada</span>
          </div>

          <h2 className="text-3xl sm:text-4xl md:text-5xl lg:text-6xl font-bold leading-tight">
            <span className="block text-slate-900 dark:text-white mb-2">
              ¿Por qué elegir nuestro
            </span>
            <span className="block text-emerald-700 dark:text-emerald-400">
              Mapa Digital?
            </span>
          </h2>

          <p className="text-slate-700 dark:text-slate-300 text-base sm:text-lg lg:text-xl max-w-3xl mx-auto leading-relaxed px-4 sm:px-0">
            La única plataforma que combina <span className="text-emerald-700 dark:text-emerald-400 font-semibold">visualización interactiva</span> con{' '}
            <span className="text-emerald-800 dark:text-emerald-300 font-semibold">inteligencia artificial</span> para conectar comunidades académicas.
          </p>
        </div>

        {/* AI Capabilities Cards */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 sm:gap-8 mb-12 sm:mb-16">
          {aiCapabilities.map((capability, index) => (
            <div
              key={index}
              ref={addToRefs}
              className={`group relative overflow-hidden text-center space-y-4 sm:space-y-6 p-6 sm:p-8 lg:p-10 rounded-2xl sm:rounded-3xl bg-white/90 dark:bg-slate-800/40 backdrop-blur-sm border border-slate-300 dark:border-slate-700/50 hover:border-emerald-600/70 dark:hover:border-emerald-400/50 transition-all duration-500 hover:scale-105 hover:shadow-2xl ${capability.bgGlow}`}
            >
              {/* Solid background on hover */}
              <div className={`absolute inset-0 ${capability.color} opacity-0 group-hover:opacity-5 transition-opacity duration-500`}></div>

              {/* Content */}
              <div className="relative z-10">
                {/* Icon */}
                <div className="flex justify-center mb-4 sm:mb-6">
                  <div className={`p-4 sm:p-5 rounded-xl ${capability.color} text-white group-hover:scale-110 transition-transform duration-300 shadow-lg`}>
                    {capability.icon}
                  </div>
                </div>

                {/* Text */}
                <div className="space-y-3 sm:space-y-4 mb-4 sm:mb-6">
                  <h3 className="font-bold text-slate-900 dark:text-white text-lg sm:text-xl lg:text-2xl leading-tight">
                    {capability.title}
                  </h3>
                  <p className="text-slate-700 dark:text-slate-400 text-sm sm:text-base leading-relaxed">
                    {capability.desc}
                  </p>
                </div>

                {/* Metric Badge */}
                <div className="inline-flex items-center gap-2 rounded-full bg-emerald-100 dark:bg-emerald-800/30 px-3 sm:px-4 py-2 text-xs sm:text-sm font-bold text-emerald-800 dark:text-emerald-300 border border-emerald-300 dark:border-emerald-700">
                  <div className="w-2 h-2 bg-emerald-600 dark:bg-emerald-400 rounded-full animate-pulse"></div>
                  {capability.metric}
                </div>
              </div>

              {/* Floating indicator */}
              <div className="absolute top-3 right-3 opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                <div className="w-3 h-3 bg-emerald-600 dark:bg-emerald-400 rounded-full animate-ping"></div>
              </div>
            </div>
          ))}
        </div>

        {/* Central CTA */}
        <div
          ref={ctaRef}
          className="text-center space-y-6 sm:space-y-8"
        >
          {/* Main CTA Card */}
          <div className="max-w-4xl mx-auto rounded-3xl lg:rounded-[2rem] bg-white/90 dark:bg-slate-800/50 backdrop-blur-sm border border-emerald-300 dark:border-emerald-700 p-8 sm:p-12 lg:p-16 shadow-2xl hover:shadow-emerald-400/20 transition-all duration-500">

            {/* Map Icon Animation */}
            <div className="flex justify-center mb-6 sm:mb-8">
              <div className="relative">
                <div className="w-16 h-16 sm:w-20 sm:h-20 lg:w-24 lg:h-24 bg-emerald-600 rounded-full flex items-center justify-center text-white text-2xl sm:text-3xl lg:text-4xl animate-pulse">
                  🗺️
                </div>

                {/* Orbiting elements */}
                {[...Array(6)].map((_, i) => (
                  <div
                    key={i}
                    className="absolute w-2 h-2 sm:w-3 sm:h-3 bg-blue-400 rounded-full animate-ping"
                    style={{
                      top: '50%',
                      left: '50%',
                      transform: `translate(-50%, -50%) rotate(${i * 60}deg) translateY(-40px)`,
                      animationDelay: `${i * 0.3}s`
                    }}
                  />
                ))}
              </div>
            </div>

            {/* CTA Text */}
            <div className="space-y-4 sm:space-y-6 mb-8 sm:mb-10">
              <h3 className="text-2xl sm:text-3xl lg:text-4xl font-bold">
                <span className="text-emerald-700 dark:text-emerald-400">
                  ¿Listo para conectar tu proyecto?
                </span>
              </h3>

              <p className="text-slate-700 dark:text-slate-300 text-base sm:text-lg lg:text-xl max-w-2xl mx-auto leading-relaxed">
                Únete a los <span className="text-emerald-700 dark:text-emerald-400 font-semibold">17+ investigadores</span> que ya están
                compartiendo sus metodologías de <span className="text-emerald-800 dark:text-emerald-300 font-semibold">innovación educativa</span>.
              </p>
            </div>

            {/* CTA Button */}
            <div className="flex flex-col sm:flex-row items-center justify-center gap-4 sm:gap-6">
              <PrimaryButton
                href="/register"
                className="text-lg sm:text-xl px-8 sm:px-12 py-4 sm:py-6 bg-gradient-to-r from-emerald-600 to-blue-600 hover:from-emerald-500 hover:to-blue-500 text-white font-bold rounded-2xl shadow-2xl hover:scale-105 transform transition-all duration-300 border-none w-full sm:w-auto"
              >
                <BrainIcon className="w-5 h-5 sm:w-6 sm:h-6" />
                Registrar mi proyecto →
              </PrimaryButton>

              <div className="text-xs sm:text-sm text-slate-600 dark:text-slate-400">
                <span className="flex items-center gap-2 justify-center">
                  <span className="w-2 h-2 bg-emerald-600 dark:bg-emerald-400 rounded-full animate-pulse"></span>
                  Acceso gratuito • Licencia Creative Commons
                </span>
              </div>
            </div>
          </div>

          {/* Trust Indicators */}
          <div className="flex flex-col sm:flex-row items-center justify-center gap-4 sm:gap-8 text-xs sm:text-sm text-slate-700 dark:text-slate-400">
            <span className="flex items-center gap-2">
              <span className="w-2 h-2 bg-emerald-600 dark:bg-emerald-400 rounded-full animate-pulse"></span>
              17+ proyectos de innovación
            </span>
            <span className="flex items-center gap-2">
              <span className="w-2 h-2 bg-blue-600 dark:bg-blue-400 rounded-full animate-pulse"></span>
              Conexión a nivel Latinoamericano
            </span>
            <span className="flex items-center gap-2">
              <span className="w-2 h-2 bg-cyan-600 dark:bg-cyan-400 rounded-full animate-pulse"></span>
              Comunidad académica colaborativa
            </span>
          </div>
        </div>
      </Container>
    </section>
  );
}
