// Process (visual timeline) + Cases (featured + smaller, animated chart)

// ── useReveal hook: marks an element for the global reveal observer ──
function useReveal() {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    el.classList.add("reveal");
  }, []);
  return ref;
}
window.useReveal = useReveal;

// ── Process — vertical visual timeline ──────────────────────────
function Process() {
  const steps = [
    {
      n: "01",
      t: "Audit & feuille de route",
      d: "On analyse votre activité et vos enjeux pour identifier les opportunités IA à plus fort impact. Vous repartez avec un plan d'action chiffré et priorisé.",
      visual: <AuditVisual />,
      duration: "",
    },
    {
      n: "02",
      t: "Déploiement",
      d: "Intégration dans vos outils existants, branchement des données, sécurité, accès équipes. Vous voyez l'IA tourner sur vos vrais cas d'usage en quelques semaines.",
      visual: <DeployVisual />,
      duration: "",
    },
    {
      n: "03",
      t: "Suivi & amélioration",
      d: "Maintenance, monitoring, ajustements. Vos outils IA gagnent en précision au fil de l'usage. Un suivi continu pour faire évoluer la solution avec vous.",
      visual: <MonitorVisual />,
      duration: "en continu",
    },
  ];

  return (
    <section id="process" data-screen-label="03 Process" className="section">
      <div className="container">
        <div className="reveal" style={{
          display: "flex", flexDirection: "column", gap: 14,
          marginBottom: 48, maxWidth: 760,
        }}>
          <span className="eyebrow">/ Notre méthode</span>
          <h2 className="t-display-md" style={{ margin: 0, textWrap: "balance" }}>
            De l'idée au déploiement, en quelques semaines.
          </h2>
        </div>

        <div className="process-timeline">
          {/* Vertical accent line — left side */}
          <div className="process-line">
            <div className="process-line-fill" />
          </div>

          {steps.map((s, i) => (
            <ProcessStep key={i} {...s} idx={i} last={i === steps.length - 1} />
          ))}
        </div>

        <style>{`
          .process-timeline {
            position: relative;
            display: flex;
            flex-direction: column;
            gap: 20px;
            padding-left: 44px;
          }
          .process-line {
            position: absolute;
            left: 21px;
            top: 22px;
            bottom: 22px;
            width: 1px;
            background: var(--hairline);
          }
          .process-line-fill {
            position: absolute;
            inset: 0;
            background: linear-gradient(180deg, var(--accent) 0%, var(--accent) 50%, transparent 100%);
            transform-origin: top;
            transform: scaleY(0);
            transition: transform 1.05s var(--ease-out-soft);
          }

          .process-step {
            position: relative;
            display: grid;
            grid-template-columns: 1fr 1fr;
            align-items: center;
            gap: 24px;
            padding: 6px 0;
          }

          /* Marker circle on the line */
          .process-marker {
            position: absolute;
            left: -44px;
            top: 24px;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            background: var(--canvas);
            border: 1px solid var(--hairline-strong);
            display: grid; place-items: center;
            font-family: var(--font-mono);
            font-size: 12px;
            letter-spacing: 0.06em;
            color: var(--ink);
            z-index: 2;
            transition: border-color 0.24s var(--ease-ui), box-shadow 0.36s var(--ease-ui);
          }
          .process-step.reveal.in .process-marker {
            border-color: var(--accent);
            box-shadow: 0 0 0 4px color-mix(in oklab, var(--accent) 18%, transparent), 0 0 30px var(--accent-glow);
          }
          .process-marker::after {
            content: "";
            position: absolute;
            inset: -1px;
            border-radius: 50%;
            border: 1px dashed var(--accent);
            opacity: 0;
            animation: pulseRing 2.4s ease-out infinite;
          }
          .process-step.reveal.in .process-marker::after { opacity: 1; }
          @keyframes pulseRing {
            0%   { transform: scale(1);   opacity: 0.6; }
            100% { transform: scale(1.8); opacity: 0; }
          }

          /* When any step is visible, fill the line */
          .process-timeline:has(.process-step.reveal.in) .process-line-fill { transform: scaleY(1); }

          @media (max-width: 880px) {
            .process-timeline { padding-left: 72px; gap: 24px; }
            .process-line { left: 21px; }
            .process-step { grid-template-columns: 1fr; gap: 16px; padding: 10px 0; }
            .process-marker { left: -72px; width: 42px; height: 42px; font-size: 12px; top: 4px; }
            .process-visual { aspect-ratio: 1.8 / 1 !important; padding: 16px !important; }
          }
        `}</style>
      </div>
    </section>
  );
}

function ProcessStep({ n, t, d, visual, duration, idx, last }) {
  const ref = useReveal();
  return (
    <div ref={ref} className="process-step reveal">
      <div className="process-marker">{n}</div>

      {/* Content — left */}
      <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
        {duration && (
          <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
            <span style={{
              padding: "3px 10px",
              borderRadius: 9999,
              border: "1px solid var(--hairline)",
              fontFamily: "var(--font-mono)",
              fontSize: 10.5,
              letterSpacing: "0.08em",
              textTransform: "uppercase",
              color: "var(--body-mid)",
              whiteSpace: "nowrap",
            }}>{duration}</span>
          </div>
        )}
        <h3 style={{
          margin: 0,
          fontSize: "clamp(20px, 2.4vw, 26px)",
          letterSpacing: "-0.025em",
          lineHeight: 1.15,
          color: "var(--ink)",
          textWrap: "balance",
        }}>{t}</h3>
        {d && <p style={{ margin: 0, color: "var(--body)", fontSize: 14.5, lineHeight: 1.55, maxWidth: 460 }}>{d}</p>}
      </div>

      {/* Visual — right */}
      <div className="process-visual" style={{
        background: "var(--canvas-card)",
        border: "1px solid var(--hairline)",
        borderRadius: "var(--radius-sm)",
        padding: 22,
        aspectRatio: "1.5 / 1",
        display: "grid",
        placeItems: "center",
        overflow: "hidden",
        position: "relative",
      }}>{visual}</div>
    </div>
  );
}

// ── Process visuals ─────────────────────────────────────────────
function AuditVisual() {
  // Grid of dots with one highlighted (the opportunity discovered)
  const rows = 7, cols = 11;
  return (
    <svg width="100%" height="100%" viewBox="0 0 220 140" style={{ maxHeight: 180 }}>
      {Array.from({ length: rows }).map((_, r) =>
        Array.from({ length: cols }).map((_, c) => {
          const x = 12 + c * 20;
          const y = 12 + r * 20;
          const isHot = (r === 3 && c === 5);
          const isWarm = (r === 2 && c === 4) || (r === 4 && c === 6) || (r === 3 && c === 7);
          return <circle
            key={`${r}-${c}`}
            cx={x} cy={y} r={isHot ? 4 : isWarm ? 2.5 : 1.5}
            fill={isHot ? "var(--accent)" : isWarm ? "var(--accent-soft)" : "var(--ink)"}
            opacity={isHot ? 1 : isWarm ? 0.65 : 0.25}
          />;
        })
      )}
      <circle cx="112" cy="72" r="22" fill="none" stroke="var(--accent)" strokeWidth="1" strokeDasharray="3 3" opacity="0.8">
        <animate attributeName="r" values="22;26;22" dur="2.4s" repeatCount="indefinite" />
      </circle>
      <text x="112" y="115" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="1" fill="var(--accent)">OPPORTUNITÉ</text>
    </svg>
  );
}

function DeployVisual() {
  // Flow diagram: sources → agent → outputs (compact, balanced)
  return (
    <svg width="100%" height="100%" viewBox="0 0 240 130" preserveAspectRatio="xMidYMid meet" style={{ maxHeight: 180 }}>
      {/* Sources (left) */}
      <g>
        <rect x="14" y="22" width="42" height="22" rx="5" fill="none" stroke="var(--hairline-strong)" />
        <text x="35" y="36" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="var(--body)">CRM</text>
        <rect x="14" y="54" width="42" height="22" rx="5" fill="none" stroke="var(--hairline-strong)" />
        <text x="35" y="68" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="var(--body)">EMAIL</text>
        <rect x="14" y="86" width="42" height="22" rx="5" fill="none" stroke="var(--hairline-strong)" />
        <text x="35" y="100" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="var(--body)">DOCS</text>
      </g>

      {/* Agent center */}
      <g>
        <circle cx="120" cy="65" r="22" fill="color-mix(in oklab, var(--accent) 18%, transparent)" stroke="var(--accent)" strokeWidth="1.2" />
        <circle cx="120" cy="65" r="3" fill="var(--accent)">
          <animate attributeName="r" values="3;5;3" dur="1.8s" repeatCount="indefinite" />
        </circle>
        <text x="120" y="100" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="1" fill="var(--ink)">AGENT</text>
      </g>

      {/* Outputs (right) */}
      <g>
        <rect x="184" y="22" width="42" height="22" rx="5" fill="none" stroke="var(--hairline-strong)" />
        <text x="205" y="36" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="var(--body)">TEAMS</text>
        <rect x="184" y="54" width="42" height="22" rx="5" fill="none" stroke="var(--hairline-strong)" />
        <text x="205" y="68" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="var(--body)">EMAIL</text>
        <rect x="184" y="86" width="42" height="22" rx="5" fill="none" stroke="var(--hairline-strong)" />
        <text x="205" y="100" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="var(--body)">DB</text>
      </g>

      {/* Connectors */}
      <path d="M56 33 L98 65 M56 65 L98 65 M56 97 L98 65" stroke="var(--hairline-strong)" strokeWidth="0.8" fill="none" />
      <path d="M142 65 L184 33 M142 65 L184 65 M142 65 L184 97" stroke="var(--hairline-strong)" strokeWidth="0.8" fill="none" />

      {/* Data flow particles */}
      <circle r="2" fill="var(--accent)"><animateMotion dur="1.6s" repeatCount="indefinite" path="M56 33 L98 65" /></circle>
      <circle r="2" fill="var(--accent)"><animateMotion dur="1.6s" begin="0.4s" repeatCount="indefinite" path="M56 65 L98 65" /></circle>
      <circle r="2" fill="var(--accent)"><animateMotion dur="1.6s" begin="0.8s" repeatCount="indefinite" path="M56 97 L98 65" /></circle>
      <circle r="2" fill="var(--accent-soft)"><animateMotion dur="1.6s" begin="0.8s" repeatCount="indefinite" path="M142 65 L184 33" /></circle>
      <circle r="2" fill="var(--accent-soft)"><animateMotion dur="1.6s" begin="0.4s" repeatCount="indefinite" path="M142 65 L184 65" /></circle>
      <circle r="2" fill="var(--accent-soft)"><animateMotion dur="1.6s" repeatCount="indefinite" path="M142 65 L184 97" /></circle>
    </svg>
  );
}

function MonitorVisual() {
  // Bar chart that grows: usage / precision over time
  return (
    <svg width="100%" height="100%" viewBox="0 0 240 140" style={{ maxHeight: 180 }}>
      {/* axes */}
      <line x1="20" y1="120" x2="220" y2="120" stroke="var(--hairline)" strokeWidth="0.8" />
      <line x1="20" y1="20" x2="20" y2="120" stroke="var(--hairline)" strokeWidth="0.8" />
      {/* grid */}
      {[40, 60, 80, 100].map(y => (
        <line key={y} x1="20" y1={y} x2="220" y2={y} stroke="var(--hairline)" strokeWidth="0.4" strokeDasharray="2 4" />
      ))}
      {/* bars */}
      {[
        { x: 38,  h: 30 },
        { x: 60,  h: 45 },
        { x: 82,  h: 38 },
        { x: 104, h: 56 },
        { x: 126, h: 64 },
        { x: 148, h: 72 },
        { x: 170, h: 84 },
        { x: 192, h: 92 },
      ].map((b, i) => (
        <rect key={i} x={b.x} y={120 - b.h} width="14" height={b.h}
          fill={i >= 6 ? "var(--accent)" : "var(--ink)"}
          opacity={i >= 6 ? 1 : 0.18}>
          <animate attributeName="height" from="0" to={b.h} dur="0.8s" begin={`${i * 0.08}s`} fill="freeze" />
          <animate attributeName="y" from="120" to={120 - b.h} dur="0.8s" begin={`${i * 0.08}s`} fill="freeze" />
        </rect>
      ))}
      {/* trend line */}
      <path d="M45 90 L67 75 L89 82 L111 64 L133 56 L155 48 L177 36 L199 28"
        stroke="var(--accent)" strokeWidth="1.2" fill="none" strokeLinecap="round" strokeLinejoin="round"
        strokeDasharray="200" strokeDashoffset="200">
        <animate attributeName="stroke-dashoffset" from="200" to="0" dur="1.2s" begin="0.4s" fill="freeze" />
      </path>
      <text x="220" y="18" textAnchor="end" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="1" fill="var(--accent)">+38%</text>
    </svg>
  );
}

// ── Cases — featured + grid ─────────────────────────────────────
function Cases() {
  const featured = {
    industry: "Cabinet dentaire · 4 dentistes · Paris",
    title: "Un assistant IA qui répond aux questions des patients et prend les rendez-vous 24h/7j.",
    desc: "Disponible par appel et par SMS, l'assistant répond aux questions des patients à toute heure (horaires, tarifs, motifs de consultation, urgences), propose des créneaux, gère les annulations et envoie les rappels.",
    metrics: [
      { v: "+38%", l: "RDV pris hors horaires" },
    ],
  };

  const small = [
    {
      industry: "Pizzeria · Tomate & Mozza · Gironde",
      title: "Un service de click & collect automatisé, de la commande à la prise en charge.",
      desc: "L'IA prend les commandes en ligne, confirme la préparation, gère les modifications et envoie les notifications de retrait. L'équipe en salle ne décroche plus le téléphone pendant le coup de feu.",
      metric: { v: "+20%", l: "de chiffre d'affaires" },
    },
    {
      industry: "Cabinet de conseil · 100+ collab. · Paris",
      title: "Une plateforme IA interne qui automatise les tâches répétitives des équipes.",
      desc: "Plusieurs agents IA spécialisés (gestion de mails, rédaction de devis, reporting, suivi de dossiers, support interne) regroupés dans une interface unique. Les collaborateurs déclenchent les automatisations à la demande.",
      metric: { v: "6 h/sem", l: "récupérées par collaborateur" },
    },
  ];

  return (
    <section id="cas" data-screen-label="05 Cases" className="section">
      <div className="container">
        <div className="reveal" style={{
          display: "flex", justifyContent: "space-between", alignItems: "flex-end",
          marginBottom: 24, gap: 32, flexWrap: "wrap",
        }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <span className="eyebrow">/ Cas clients</span>
            <h2 className="t-display-md" style={{ margin: 0, maxWidth: 640, textWrap: "balance" }}>
              50+ entreprises nous ont fait confiance.
            </h2>
            <p className="t-body-lg" style={{ margin: 0, maxWidth: 600, color: "var(--body)" }}>
              <strong style={{ color: "var(--ink)" }}>9 entreprises sur 10</strong> renouvellent leur collaboration au-delà du premier projet avec Pulse.
            </p>
          </div>
        </div>

        <div className="cases-layout" data-stagger style={{ marginTop: 32 }}>
          <CaseFeatured {...featured} />
          {small.map((c, i) => <CaseSmall key={i} {...c} />)}
        </div>

        <style>{`
          .cases-layout {
            display: grid;
            grid-template-columns: 1.5fr 1fr;
            gap: 16px;
          }
          .cases-layout > .case-featured { grid-row: span 2; }
          .cases-proof {
            justify-content: space-between;
            align-items: center;
          }
          @media (max-width: 880px) {
            .cases-layout { grid-template-columns: 1fr; gap: 32px !important; }
            .cases-layout > .case-featured { grid-row: auto; }
            .cases-proof {
              flex-direction: column;
              align-items: stretch;
              gap: 16px;
              padding: 20px;
            }
            .cases-proof-sep { display: none !important; }
          }
        `}</style>
      </div>
    </section>
  );
}

function ProofItem({ v, l, accent }) {
  return (
    <div style={{
      display: "flex",
      flexDirection: "column",
      gap: 4,
      flex: 1,
      minWidth: 0,
    }}>
      <span style={{
        fontSize: 32,
        letterSpacing: "-0.04em",
        lineHeight: 1,
        color: accent ? "var(--accent)" : "var(--ink)",
      }}>{v}</span>
      <span className="t-mono-sm" style={{ color: "var(--body-mid)" }}>{l}</span>
    </div>
  );
}

function ProofSep() {
  return <span className="cases-proof-sep" style={{ width: 1, height: 36, background: "var(--hairline)", margin: "0 24px", flexShrink: 0 }} />;
}

function CaseFeatured({ industry, title, desc, metrics }) {
  const ref = useReveal();
  return (
    <article ref={ref} className="reveal interactive-card case-featured" style={{
      background: "var(--canvas-card)",
      border: "1px solid var(--hairline)",
      borderRadius: "var(--radius-sm)",
      padding: 28,
      display: "flex",
      flexDirection: "column",
      gap: 18,
      position: "relative",
      overflow: "hidden",
      minHeight: 380,
    }}>
      {/* Background chart */}
      <div className="case-featured-bg" style={{
        position: "absolute", inset: 0,
        opacity: 0.5,
        pointerEvents: "none",
      }}>
        <svg width="100%" height="100%" preserveAspectRatio="none" viewBox="0 0 600 400">
          <defs>
            <linearGradient id="caseGrad" x1="0" x2="0" y1="0" y2="1">
              <stop offset="0" stopColor="var(--accent)" stopOpacity="0.2" />
              <stop offset="1" stopColor="var(--accent)" stopOpacity="0" />
            </linearGradient>
          </defs>
          <path d="M0 320 Q 100 280 200 290 T 400 220 T 600 120 L 600 400 L 0 400 Z" fill="url(#caseGrad)" />
          <path d="M0 320 Q 100 280 200 290 T 400 220 T 600 120" stroke="var(--accent)" strokeWidth="1.2" fill="none" />
        </svg>
      </div>

      <div style={{ position: "relative", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
        <span style={{
          fontFamily: "var(--font-mono)",
          fontSize: 10,
          letterSpacing: "0.12em",
          textTransform: "uppercase",
          color: "var(--body-mid)",
          lineHeight: 1.4,
        }}>{industry}</span>
      </div>

      <h3 style={{
        margin: 0,
        fontSize: "clamp(20px, 2.05vw, 26px)",
        letterSpacing: "-0.028em",
        lineHeight: 1.18,
        color: "var(--ink)",
        position: "relative",
        textWrap: "balance",
      }}>{title}</h3>

      <p style={{
        margin: 0, color: "var(--body)", fontSize: 14.5, lineHeight: 1.55,
        position: "relative", maxWidth: 520,
      }}>{desc}</p>

      <div style={{ flex: 1 }} />

      <div style={{
        display: "flex",
        flexWrap: "wrap",
        gap: 32,
        paddingTop: 18,
        borderTop: "1px solid var(--hairline)",
        position: "relative",
      }}>
        {metrics.map((m, i) => (
          <div key={i} style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            <span style={{
              fontSize: 22,
              letterSpacing: "-0.025em",
              lineHeight: 1,
              color: i === 0 ? "var(--accent)" : "var(--ink)",
            }}>{m.v}</span>
            <span style={{
              fontFamily: "var(--font-mono)",
              fontSize: 10,
              letterSpacing: "0.12em",
              textTransform: "uppercase",
              color: "var(--body-mid)",
            }}>{m.l}</span>
          </div>
        ))}
      </div>
    </article>
  );
}

function CaseSmall({ industry, title, desc, metric }) {
  const ref = useReveal();
  return (
    <article ref={ref} className="reveal interactive-card" style={{
      background: "var(--canvas-card)",
      border: "1px solid var(--hairline)",
      borderRadius: "var(--radius-sm)",
      padding: 22,
      display: "flex",
      flexDirection: "column",
      gap: 10,
      position: "relative",
      overflow: "hidden",
    }}>
      <span style={{
        fontFamily: "var(--font-mono)",
        fontSize: 10,
        letterSpacing: "0.12em",
        textTransform: "uppercase",
        color: "var(--body-mid)",
        lineHeight: 1.4,
      }}>{industry}</span>
      <h3 style={{
        margin: 0,
        fontSize: 17,
        letterSpacing: "-0.02em",
        lineHeight: 1.25,
        color: "var(--ink)",
      }}>{title}</h3>
      <p style={{ margin: 0, color: "var(--body)", fontSize: 13.5, lineHeight: 1.5, flex: 1 }}>{desc}</p>
      <div style={{
        display: "flex", alignItems: "baseline", gap: 10,
        paddingTop: 12,
        borderTop: "1px solid var(--hairline)",
      }}>
        <span style={{
          fontSize: 18,
          letterSpacing: "-0.022em",
          lineHeight: 1,
          color: "var(--accent)",
        }}>{metric.v}</span>
        <span style={{
          fontFamily: "var(--font-mono)",
          fontSize: 10,
          letterSpacing: "0.12em",
          textTransform: "uppercase",
          color: "var(--body-mid)",
        }}>{metric.l}</span>
      </div>
    </article>
  );
}

Object.assign(window, { Process, Cases });
