import React, { useEffect, useRef } from 'react';
import { FileText, Brush, Globe } from 'lucide-react';

const processSteps = [
  {
    id: 1,
    title: 'Brief express',
    description: 'Comprendre vos besoins',
    icon: FileText
  },
  {
    id: 2,
    title: 'Design & développement',
    description: 'Création de votre projet',
    icon: Brush
  },
  {
    id: 3,
    title: 'Mise en ligne + suivi annuel',
    description: 'Support continu',
    icon: Globe
  }
];

export const Process: React.FC = () => {
  const sectionRef = useRef<HTMLElement>(null);
  const stepsRef = useRef<(HTMLDivElement | null)[]>([]);
  const titleRef = useRef<HTMLHeadingElement>(null);
  const circleRefs = useRef<(HTMLDivElement | null)[]>([]);
  const iconRefs = useRef<(HTMLDivElement | null)[]>([]);
  const animatedRef = useRef<boolean>(false);
  const rotationIntervalRef = useRef<NodeJS.Timeout | null>(null);
  const isVisibleRef = useRef<boolean>(true);

  useEffect(() => {
    const handleVisibilityChange = () => {
      isVisibleRef.current = !document.hidden;
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add('visible');
            
            if (titleRef.current && !animatedRef.current) {
              animatedRef.current = true;
              const letters = titleRef.current.querySelectorAll('.falling-letter');
              letters.forEach((letter) => {
                const delay = Math.random() * 2;
                const duration = 0.5 + Math.random();
                const rotation = (Math.random() - 0.5) * 720;
                
                letter.animate([
                  { 
                    transform: `translateY(-100vh) rotate(${rotation}deg)`, 
                    opacity: 0 
                  },
                  { 
                    transform: `translateY(0) rotate(0deg)`, 
                    opacity: 1 
                  }
                ], {
                  duration: duration * 1000,
                  delay: delay * 1000,
                  easing: 'cubic-bezier(0.34, 1.56, 0.64, 1)',
                  fill: 'forwards'
                });
              });

              // Démarrer la rotation aléatoire des icônes
              startRandomIconRotation();
            }
          }
        });
      },
      { threshold: 0.1 }
    );

    const startRandomIconRotation = () => {
      let currentIconIndex = 0;
      const interval = 2000; // intervalle fixe entre chaque rotation

      const rotateNext = () => {
        if (!isVisibleRef.current) {
          rotationIntervalRef.current = setTimeout(rotateNext, interval);
          return;
        }

        const icon = iconRefs.current[currentIconIndex];
        if (icon) {
          icon.style.transform = 'rotate(360deg)';
          icon.style.transition = 'transform 0.8s cubic-bezier(0.68, -0.55, 0.265, 1.55)';
          setTimeout(() => {
            icon.style.transform = 'rotate(0deg)';
            icon.style.transition = 'transform 0.3s ease';
          }, 800);
        }

        currentIconIndex = (currentIconIndex + 1) % iconRefs.current.length;
        rotationIntervalRef.current = setTimeout(rotateNext, interval);
      };

      rotationIntervalRef.current = setTimeout(rotateNext, 1500);
    };

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

    stepsRef.current.forEach((step) => {
      if (step) observer.observe(step);
    });

    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange);
      if (sectionRef.current) {
        observer.unobserve(sectionRef.current);
      }
      stepsRef.current.forEach((step) => {
        if (step) observer.unobserve(step);
      });
      if (rotationIntervalRef.current) {
        clearTimeout(rotationIntervalRef.current);
      }
    };
  }, []);

  const handleCircleClick = (index: number) => {
    const circle = circleRefs.current[index];
    if (circle) {
      // Ajouter la classe de rotation rapide
      circle.classList.add('spin-fast');
      
      // Retirer la classe après l'animation
      setTimeout(() => {
        circle.classList.remove('spin-fast');
      }, 2000); // 2 secondes pour l'animation complète
    }
  };

  const title = "Notre Process".split('').map((char, index) => {
    if (char === ' ') return ' ';
    return char;
  });

  return (
    <section id="process" className="section fade-in" ref={sectionRef}>
      <div className="container px-4 md:px-8">
        <div className="flex justify-center mb-12">
          <h2 
            ref={titleRef}
            className="text-3xl sm:text-4xl font-light falling-letters"
          >
            {title.map((char, index) => (
              <span
                key={index}
                className={char === ' ' ? 'mx-2' : 'falling-letter'}
                style={{ opacity: char === ' ' ? 1 : 0 }}
              >
                {char}
              </span>
            ))}
          </h2>
        </div>
        
        <div className="grid grid-cols-1 md:grid-cols-3 gap-12 md:gap-8">
          {processSteps.map((step, index) => {
            const Icon = step.icon;
            
            return (
              <div 
                key={step.id}
                className="flex flex-col items-center text-center fade-in relative"
                ref={el => stepsRef.current[index] = el}
                style={{ animationDelay: `${index * 0.2}s` }}
              >
                <div className="relative mb-6">
                  <div 
                    className="process-circle cursor-pointer"
                    onClick={() => handleCircleClick(index)}
                  >
                    <div 
                      ref={el => circleRefs.current[index] = el}
                      className="w-14 h-14 rounded-full border border-white/30 flex items-center justify-center relative z-10 bg-[#0F1A4C] hover:scale-110 transition-transform duration-200"
                    >
                      <div ref={el => iconRefs.current[index] = el}>
                        <Icon size={24} className="text-white/80" />
                      </div>
                    </div>
                  </div>
                  
                  {/* Animated connecting line - desktop */}
                  {index < processSteps.length - 1 && (
                    <div className="hidden md:block absolute top-1/2 left-0 w-full -translate-y-1/2">
                      <div className="h-[1px] bg-white/10 relative overflow-hidden">
                        <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/40 to-transparent animate-pulse"></div>
                      </div>
                    </div>
                  )}
                </div>
                
                <h3 className="text-xl font-light mb-4">{step.title}</h3>
                <p className="text-sm text-white/80 max-w-xs mx-auto">{step.description}</p>

                {/* Animated connecting line - mobile */}
                {index < processSteps.length - 1 && (
                  <div className="md:hidden absolute -bottom-6 left-1/2 -translate-x-1/2">
                    <div className="w-[1px] h-12 bg-white/10 relative overflow-hidden">
                      <div className="absolute inset-0 bg-gradient-to-b from-transparent via-white/40 to-transparent animate-pulse"></div>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
};