import { useEffect, useRef, useState } from "react";
import { Search, Link2, RefreshCw, LineChart } from "lucide-react";

const steps = [
  {
    icon: <Search className="w-6 h-6" />,
    title: "Choose Strategy",
    description: "Select a strategy that aligns with your goals and risk appetite.",
  },
  {
    icon: <Link2 className="w-6 h-6" />,
    title: "Link Your Broker",
    description: "Connect your existing brokerage account securely.",
  },
  {
    icon: <RefreshCw className="w-6 h-6" />,
    title: "Auto-Invest",
    description: "Set up automatic monthly investments with a single click.",
  },
  {
    icon: <LineChart className="w-6 h-6" />,
    title: "Track Growth",
    description: "Watch your portfolio grow steadily over time.",
  },
];

export default function HowItWorks() {
  const sectionRef = useRef<HTMLDivElement>(null);
  const [visibleSteps, setVisibleSteps] = useState<number[]>([]);
  const [activeStep, setActiveStep] = useState(0);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          const index = parseInt(entry.target.getAttribute("data-step") || "0");
          if (entry.isIntersecting) {
            setVisibleSteps((prev) => {
              if (!prev.includes(index)) {
                return [...prev, index];
              }
              return prev;
            });
          }
        });
      },
      { threshold: 0.5 }
    );

    const stepElements = sectionRef.current?.querySelectorAll("[data-step]");
    stepElements?.forEach((el) => observer.observe(el));

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

  useEffect(() => {
    if (visibleSteps.length > 0) {
      const interval = setInterval(() => {
        setActiveStep((prev) => (prev + 1) % steps.length);
      }, 3000);
      return () => clearInterval(interval);
    }
  }, [visibleSteps]);

  return (
    <section
      ref={sectionRef}
      id="how-it-works"
      className="relative overflow-hidden px-4 py-20 sm:px-6 sm:py-24 md:py-32"
      data-testid="section-how-it-works"
    >
      <div className="absolute left-1/2 top-1/2 h-[420px] w-[420px] -translate-x-1/2 -translate-y-1/2 opacity-20 sm:h-[560px] sm:w-[560px] md:h-[800px] md:w-[800px] md:opacity-30">
        <div 
          className="absolute inset-0 rounded-full border border-primary/20"
          style={{ animation: "pulse-ring 4s ease-out infinite" }}
        />
        <div 
          className="absolute inset-8 rounded-full border border-primary/15"
          style={{ animation: "pulse-ring 4s ease-out infinite 1s" }}
        />
        <div 
          className="absolute inset-16 rounded-full border border-primary/10"
          style={{ animation: "pulse-ring 4s ease-out infinite 2s" }}
        />
      </div>

      <div className="max-w-4xl mx-auto relative">
        <div className="text-center mb-16">
          <p className="text-sm uppercase tracking-widest text-muted-foreground mb-4">
            How It Works
          </p>
          <h2 className="mb-4 text-3xl font-bold sm:text-4xl md:text-5xl" data-testid="text-how-it-works-headline">
            Four Simple Steps
          </h2>
          <p className="text-base text-muted-foreground sm:text-lg md:text-xl">
            Start your investment journey in minutes.
          </p>
        </div>

        <div className="grid gap-6 md:grid-cols-2 md:gap-8">
          {steps.map((step, index) => (
            <div
              key={step.title}
              data-step={index}
              className={`group flex items-start gap-4 transition-all duration-700 ease-out sm:gap-5 ${
                visibleSteps.includes(index)
                  ? "opacity-100 translate-y-0"
                  : "opacity-0 translate-y-8"
              }`}
              style={{ transitionDelay: `${index * 150}ms` }}
              onMouseEnter={() => setActiveStep(index)}
            >
              <div 
                className={`flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-xl transition-all duration-500 sm:h-14 sm:w-14 ${
                  activeStep === index 
                    ? "bg-primary text-primary-foreground scale-110 shadow-lg shadow-primary/25" 
                    : "bg-primary/10 text-primary"
                }`}
              >
                <div className={`transition-transform duration-500 ${activeStep === index ? "scale-110" : ""}`}>
                  {step.icon}
                </div>
              </div>
              <div>
                <div className="flex items-center gap-3 mb-2">
                  <span 
                    className={`text-sm font-medium transition-colors duration-300 ${
                      activeStep === index ? "text-primary" : "text-muted-foreground"
                    }`}
                  >
                    0{index + 1}
                  </span>
                  <h3 
                    className={`text-base font-semibold transition-colors duration-300 sm:text-lg ${
                      activeStep === index ? "text-foreground" : "text-foreground/80"
                    }`}
                    data-testid={`text-step-title-${index}`}
                  >
                    {step.title}
                  </h3>
                </div>
                <p className="text-muted-foreground leading-relaxed">
                  {step.description}
                </p>
                <div 
                  className={`h-0.5 bg-primary mt-4 transition-all duration-500 origin-left ${
                    activeStep === index ? "scale-x-100 opacity-100" : "scale-x-0 opacity-0"
                  }`}
                />
              </div>
            </div>
          ))}
        </div>

        <div className="flex justify-center gap-2 mt-12">
          {steps.map((_, index) => (
            <button
              key={index}
              onClick={() => setActiveStep(index)}
              className={`w-2 h-2 rounded-full transition-all duration-300 ${
                activeStep === index 
                  ? "bg-primary w-8" 
                  : "bg-muted-foreground/30 hover:bg-muted-foreground/50"
              }`}
              data-testid={`button-step-indicator-${index}`}
            />
          ))}
        </div>
      </div>

      <style>{`
        @keyframes pulse-ring {
          0% { transform: scale(0.8); opacity: 1; }
          100% { transform: scale(1.2); opacity: 0; }
        }
      `}</style>
    </section>
  );
}
