import { useEffect, useRef, useState } from 'react';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { Check, Award, Users, Clock } from 'lucide-react';

gsap.registerPlugin(ScrollTrigger);

interface CounterProps {
  end: number;
  suffix?: string;
  prefix?: string;
  duration?: number;
}

const Counter = ({ end, suffix = '', prefix = '', duration = 2 }: CounterProps) => {
  const [count, setCount] = useState(0);
  const counterRef = useRef<HTMLDivElement>(null);
  const hasAnimated = useRef(false);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting && !hasAnimated.current) {
            hasAnimated.current = true;
            let startTime: number;
            const animate = (timestamp: number) => {
              if (!startTime) startTime = timestamp;
              const progress = Math.min((timestamp - startTime) / (duration * 1000), 1);
              setCount(Math.floor(progress * end));
              if (progress < 1) {
                requestAnimationFrame(animate);
              }
            };
            requestAnimationFrame(animate);
          }
        });
      },
      { threshold: 0.5 }
    );

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

    return () => observer.disconnect();
  }, [end, duration]);

  return (
    <div ref={counterRef} className="counter text-4xl md:text-5xl font-black text-[#cbf400]">
      {prefix}{count}{suffix}
    </div>
  );
};

const About = () => {
  const sectionRef = useRef<HTMLDivElement>(null);
  const imageRef = useRef<HTMLDivElement>(null);
  const contentRef = useRef<HTMLDivElement>(null);
  const statsRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const ctx = gsap.context(() => {
      // Image reveal animation
      gsap.fromTo(
        imageRef.current,
        { clipPath: 'circle(0% at 50% 50%)', opacity: 0 },
        {
          clipPath: 'circle(100% at 50% 50%)',
          opacity: 1,
          duration: 1.2,
          ease: 'power3.out',
          scrollTrigger: {
            trigger: imageRef.current,
            start: 'top 80%',
            toggleActions: 'play none none reverse',
          },
        }
      );

      // Content animation
      const contentElements = contentRef.current?.querySelectorAll('.animate-item');
      if (contentElements) {
        gsap.fromTo(
          contentElements,
          { y: 30, opacity: 0 },
          {
            y: 0,
            opacity: 1,
            duration: 0.6,
            stagger: 0.1,
            ease: 'back.out(1.7)',
            scrollTrigger: {
              trigger: contentRef.current,
              start: 'top 80%',
              toggleActions: 'play none none reverse',
            },
          }
        );
      }

      // Stats animation
      gsap.fromTo(
        statsRef.current,
        { y: 50, opacity: 0 },
        {
          y: 0,
          opacity: 1,
          duration: 0.8,
          ease: 'expo.out',
          scrollTrigger: {
            trigger: statsRef.current,
            start: 'top 85%',
            toggleActions: 'play none none reverse',
          },
        }
      );
    }, sectionRef);

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

  const differentials = [
    'Atendimento personalizado e próximo',
    'Equipe certificada e especializada',
    'SLA garantido em todos os serviços',
    'Tecnologia de ponta sempre atualizada',
    'Relatórios detalhados e transparentes',
    'Foco em resultados e produtividade',
  ];

  return (
    <section
      id="about"
      ref={sectionRef}
      className="section-padding bg-[#1a1a1a] relative overflow-hidden"
    >
      {/* Background decoration */}
      <div className="absolute top-1/2 left-0 w-[600px] h-[600px] bg-[#cbf400]/5 rounded-full blur-3xl -translate-y-1/2 -translate-x-1/2" />

      <div className="container-custom relative z-10">
        <div className="grid lg:grid-cols-2 gap-12 lg:gap-20 items-center">
          {/* Image */}
          <div ref={imageRef} className="relative">
            <div className="relative rounded-2xl overflow-hidden shadow-2xl border border-white/5">
              <img
                src="/about-image.jpg"
                alt="Equipe Avanzato"
                className="w-full h-auto object-cover"
              />
              
              {/* Glassmorphism overlay card */}
              <div className="absolute bottom-6 left-6 right-6 glass rounded-xl p-6 border border-[#cbf400]/20">
                <div className="flex items-center gap-4">
                  <div className="w-14 h-14 rounded-full bg-[#cbf400]/20 flex items-center justify-center border border-[#cbf400]/30">
                    <Award className="w-7 h-7 text-[#cbf400]" />
                  </div>
                  <div>
                    <div className="text-white font-bold text-lg">+23 anos</div>
                    <div className="text-gray-400 text-sm">de experiência no mercado</div>
                  </div>
                </div>
              </div>
            </div>

            {/* Decorative elements */}
            <div className="absolute -top-4 -right-4 w-24 h-24 border-2 border-[#cbf400]/20 rounded-xl" />
            <div className="absolute -bottom-4 -left-4 w-32 h-32 bg-[#cbf400]/10 rounded-xl -z-10" />
          </div>

          {/* Content */}
          <div ref={contentRef}>
            <span className="animate-item inline-block px-4 py-2 rounded-full bg-[#cbf400]/10 text-[#cbf400] text-sm font-semibold mb-4 border border-[#cbf400]/20">
              Sobre a Avanzato
            </span>

            <h2 className="animate-item text-3xl md:text-4xl lg:text-5xl font-black text-white mb-6">
              Por que escolher a{' '}
              <span className="text-gradient">Avanzato?</span>
            </h2>

            <p className="animate-item text-gray-400 text-lg mb-6 leading-relaxed">
              Com mais de 23 anos de experiência, somos o parceiro estratégico que sua empresa 
              precisa para navegar na transformação digital. Não vendemos tecnologia, 
              <strong className="text-white"> entregamos resultados</strong>.
            </p>

            <p className="animate-item text-gray-400 mb-8 leading-relaxed">
              Nossa missão é capacitar empresas de todos os tamanhos a alcançar seus objetivos, 
              assegurando que a TI seja uma aliada estratégica. Permitimos que nossos clientes 
              se concentrem no que fazem de melhor - conduzir seus negócios com sucesso.
            </p>

            {/* Differentials */}
            <div className="animate-item grid sm:grid-cols-2 gap-3 mb-8">
              {differentials.map((item, index) => (
                <div key={index} className="flex items-start gap-3">
                  <div className="w-5 h-5 rounded-full bg-[#cbf400]/10 flex items-center justify-center flex-shrink-0 mt-0.5 border border-[#cbf400]/30">
                    <Check className="w-3 h-3 text-[#cbf400]" />
                  </div>
                  <span className="text-sm text-gray-300">{item}</span>
                </div>
              ))}
            </div>

            {/* CTA */}
            <a
              href="https://api.whatsapp.com/send?phone=551148101704&text=Olá!%20Gostaria%20de%20conhecer%20mais%20sobre%20a%20Avanzato"
              target="_blank"
              rel="noopener noreferrer"
              className="animate-item btn-primary inline-flex items-center gap-2"
            >
              Conheça nossa história
            </a>
          </div>
        </div>

        {/* Stats */}
        <div
          ref={statsRef}
          className="grid grid-cols-2 md:grid-cols-4 gap-6 mt-20 pt-12 border-t border-white/10"
        >
          <div className="text-center">
            <Counter end={500} suffix="+" />
            <div className="flex items-center justify-center gap-2 mt-2 text-gray-500">
              <Users className="w-4 h-4" />
              <span className="text-sm">Clientes atendidos</span>
            </div>
          </div>
          <div className="text-center">
            <Counter end={99} suffix=".9%" />
            <div className="flex items-center justify-center gap-2 mt-2 text-gray-500">
              <Clock className="w-4 h-4" />
              <span className="text-sm">Uptime garantido</span>
            </div>
          </div>
          <div className="text-center">
            <Counter end={23} suffix="+" />
            <div className="flex items-center justify-center gap-2 mt-2 text-gray-500">
              <Award className="w-4 h-4" />
              <span className="text-sm">Anos de experiência</span>
            </div>
          </div>
          <div className="text-center">
            <Counter end={24} suffix="/7" />
            <div className="flex items-center justify-center gap-2 mt-2 text-gray-500">
              <Users className="w-4 h-4" />
              <span className="text-sm">Suporte técnico</span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

export default About;
