// ===== CENA 3 (14–22s) — 5 AGENTES · CENA 4 (22–28s) — VEREDICTO =====

// ---------- CENA 3 ----------

const AGENT_THOUGHTS = [
  {
    key:   "analyst",
    emoji: "🎯",
    name:  "Analista",
    model: "sonnet-4.5",
    border: C.lime,
    lines: [
      "objeto: equipamentos de TI · perfil compatível",
      "concorrência estimada: 6 empresas locais",
      "match 89% · participe.",
    ],
  },
  {
    key:   "legal",
    emoji: "⚖️",
    name:  "Jurídico",
    model: "sonnet-4.5",
    border: C.stop,
    lines: [
      "lendo 84 páginas…",
      "cláusula 4.3 § II — exigência abusiva",
      "minuta de impugnação pronta · TCU AC 1.234/2021",
    ],
  },
  {
    key:   "finance",
    emoji: "💰",
    name:  "Financeiro",
    model: "haiku-4.5",
    border: C.go,
    lines: [
      "BDI: 22,4% · margem 18% sobre custo",
      "fluxo de caixa: 47 dias até o 1º pagto",
      "preço-piso sugerido: R$ 312.500",
    ],
  },
  {
    key:   "docs",
    emoji: "📋",
    name:  "Documentalista",
    model: "haiku-4.5",
    border: C.info,
    lines: [
      "validando 6 certidões…",
      "CND federal: vence em 18 dias · ok",
      "5/6 documentos válidos · 1 a emitir",
    ],
  },
  {
    key:   "coach",
    emoji: "🎓",
    name:  "Coach",
    model: "sonnet-4.5",
    border: C.lime,
    lines: [
      "traduzindo pro linguajar humano…",
      "vale a pena · margem boa, sem pegadinha",
      "vamos? você tá pronto.",
    ],
  },
];

function AgentReasoningCard({ agent, localTime, startAt, isLast }) {
  // Each agent: starts at startAt, types each line over 1.0s with 0.2s gap
  const t = localTime - startAt;
  const visible = t > -0.2;

  // Entry: opacity + slide
  const entryT = Math.max(0, Math.min(1, (t + 0.2) / 0.5));
  const eased = Easing.easeOutCubic(entryT);

  // Lines reveal one by one
  const linePerDur = 1.0;
  const lineGap = 0.15;
  const lineCount = agent.lines.length;
  const finishAt = lineCount * (linePerDur + lineGap);
  const isWorking = t >= 0 && t < finishAt;
  const isDone = t >= finishAt;

  const lines = agent.lines.map((line, i) => {
    const lineStart = i * (linePerDur + lineGap);
    const lineT = t - lineStart;
    if (lineT <= 0) return { text: "", done: false, show: false };
    const charsTotal = line.length;
    const revealDur = Math.min(linePerDur * 0.85, charsTotal * 0.018);
    const chars = Math.floor(Math.min(1, lineT / revealDur) * charsTotal);
    return { text: line.slice(0, chars), done: lineT >= revealDur, show: true, full: line };
  });

  return (
    <article style={{
      borderRadius: 16,
      border: `1px solid ${isDone ? agent.border + "aa" : C.lineDk}`,
      background: isDone ? `${agent.border}10` : `${C.ink2}cc`,
      padding: "20px 24px",
      opacity: visible ? eased : 0,
      transform: `translateX(${(1 - eased) * 20}px)`,
      transition: "border-color 200ms, background 200ms",
      display: "flex", flexDirection: "column",
      minHeight: 134,
    }}>
      <header style={{ display: "flex", alignItems: "center", gap: 14 }}>
        <div style={{
          width: 44, height: 44, borderRadius: 12,
          background: `${C.ink}aa`,
          border: `1px solid ${agent.border}55`,
          display: "grid", placeItems: "center", fontSize: 22,
        }}>{agent.emoji}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: F.display, fontSize: 22, color: C.paper, letterSpacing: "-0.01em" }}>
            {agent.name}
          </div>
          <div style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: C.stone3, marginTop: 2 }}>
            {agent.model}
          </div>
        </div>
        <div style={{
          fontFamily: F.mono, fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase",
          padding: "4px 10px", borderRadius: 999,
          background: isDone ? `${agent.border}25` : `${C.lime}18`,
          color: isDone ? agent.border : C.lime,
          display: "inline-flex", alignItems: "center", gap: 6,
        }}>
          <span style={{
            width: 6, height: 6, borderRadius: 999,
            background: isDone ? agent.border : C.lime,
            animation: isWorking ? "pulseDot 900ms infinite" : "none",
            boxShadow: isWorking ? `0 0 8px ${C.lime}` : "none",
          }} />
          {isDone ? "concluído" : "pensando"}
        </div>
      </header>

      <div style={{ marginTop: 14, fontFamily: F.mono, fontSize: 14, lineHeight: 1.6, color: "#C8D0E8" }}>
        {lines.map((l, i) => l.show ? (
          <div key={i} style={{ marginBottom: 4 }}>
            <span style={{ color: C.stone3 }}>›&nbsp;</span>
            <span style={{ color: l.done ? "#D6DBEC" : C.paper }}>
              {l.text}
              {!l.done && <span className="cursor-blink" style={{
                display: "inline-block", width: 7, height: 14, marginLeft: 2,
                background: C.lime, verticalAlign: "middle",
                animation: "blink 800ms steps(2) infinite",
              }} />}
            </span>
          </div>
        ) : null)}
      </div>
    </article>
  );
}

function SceneAgents() {
  const { localTime, duration } = useSprite();
  const exitT = Math.max(0, duration - 0.5);
  const exitOpacity = localTime > exitT ? 1 - (localTime - exitT) / 0.5 : 1;

  // Edital paper enters at 0, then 5 agents trigger at staggered times
  const agentStarts = [0.6, 1.0, 1.4, 1.8, 2.2];

  return (
    <div style={{
      position: "absolute", inset: 0,
      background: `linear-gradient(180deg, ${C.ink} 0%, #0c1a36 100%)`,
      color: C.paper, opacity: exitOpacity, overflow: "hidden",
    }}>
      {/* Grain */}
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage: "radial-gradient(rgba(255,255,255,0.025) 1px, transparent 1px)",
        backgroundSize: "5px 5px", pointerEvents: "none",
      }} />

      {/* Header */}
      <div style={{ position: "absolute", left: 96, top: 110, right: 96 }}>
        <div style={{ fontFamily: F.mono, fontSize: 13, letterSpacing: "0.24em", textTransform: "uppercase", color: C.lime, marginBottom: 14 }}>
          <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 999, background: C.lime, marginRight: 12, verticalAlign: "middle", boxShadow: `0 0 10px ${C.lime}` }} />
          Agentes 2–6 / 6 · trabalho em paralelo
        </div>
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 40 }}>
          <h1 style={{ fontFamily: F.display, fontSize: 76, lineHeight: 0.95, margin: 0, letterSpacing: "-0.03em" }}>
            5 cérebros lendo<br />o mesmo edital<span style={{ color: C.lime }}>.</span>
          </h1>
          <div style={{ textAlign: "right", paddingBottom: 8 }}>
            <div style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: C.stone3 }}>Edital em análise</div>
            <div style={{ fontFamily: F.mono, fontSize: 16, color: C.paper, marginTop: 4 }}>EDT-2026-04-A1B2</div>
            <div style={{ fontFamily: F.sans, fontSize: 15, color: "#A8B2CC", marginTop: 2 }}>Pref. Campinas · SP</div>
          </div>
        </div>
      </div>

      {/* Left: edital paper, tilted slightly */}
      <div style={{
        position: "absolute", left: 96, top: 320,
        width: 460, height: 640,
        background: "#FAFAF7",
        borderRadius: 8,
        boxShadow: "0 30px 80px -10px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.05)",
        transform: `rotate(-2.2deg) translateY(${interpolate([0, 0.7], [40, 0], Easing.easeOutCubic)(localTime)}px)`,
        opacity: Math.min(1, localTime / 0.5),
        overflow: "hidden",
      }}>
        {/* Header bar */}
        <div style={{
          padding: "22px 32px 18px",
          borderBottom: "1px solid #E5E3DA",
          background: "#F0EFE8",
        }}>
          <div style={{ fontFamily: F.mono, fontSize: 10, letterSpacing: "0.18em", textTransform: "uppercase", color: "#6B6B6B" }}>
            Prefeitura Municipal de Campinas
          </div>
          <div style={{ fontFamily: F.display, fontSize: 22, color: "#0F1E3A", marginTop: 8, letterSpacing: "-0.01em" }}>
            Pregão Eletrônico nº 047/2026
          </div>
          <div style={{ fontFamily: F.mono, fontSize: 12, color: "#2C2C2C", marginTop: 6 }}>
            Aquisição de equipamentos de TI
          </div>
        </div>
        {/* Body — page text simulation */}
        <div style={{ padding: "28px 32px", fontFamily: F.sans, fontSize: 11, lineHeight: 1.55, color: "#2C2C2C" }}>
          <div style={{ fontFamily: F.display, fontSize: 16, marginBottom: 10, color: "#0F1E3A" }}>1. DO OBJETO</div>
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} style={{ height: 6, background: "#E5E3DA", borderRadius: 2, marginBottom: 6, width: `${94 - (i % 3) * 8}%` }} />
          ))}
          <div style={{ fontFamily: F.display, fontSize: 16, margin: "22px 0 10px", color: "#0F1E3A" }}>2. DA HABILITAÇÃO</div>
          {Array.from({ length: 5 }).map((_, i) => (
            <div key={i} style={{ height: 6, background: "#E5E3DA", borderRadius: 2, marginBottom: 6, width: `${88 - (i % 4) * 6}%` }} />
          ))}
          <div style={{ fontFamily: F.display, fontSize: 16, margin: "22px 0 10px", color: "#0F1E3A" }}>4. CLÁUSULA 4.3</div>
          {/* Cláusula 4.3 highlighted by Jurídico */}
          <div style={{
            position: "relative",
            background: localTime > 1.4 ? `${C.stop}18` : "transparent",
            border: localTime > 1.4 ? `1px dashed ${C.stop}` : "1px dashed transparent",
            padding: "8px 10px", marginLeft: -10, marginRight: -10, borderRadius: 4,
            transition: "all 600ms",
          }}>
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} style={{ height: 6, background: "#E5E3DA", borderRadius: 2, marginBottom: 6, width: `${82 - (i % 3) * 5}%` }} />
            ))}
            {localTime > 1.8 && (
              <div style={{
                position: "absolute", right: -8, top: -10,
                background: C.stop, color: C.paper,
                fontFamily: F.mono, fontSize: 9, letterSpacing: "0.16em", textTransform: "uppercase",
                padding: "4px 8px", borderRadius: 4,
                animation: "popCount 350ms cubic-bezier(0.18, 0.89, 0.32, 1.28)",
              }}>
                abusiva
              </div>
            )}
          </div>
        </div>
        {/* Page count footer */}
        <div style={{
          position: "absolute", bottom: 16, left: 32, right: 32,
          display: "flex", justifyContent: "space-between",
          fontFamily: F.mono, fontSize: 10, color: "#9B9B9B",
        }}>
          <span>p. 1 de 84</span><span>Pleita · 2026</span>
        </div>
      </div>

      {/* Right: 5 agent cards in 2 columns */}
      <div style={{
        position: "absolute", left: 620, top: 320, right: 96,
        display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14,
        gridAutoRows: "min-content",
      }}>
        {AGENT_THOUGHTS.map((a, i) => (
          <div key={a.key} style={ i === 4 ? { gridColumn: "1 / -1" } : {} }>
            <AgentReasoningCard
              agent={a}
              localTime={localTime}
              startAt={agentStarts[i]}
              isLast={i === 4}
            />
          </div>
        ))}
      </div>

      <style>{`
        @keyframes blink   { 0%, 50% { opacity: 1; } 50.01%, 100% { opacity: 0; } }
        @keyframes pulseDot{ 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.4; transform: scale(0.85); } }
      `}</style>
    </div>
  );
}

// ---------- CENA 4 — VEREDICTO ----------

function SceneVerdict() {
  const { localTime, duration } = useSprite();
  const exitT = Math.max(0, duration - 0.5);
  const exitOpacity = localTime > exitT ? 1 - (localTime - exitT) / 0.5 : 1;

  // Verdict pulse: scale up then settle
  const verdictScale = interpolate([0, 0.45, 0.7], [0.3, 1.08, 1], [Easing.easeOutBack, Easing.easeOutCubic])(localTime);
  const verdictOpacity = Math.min(1, localTime / 0.3);

  // Stats reveal at 0.9s
  const statsOpacity = Math.min(1, Math.max(0, (localTime - 0.9) / 0.5));
  const statsY = (1 - Easing.easeOutCubic(Math.min(1, Math.max(0, (localTime - 0.9) / 0.5)))) * 20;

  // Docs reveal staggered after 1.8s
  const docs = [
    { name: "Cartão CNPJ",                 ok: true },
    { name: "Certidão Federal",            ok: true },
    { name: "Certidão Estadual",           ok: true },
    { name: "Certidão Municipal",          ok: true },
    { name: "FGTS",                        ok: true },
    { name: "Trabalhista",                 ok: true },
  ];

  return (
    <div style={{
      position: "absolute", inset: 0,
      background: `radial-gradient(circle at 50% 40%, #1a2f5c 0%, ${C.ink} 60%, #06112a 100%)`,
      color: C.paper, opacity: exitOpacity, overflow: "hidden",
    }}>
      {/* Grain */}
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage: "radial-gradient(rgba(255,255,255,0.025) 1px, transparent 1px)",
        backgroundSize: "5px 5px", pointerEvents: "none",
      }} />

      {/* Pulsing rings */}
      <div style={{
        position: "absolute", left: "50%", top: 280,
        transform: "translateX(-50%)",
        width: 460, height: 460,
        opacity: verdictOpacity * 0.5,
      }}>
        {[0, 0.5, 1].map((delay, i) => (
          <div key={i} style={{
            position: "absolute", inset: 0,
            borderRadius: "50%",
            border: `2px solid ${C.go}`,
            animation: `ringPulse 2.4s ${delay}s infinite ease-out`,
            opacity: 0,
          }} />
        ))}
      </div>

      {/* Massive verdict circle */}
      <div style={{
        position: "absolute", left: "50%", top: 320,
        transform: `translateX(-50%) scale(${verdictScale})`,
        opacity: verdictOpacity,
      }}>
        <div style={{
          width: 380, height: 380, borderRadius: "50%",
          background: `radial-gradient(circle at 35% 30%, ${C.go} 0%, #0d5e2e 100%)`,
          boxShadow: `0 0 80px ${C.go}66, inset 0 -20px 40px rgba(0,0,0,0.3)`,
          display: "grid", placeItems: "center", textAlign: "center",
        }}>
          <div>
            <div style={{ fontSize: 96, lineHeight: 1 }}>🟢</div>
            <div style={{
              fontFamily: F.display, fontSize: 64, color: C.paper, marginTop: 8,
              letterSpacing: "-0.03em", lineHeight: 0.95,
            }}>PARTICIPE</div>
          </div>
        </div>
      </div>

      {/* Eyebrow + verdict explainer top */}
      <div style={{ position: "absolute", left: "50%", top: 96, transform: "translateX(-50%)", textAlign: "center" }}>
        <div style={{ fontFamily: F.mono, fontSize: 13, letterSpacing: "0.24em", textTransform: "uppercase", color: C.lime, marginBottom: 14 }}>
          <span style={{ display: "inline-block", width: 8, height: 8, borderRadius: 999, background: C.lime, marginRight: 12, verticalAlign: "middle", boxShadow: `0 0 10px ${C.lime}` }} />
          Veredicto · em 2,3 segundos
        </div>
        <div style={{ fontFamily: F.display, fontSize: 56, letterSpacing: "-0.02em", lineHeight: 1 }}>
          Tudo conferido. Você tem chance real<span style={{ color: C.lime }}>.</span>
        </div>
      </div>

      {/* Score + margin chips · left and right of the circle */}
      <div style={{
        position: "absolute", left: 220, top: 460,
        opacity: statsOpacity, transform: `translateY(${statsY}px)`,
      }}>
        <StatCard label="Score" value="89" valueColor={C.lime} sub="match com seu perfil" />
        <div style={{ height: 14 }} />
        <StatCard label="Margem" value="18%" valueColor={C.paper} sub="sobre o custo" />
      </div>

      <div style={{
        position: "absolute", right: 220, top: 460,
        opacity: statsOpacity, transform: `translateY(${statsY}px)`,
        textAlign: "right",
      }}>
        <StatCard label="Valor estimado" value="R$ 1,2M" valueColor={C.paper} sub="contrato anual" align="right" />
        <div style={{ height: 14 }} />
        <StatCard label="Concorrência" value="6 empresas" valueColor={C.paper} sub="estimadas no certame" align="right" />
      </div>

      {/* Cofre · documentos */}
      <div style={{
        position: "absolute", left: "50%", bottom: 190,
        transform: "translateX(-50%)",
        textAlign: "center",
        opacity: Math.min(1, Math.max(0, (localTime - 1.8) / 0.5)),
      }}>
        <div style={{ fontFamily: F.mono, fontSize: 12, letterSpacing: "0.20em", textTransform: "uppercase", color: C.stone3, marginBottom: 12 }}>
          Cofre · documentos prontos
        </div>
        <div style={{ display: "flex", gap: 10, justifyContent: "center" }}>
          {docs.map((d, i) => {
            const at = 2.0 + i * 0.12;
            const show = localTime > at;
            const tt = Math.max(0, Math.min(1, (localTime - at) / 0.3));
            return (
              <div key={d.name} style={{
                padding: "10px 16px", borderRadius: 999,
                background: `${C.go}1a`, border: `1px solid ${C.go}55`,
                opacity: show ? 1 : 0,
                transform: `translateY(${(1 - Easing.easeOutBack(tt)) * 10}px)`,
                display: "inline-flex", alignItems: "center", gap: 8,
                whiteSpace: "nowrap",
              }}>
                <span style={{ color: C.go, fontSize: 14 }}>✓</span>
                <span style={{ fontFamily: F.mono, fontSize: 13, color: C.paper, letterSpacing: "0.04em" }}>{d.name}</span>
              </div>
            );
          })}
        </div>
        <div style={{
          marginTop: 18,
          fontFamily: F.sans, fontSize: 18, color: "#A8B2CC",
          opacity: Math.min(1, Math.max(0, (localTime - 3.2) / 0.5)),
        }}>
          A Pleita já preparou tudo. <span style={{ color: C.paper }}>Você só precisa dizer "vai".</span>
        </div>
      </div>

      <style>{`
        @keyframes ringPulse {
          0%   { transform: scale(0.6); opacity: 0.6; }
          80%  { transform: scale(1.3); opacity: 0; }
          100% { transform: scale(1.3); opacity: 0; }
        }
      `}</style>
    </div>
  );
}

function StatCard({ label, value, valueColor = C.paper, sub, align = "left" }) {
  return (
    <div style={{
      padding: "20px 26px",
      borderRadius: 14,
      background: `${C.ink2}cc`,
      border: `1px solid ${C.lineDk}`,
      backdropFilter: "blur(8px)",
      minWidth: 240,
      textAlign: align,
    }}>
      <div style={{ fontFamily: F.mono, fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: C.stone3 }}>
        {label}
      </div>
      <div style={{ fontFamily: F.display, fontSize: 52, lineHeight: 1, color: valueColor, marginTop: 6, letterSpacing: "-0.02em", fontVariantNumeric: "tabular-nums" }}>
        {value}
      </div>
      <div style={{ fontFamily: F.sans, fontSize: 14, color: "#A8B2CC", marginTop: 6 }}>{sub}</div>
    </div>
  );
}

Object.assign(window, { SceneAgents, SceneVerdict });
