function Showcase() {
  return (
    <Section id="vitrine" className="relative py-28 sm:py-36 overflow-hidden">
      {/* aurora hint */}
      <div className="absolute inset-x-0 top-0 h-[460px] aurora opacity-30"></div>
      <div className="absolute inset-0 tech-grid opacity-30 [mask-image:linear-gradient(180deg,black,transparent_70%)]"></div>

      <div className="relative mx-auto max-w-7xl px-5 sm:px-8">
        <div className="text-center max-w-3xl mx-auto">
          <Reveal><SectionEyebrow className="mx-auto justify-center inline-flex">02 · La vitrine</SectionEyebrow></Reveal>
          <Reveal delay={80}><h2 className="mt-5 font-display text-4xl sm:text-5xl md:text-6xl font-medium tracking-tight text-paper-50">Voyez Flowo <span className="gtext">en action.</span></h2></Reveal>
          <Reveal delay={140}><p className="mt-5 text-paper-100/65 text-[17px]">Pas des promesses. Des systèmes qui tournent.</p></Reveal>
        </div>

        <div className="mt-20 grid lg:grid-cols-2 gap-6">
          <Reveal>
            <ShowcaseCard
              tag="Génération IA"
              title="Email de relance écrit en 1.4s"
              desc="L'IA lit le dossier, choisit le ton, signe avec le bon collaborateur."
              chips={['Personnalisé', 'Ton adapté', 'Avec IA']}
            >
              <EmailTyper />
            </ShowcaseCard>
          </Reveal>
          <Reveal delay={120}>
            <ShowcaseCard
              tag="Orchestration"
              title="Workflow intelligent · n nœuds"
              desc="Déclencheur → Lecture → IA → Envoi → Mise à jour. Tout est observable."
              chips={['n8n self-hosted', 'Suisse', 'Sans IA · Avec IA']}
            >
              <WorkflowCanvas />
            </ShowcaseCard>
          </Reveal>
          <Reveal>
            <ShowcaseCard
              tag="Analyse de sentiment"
              title="Chaque réponse, routée au bon humain"
              desc="Coopératif, demande de délai, ou mécontent : l'IA classe et escalade si besoin."
              chips={['Sentiment', 'Escalade auto', 'Avec IA']}
            >
              <SentimentRouter />
            </ShowcaseCard>
          </Reveal>
          <Reveal delay={120}>
            <ShowcaseCard
              tag="Tableau de bord"
              title="Le pouls de votre fiduciaire en direct"
              desc="Relances envoyées, taux de réponse, dossiers à escalader. Mis à jour minute par minute."
              chips={['Temps réel', 'Digest hebdo', 'Avec IA']}
            >
              <Dashboard />
            </ShowcaseCard>
          </Reveal>
        </div>
      </div>
    </Section>
  );
}

function ShowcaseCard({ tag, title, desc, chips, children }) {
  return (
    <div className="gborder p-6 sm:p-7 group h-full flex flex-col">
      <div className="flex items-center gap-2 mb-4">
        <span className="font-mono text-[10.5px] tracking-[0.22em] uppercase text-violet-500/90">{tag}</span>
        <span className="flex-1 border-t border-paper-300/8"></span>
        <span className="text-[10px] font-mono text-paper-300/35">DÉMO</span>
        <span className="relative flex w-1.5 h-1.5"><span className="absolute inset-0 rounded-full bg-emerald-400"></span><span className="absolute inset-0 rounded-full bg-emerald-400 animate-ping opacity-60"></span></span>
      </div>
      <h3 className="font-display text-[22px] sm:text-[24px] text-paper-50 font-medium tracking-tight text-balance">{title}</h3>
      <p className="mt-2 text-[14px] text-paper-100/60">{desc}</p>
      <div className="mt-5 flex flex-wrap gap-1.5">
        {chips.map((c) => <Chip key={c} tone="ink" className="!text-[10px] !py-0.5">{c}</Chip>)}
      </div>
      <div className="mt-6 rounded-xl bg-ink-900/70 border border-paper-300/5 overflow-hidden flex-1 min-h-[260px] relative">
        {children}
      </div>
    </div>
  );
}

/* --- Showcase A — typing email --- */
function EmailTyper() {
  const lines = [
    { t: "Bonjour,", d: 60 },
    { t: "", d: 100 },
    { t: "Pour finaliser votre déclaration TVA du Q3, il nous", d: 22 },
    { t: "manque deux pièces : le justificatif de votre achat", d: 22 },
    { t: "de juillet et la facture du fournisseur identifiée", d: 22 },
    { t: "dans votre Bexio.", d: 22 },
    { t: "", d: 80 },
    { t: "Pourriez-vous les transmettre d'ici vendredi 28 ?", d: 22 },
    { t: "", d: 80 },
    { t: "Avec mes meilleures salutations,", d: 30 },
    { t: "Votre fiduciaire", d: 26 },
  ];
  const [out, setOut] = useState(['']);
  const [done, setDone] = useState(false);
  useEffect(() => {
    let cancelled = false;
    async function run() {
      while (!cancelled) {
        setDone(false);
        setOut(['']);
        let cur = [''];
        for (let i = 0; i < lines.length; i++) {
          const { t, d } = lines[i];
          for (let c = 0; c < t.length; c++) {
            if (cancelled) return;
            cur[i] = (cur[i] || '') + t[c];
            setOut([...cur]);
            await new Promise(r => setTimeout(r, d));
          }
          if (cancelled) return;
          cur.push('');
          setOut([...cur]);
          await new Promise(r => setTimeout(r, 80));
        }
        setDone(true);
        await new Promise(r => setTimeout(r, 4200));
      }
    }
    run();
    return () => { cancelled = true; };
  }, []);
  return (
    <div className="h-full flex flex-col">
      {/* email chrome */}
      <div className="px-4 py-3 border-b border-paper-300/5 flex items-center gap-3 text-[11.5px]">
        <div className="w-7 h-7 rounded-full bg-gradient-to-br from-violet-600 to-violet-500 grid place-items-center overflow-hidden">
          <img src={window.__resources.flowoLogo} alt="" aria-hidden="true" className="w-5 h-5 object-contain" />
        </div>
        <div className="flex-1 min-w-0">
          <div className="text-paper-50 truncate">À : client@exemple.ch</div>
          <div className="text-paper-300/45 truncate">Relance · Pièces manquantes TVA Q3</div>
        </div>
        <div className="font-mono text-[10px] text-violet-500 flex items-center gap-1.5">
          <Icon.Spark className="w-3 h-3" /> IA · GPT-4 · FR
        </div>
      </div>
      <div className="p-4 sm:p-5 font-[450] text-[13.5px] leading-relaxed text-paper-100/85 overflow-hidden flex-1">
        {out.map((l, i) => (
          <div key={i} className={`min-h-[1.6em] ${i === out.length - 1 ? 'caret' : ''}`}>{l || '\u00a0'}</div>
        ))}
      </div>
      <div className="px-4 py-3 border-t border-paper-300/5 flex items-center justify-between text-[11.5px]">
        <div className="flex items-center gap-2 text-paper-300/45 font-mono">
          <span className={`inline-flex w-1.5 h-1.5 rounded-full ${done ? 'bg-emerald-400' : 'bg-violet-500 animate-pulse'}`}></span>
          {done ? 'Rédigé en 1.4s · prêt à envoyer' : 'Génération en cours…'}
        </div>
        <div className="flex items-center gap-1.5">
          <span className="px-2 py-1 rounded border border-paper-300/10 text-paper-100/70 text-[11px]">Aperçu</span>
          <span className="px-2 py-1 rounded bg-violet-600 text-white text-[11px]">Envoyer</span>
        </div>
      </div>
    </div>
  );
}

/* --- Showcase B — workflow canvas with light-up edges --- */
function WorkflowCanvas() {
  const [step, setStep] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setStep((s) => (s + 1) % 6), 900);
    return () => clearInterval(id);
  }, []);
  const nodes = [
    { x: 70, y: 130, t: 'Déclencheur', sub: '08h00 · CRON', icon: 'clock' },
    { x: 220, y: 70, t: 'Lecture', sub: 'Google Sheets', icon: 'sheet' },
    { x: 220, y: 190, t: 'Filtre', sub: 'dossiers > 7j', icon: 'filter' },
    { x: 380, y: 130, t: 'IA', sub: 'GPT-4 · ton FR', icon: 'spark' },
    { x: 540, y: 70, t: 'Envoi', sub: 'Gmail', icon: 'mail' },
    { x: 540, y: 190, t: 'Maj', sub: 'Sheets', icon: 'check' },
  ];
  const edges = [
    [0,1], [0,2], [1,3], [2,3], [3,4], [3,5]
  ];
  const activeMap = step;
  return (
    <div className="absolute inset-0">
      <div className="absolute inset-0 [background-image:radial-gradient(rgba(255,255,255,0.06)_1px,transparent_1px)] [background-size:20px_20px] opacity-60"></div>
      <svg viewBox="0 0 640 280" className="w-full h-full" preserveAspectRatio="xMidYMid meet">
        <defs>
          <linearGradient id="lt" x1="0" x2="1"><stop offset="0" stopColor="#22d3ee" /><stop offset="1" stopColor="#10b981" /></linearGradient>
          <filter id="gl"><feGaussianBlur stdDeviation="3" /></filter>
        </defs>
        {edges.map(([a, b], i) => {
          const na = nodes[a], nb = nodes[b];
          const active = i < activeMap;
          const d = `M ${na.x + 42} ${na.y} C ${(na.x + nb.x) / 2} ${na.y}, ${(na.x + nb.x) / 2} ${nb.y}, ${nb.x - 42} ${nb.y}`;
          return (
            <g key={i}>
              <path d={d} stroke={active ? '#10b981' : 'rgba(255,255,255,0.07)'} strokeWidth="1.4" fill="none" />
              {active && <path d={d} stroke="url(#lt)" strokeWidth="2.4" fill="none" filter="url(#gl)" opacity="0.7" />}
              {active && (
                <circle r="3" fill="#10b981" filter="url(#gl)">
                  <animateMotion dur="0.9s" repeatCount="indefinite" path={d} />
                </circle>
              )}
            </g>
          );
        })}
        {nodes.map((n, i) => {
          const isActive = i <= activeMap;
          return (
            <g key={i} transform={`translate(${n.x - 42} ${n.y - 22})`}>
              <rect width="84" height="44" rx="9" fill="#0a0a0f" stroke={isActive ? '#10b981' : 'rgba(255,255,255,0.12)'} strokeWidth="1" />
              {isActive && <rect width="84" height="44" rx="9" fill="none" stroke="#10b981" opacity="0.4" filter="url(#gl)" />}
              <text x="42" y="19" textAnchor="middle" fill="#fafaf7" fontSize="11" fontFamily="Space Grotesk" fontWeight="500">{n.t}</text>
              <text x="42" y="32" textAnchor="middle" fill={isActive ? '#10b981' : '#cfceca'} opacity="0.7" fontSize="8.5" fontFamily="JetBrains Mono">{n.sub}</text>
            </g>
          );
        })}
      </svg>
      <div className="absolute bottom-3 left-4 right-4 flex items-center justify-between text-[10.5px] font-mono">
        <div className="text-paper-300/50">workflow #07 · relances tva</div>
        <div className="text-emerald-400">étape {Math.min(activeMap + 1, 6)} / 6</div>
      </div>
    </div>
  );
}

/* --- Showcase C — sentiment router --- */
function SentimentRouter() {
  const inbox = [
    { from: 'Dossier #2847', subject: 'Merci, je vous envoie ça demain', cls: 'coop' },
    { from: 'Dossier #2851', subject: 'Pouvez-vous me laisser jusqu\'à lundi ?', cls: 'delai' },
    { from: 'Dossier #2853', subject: 'Je trouve ça inacceptable, voici…', cls: 'mecontent' },
    { from: 'Dossier #2849', subject: 'OK reçu, je m\'en occupe.', cls: 'coop' },
  ];
  const [active, setActive] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setActive((a) => (a + 1) % inbox.length), 2200);
    return () => clearInterval(id);
  }, []);
  const cur = inbox[active];
  const branches = [
    { id: 'coop', label: 'Coopératif', color: '#10b981' },
    { id: 'delai', label: 'Délai', color: '#f59e0b' },
    { id: 'mecontent', label: 'Mécontent', color: '#ef4444' },
  ];
  return (
    <div className="absolute inset-0 p-5 flex items-center">
      <div className="w-full grid grid-cols-12 gap-3 items-center">
        {/* incoming card */}
        <div key={active} className="col-span-5 rounded-lg bg-ink-800/80 border border-paper-300/8 p-3 animate-[float_3s_ease-in-out_infinite]">
          <div className="text-[10px] font-mono text-paper-300/50 mb-1">EMAIL ENTRANT</div>
          <div className="text-[12px] text-paper-50 font-medium">{cur.from}</div>
          <div className="text-[12px] text-paper-100/65 mt-0.5 line-clamp-2">{cur.subject}</div>
        </div>
        {/* arrows */}
        <div className="col-span-2 relative h-32">
          <svg viewBox="0 0 100 120" className="w-full h-full">
            {branches.map((b, i) => {
              const yEnd = 20 + i * 40;
              const active = b.id === cur.cls;
              return (
                <g key={b.id}>
                  <path d={`M 0 60 C 40 60, 50 ${yEnd}, 100 ${yEnd}`} stroke={active ? b.color : 'rgba(255,255,255,0.10)'} strokeWidth={active ? 2 : 1} fill="none" />
                  {active && (
                    <circle r="2.6" fill={b.color}>
                      <animateMotion dur="0.9s" repeatCount="indefinite" path={`M 0 60 C 40 60, 50 ${yEnd}, 100 ${yEnd}`} />
                    </circle>
                  )}
                </g>
              );
            })}
          </svg>
        </div>
        {/* branches */}
        <div className="col-span-5 flex flex-col gap-2">
          {branches.map((b) => {
            const isActive = b.id === cur.cls;
            return (
              <div key={b.id} className={`px-3 py-2.5 rounded-lg border flex items-center gap-2.5 transition ${isActive ? 'bg-ink-800 scale-[1.02]' : 'opacity-50'}`} style={{ borderColor: isActive ? b.color : 'rgba(255,255,255,0.08)' }}>
                <span className="w-2 h-2 rounded-full" style={{ background: b.color, boxShadow: isActive ? `0 0 12px ${b.color}` : 'none' }}></span>
                <div className="flex-1">
                  <div className="text-[12.5px] text-paper-50 font-medium">{b.label}</div>
                  <div className="text-[10px] font-mono text-paper-300/50">{b.id === 'coop' ? 'auto · pôle clients' : b.id === 'delai' ? 'délai +5j · pôle dossiers' : 'escalade direction'}</div>
                </div>
                {isActive && <span className="text-[10px] font-mono" style={{ color: b.color }}>● ROUTÉ</span>}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* --- Showcase D — Dashboard --- */
function Dashboard() {
  const [tick, setTick] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setTick((t) => t + 1), 1400);
    return () => clearInterval(id);
  }, []);
  // gently animate numbers
  const sent = 247 + (tick % 7);
  const respRate = 72 + ((tick % 4));
  const escalated = 3 + ((tick % 3) === 0 ? 1 : 0);
  // bar chart values
  const bars = [42, 58, 51, 70, 64, 82, 76, 91, 88, 95];
  return (
    <div className="absolute inset-0 p-4 grid grid-cols-12 gap-3 content-start">
      <div className="col-span-4 rounded-lg bg-ink-800/60 border border-paper-300/5 p-3">
        <div className="text-[10px] font-mono uppercase tracking-wider text-paper-300/50">Relances · 7j</div>
        <div className="mt-1 font-display text-2xl text-paper-50">{sent}</div>
        <div className="text-[10.5px] text-emerald-400 mt-0.5">↑ +14% vs sem-1</div>
      </div>
      <div className="col-span-4 rounded-lg bg-ink-800/60 border border-paper-300/5 p-3">
        <div className="text-[10px] font-mono uppercase tracking-wider text-paper-300/50">Taux de réponse</div>
        <div className="mt-1 font-display text-2xl text-paper-50">{respRate}%</div>
        <div className="text-[10.5px] text-cy-400 mt-0.5">objectif 65%</div>
      </div>
      <div className="col-span-4 rounded-lg bg-ink-800/60 border border-paper-300/5 p-3">
        <div className="text-[10px] font-mono uppercase tracking-wider text-paper-300/50">À escalader</div>
        <div className="mt-1 font-display text-2xl text-paper-50">{escalated}</div>
        <div className="text-[10.5px] text-amber-400 mt-0.5">action requise</div>
      </div>
      <div className="col-span-12 rounded-lg bg-ink-800/60 border border-paper-300/5 p-3">
        <div className="flex items-center justify-between mb-2">
          <div className="text-[10px] font-mono uppercase tracking-wider text-paper-300/50">Activité — 10 derniers jours</div>
          <div className="text-[10px] font-mono text-cy-400">live</div>
        </div>
        <div className="flex items-end gap-1.5 h-20">
          {bars.map((v, i) => (
            <div key={i} className="flex-1 rounded-sm bg-gradient-to-t from-violet-600/30 via-violet-500/60 to-cy-400 transition-all" style={{ height: `${v + (i === (tick % 10) ? 8 : 0)}%` }}></div>
          ))}
        </div>
      </div>
      <div className="col-span-12 rounded-lg bg-ink-800/40 border border-paper-300/5 p-3">
        <div className="flex items-center justify-between text-[11px] text-paper-100/70">
          <div className="flex items-center gap-2"><span className="w-1.5 h-1.5 rounded-full bg-emerald-400 live-dot"></span> Workflow #07 · ok</div>
          <div className="font-mono text-paper-300/50">12s</div>
        </div>
      </div>
    </div>
  );
}

window.Showcase = Showcase;
