"use client";

import { useEffect, useRef, useState } from "react";
import {
  Handshake,
  Lightbulb,
  CheckCircle2,
  Rocket,
  TrendingUp,
} from "@/components/ui/icons";
import type { LucideIcon } from "@/components/ui/icons";
import { Badge } from "@/components/ui/badge";
import { Reveal } from "@/components/ui/reveal";
import { cn } from "@/lib/utils";

const STEPS: { icon: LucideIcon; title: string; text: string }[] = [
  {
    icon: Handshake,
    title: "On comprend votre activité",
    text: "On échange avec vous pour définir vos besoins et vos objectifs.",
  },
  {
    icon: Lightbulb,
    title: "On vous propose une solution",
    text: "Un site pensé pour attirer des clients, adapté à votre activité.",
  },
  {
    icon: CheckCircle2,
    title: "Vous validez",
    text: "Vous gardez le contrôle à chaque étape, sans surprise.",
  },
  {
    icon: Rocket,
    title: "On s'occupe de tout",
    text: "Création, mise en ligne, optimisation : votre site est prêt.",
  },
  {
    icon: TrendingUp,
    title: "On vous accompagne dans la durée",
    text: "On suit les performances et fait évoluer votre site en continu.",
  },
];

export function ProcessSection() {
  const trackRef = useRef<HTMLDivElement | null>(null);
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    if (typeof window === "undefined") return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
      setProgress(1);
      return;
    }

    let raf = 0;
    const update = () => {
      raf = 0;
      const node = trackRef.current;
      if (!node) return;
      const rect = node.getBoundingClientRect();
      const vh = window.innerHeight || document.documentElement.clientHeight;
      // Démarre à 0 quand le bloc commence à apparaître (top à 80 % du viewport),
      // arrive à 1 quand il quitte le viewport (bottom à 20 %).
      const start = vh * 0.8;
      const end = vh * 0.2 - rect.height;
      const span = start - end;
      const p = span > 0 ? (start - rect.top) / span : 0;
      setProgress(Math.max(0, Math.min(1, p)));
    };

    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(update);
    };

    update();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      if (raf) cancelAnimationFrame(raf);
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);

  const ballLeft = `${10 + progress * 80}%`;
  const progressWidth = `${progress * 80}%`;
  const activeIdx = Math.round(progress * (STEPS.length - 1));

  return (
    <section className="relative z-10 border-t border-border">
      <div className="mx-auto max-w-7xl px-4 sm:px-6 md:px-10 py-16 sm:py-20 md:py-24">
        <Reveal>
          <div className="text-center max-w-2xl mx-auto">
            <Badge tone="muted">Notre méthode</Badge>
            <h2 className="font-editorial mt-4 text-3xl sm:text-4xl md:text-5xl font-medium text-text leading-tight">
              Un accompagnement simple,
              <br />
              de A à Z.
            </h2>
            <p className="mt-5 text-text-muted leading-relaxed">
              On s'occupe de tout, étape par étape.
            </p>
          </div>
        </Reveal>

        <div ref={trackRef} className="mt-20 relative">
          {/* Ligne hairline (fond) */}
          <div className="hidden md:block absolute top-7 left-[10%] right-[10%] h-px bg-border" />

          {/* Ligne progressive amber */}
          <div
            className="hidden md:block absolute top-7 left-[10%] h-px bg-accent"
            style={{ width: progressWidth }}
          />

          {/* Boule lumineuse */}
          <div
            className="hidden md:block absolute top-7 -translate-x-1/2 -translate-y-1/2"
            style={{ left: ballLeft }}
          >
            <div className="size-2.5 rounded-full bg-accent shadow-[0_0_12px_var(--color-accent),0_0_24px_rgba(251,191,36,0.6)]" />
          </div>

          <ol className="grid grid-cols-1 md:grid-cols-5 gap-12 md:gap-4">
            {STEPS.map((step, i) => (
              <Step
                key={step.title}
                index={i + 1}
                active={i === activeIdx}
                reached={progress * (STEPS.length - 1) >= i - 0.05}
                last={i === STEPS.length - 1}
                {...step}
              />
            ))}
          </ol>
        </div>
      </div>
    </section>
  );
}

function Step({
  index,
  icon: Icon,
  title,
  text,
  active,
  reached,
  last,
}: {
  index: number;
  icon: LucideIcon;
  title: string;
  text: string;
  active: boolean;
  reached: boolean;
  last?: boolean;
}) {
  return (
    <li className="relative flex md:flex-col items-start md:items-center gap-5 md:gap-0 md:text-center">
      <div className="relative shrink-0">
        <div
          className={cn(
            "size-14 rounded-full bg-background border flex items-center justify-center transition-all duration-300",
            active
              ? "border-accent text-accent shadow-[0_0_0_4px_rgba(251,191,36,0.12),0_0_30px_rgba(251,191,36,0.35)]"
              : reached
                ? "border-accent/60 text-accent"
                : "border-border text-text-muted",
          )}
        >
          <Icon className="size-5" />
        </div>

        <span
          className={cn(
            "absolute -top-1 -right-1 size-6 rounded-full text-xxs font-bold flex items-center justify-center font-editorial tabular-nums shadow-[0_0_0_3px_var(--color-background)] transition-colors",
            active || reached
              ? "bg-accent text-accent-fg"
              : "bg-surface-2 text-text-muted border border-border",
          )}
        >
          {index}
        </span>

        {/* Connecteur vertical mobile */}
        {!last && (
          <span className="md:hidden absolute top-14 left-1/2 -translate-x-1/2 h-12 w-px bg-border" />
        )}
      </div>

      <div className="md:mt-6 md:px-2">
        <h3 className="text-sm font-semibold text-text">{title}</h3>
        <p className="mt-1.5 text-xs text-text-muted leading-relaxed md:max-w-[14rem] md:mx-auto">
          {text}
        </p>
      </div>
    </li>
  );
}
