// AgentScreen — the canonical agent execution screen reused by all 5 apps.
(function () {
  const I = window.SIcon || {};
  const D = window.STUDIO_DATA;

  function Stat({ k, v, tone }) {
    const c = tone === "neg" ? "var(--coral)" : tone === "pos" ? "var(--emerald)" : "var(--fg-1)";
    return (
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5 }}>
        <span style={{ color: "var(--fg-2)" }}>{k}</span>
        <span style={{ fontFamily: "var(--font-mono)", color: c }}>{v}</span>
      </div>
    );
  }
  function Block({ icon, color, title, children }) {
    return (
      <div style={{ marginBottom: 18 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
          <span style={{ color }}>{icon}</span>
          <h3 style={{ margin: 0, fontSize: 13.5, fontFamily: "var(--font-sans)", fontWeight: 600, textTransform: "none" }}>{title}</h3>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>{children}</div>
      </div>
    );
  }

  function AgentScreen({ onBack }) {
    const NS = window.StudioDesignSystemUsegallSandbox_0c6109 || {};
    const { Dots, Button, Badge, Chip, ProgressBar, AgentCard, RunTimeline, RecommendationCard } = NS;
    // run state: "idle" | "running" | "done"
    const [run, setRun] = React.useState("idle");
    const [shown, setShown] = React.useState(0); // events revealed
    const [scenario, setScenario] = React.useState(0);

    const start = React.useCallback(() => { setRun("running"); setShown(0); }, []);
    const reset = React.useCallback(() => { setRun("idle"); setShown(0); }, []);

    React.useEffect(() => {
      if (run !== "running") return;
      if (shown >= D.events.length) {
        const t = setTimeout(() => setRun("done"), 500);
        return () => clearTimeout(t);
      }
      const t = setTimeout(() => setShown((n) => n + 1), 850);
      return () => clearTimeout(t);
    }, [run, shown]);

    const currentPhase = run === "done" ? 3 : shown > 0 ? D.events[Math.min(shown, D.events.length) - 1].phase : 0;
    const progress = run === "idle" ? 0 : Math.round((shown / D.events.length) * 100);
    const iconFor = (k) => { const C = I[k]; return C ? <C size={16} /> : null; };

    return (
      <div style={{ minHeight: "100vh", display: "flex", flexDirection: "column" }}>
        {/* header */}
        <header style={{ position: "sticky", top: 0, zIndex: 20, background: "rgba(11,16,32,.92)", backdropFilter: "blur(8px)", borderBottom: "1px solid var(--line-2)" }}>
          <div className="st-wrap st-wrap--wide" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 56 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <Button variant="ghost" size="sm" icon={I.back && <I.back size={16} />} onClick={onBack}>Hub</Button>
              <span style={{ width: 1, height: 22, background: "var(--line)" }} />
              <span style={{ height: 8, width: 8, borderRadius: 999, background: run === "running" ? "var(--warn)" : run === "done" ? "var(--ok)" : "var(--muted)" }} />
              <span style={{ fontSize: 14, fontWeight: 600 }}>{D.company.name}</span>
              <span className="st-tag" style={{ background: "var(--card-2)", color: "var(--fg-2)", fontFamily: "var(--font-mono)" }}>{D.company.rating}</span>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-3)" }}>RM {D.company.rm}</span>
              {run === "idle" && <Button variant="primary" size="sm" icon={I.play && <I.play size={13} />} onClick={start}>Iniciar análise</Button>}
              {run !== "idle" && <Button variant="secondary" size="sm" icon={I.reset && <I.reset size={13} />} onClick={reset}>Nova análise</Button>}
            </div>
          </div>
          <div style={{ height: 2, background: "var(--card-2)" }}>
            <div style={{ height: "100%", width: `${progress}%`, background: "var(--cyan)", transition: "width .7s cubic-bezier(.23,1,.32,1)" }} />
          </div>
        </header>

        {/* 3-column body */}
        <div className="st-wrap st-wrap--wide" style={{ flex: 1, padding: "18px 22px", display: "grid", gridTemplateColumns: "270px 1fr 360px", gap: 16, alignItems: "start" }}>
          {/* LEFT — context */}
          <aside className="st-card" style={{ padding: 16 }}>
            <Block icon={I.building && <I.building size={16} />} color="var(--cyan)" title="Perfil do cliente">
              <Stat k="Empresa" v={D.company.name.split(" ")[0]} />
              <Stat k="Setor" v={D.company.sector} />
              <Stat k="CFO" v={D.company.cfo} />
              <Stat k="Rating" v={D.company.rating} />
            </Block>
            <Block icon={I.banknote && <I.banknote size={16} />} color="var(--emerald)" title="Posição de caixa">
              <Stat k="Saldo atual" v={D.cash.balance} />
              <Stat k="Projeção D+7" v={D.cash.d7} tone="neg" />
              <Stat k="Projeção D+30" v={D.cash.d30} tone="pos" />
              <Stat k="Buffer mínimo" v={D.cash.minBuffer} />
            </Block>
            <Block icon={I.bank && <I.bank size={16} />} color="var(--teal)" title="Bancos">
              {D.banks.map((b) => (
                <div key={b.name} style={{ background: "var(--card-2)", border: "1px solid var(--line)", borderRadius: "var(--radius-sm)", padding: "8px 10px" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 5 }}>
                    <span style={{ width: 8, height: 8, borderRadius: 999, background: b.color }} />
                    <span style={{ fontSize: 12.5, fontWeight: 600 }}>{b.name}</span>
                  </div>
                  <Stat k="Saldo" v={b.balance} />
                  <Stat k="Taxa crédito" v={b.rate} />
                </div>
              ))}
            </Block>
            <Block icon={I.globe && <I.globe size={16} />} color="var(--teal)" title="Mercado">
              {D.market.map((m) => <Stat key={m.k} k={m.k} v={m.d ? `${m.v}  ${m.d}` : m.v} tone={m.tone} />)}
            </Block>
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                <span style={{ color: "var(--danger)" }}>{I.shield && <I.shield size={16} />}</span>
                <h3 style={{ margin: 0, fontSize: 13.5, fontFamily: "var(--font-sans)", fontWeight: 600, textTransform: "none" }}>Política de risco</h3>
              </div>
              {D.riskPolicy.map((r, i) => <p key={i} style={{ margin: "0 0 6px", fontSize: 11.5, color: i === 2 ? "var(--danger)" : "var(--fg-2)", lineHeight: 1.5 }}>• {r}</p>)}
            </div>
          </aside>

          {/* CENTER — question + run */}
          <main style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <div className="st-card">
              <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
                <span style={{ width: 34, height: 34, borderRadius: 999, background: "color-mix(in oklch, var(--cyan) 18%, transparent)", color: "var(--cyan)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                  {I.dollar && <I.dollar size={16} />}
                </span>
                <div>
                  <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 4 }}>
                    <span className="st-kicker" style={{ fontSize: 10.5 }}>Pergunta do CFO</span>
                    <span style={{ fontSize: 12, color: "var(--fg-3)" }}>— {D.company.cfo}</span>
                  </div>
                  <p style={{ margin: 0, fontSize: 15, color: "var(--fg-1)", lineHeight: 1.55, fontStyle: "italic" }}>"{D.question}"</p>
                </div>
              </div>
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 14 }}>
                {D.suggestions.map((s, i) => <Chip key={i} active={i === scenario} onClick={() => setScenario(i)}>{s}</Chip>)}
              </div>
            </div>

            {run === "idle" ? (
              <div className="st-card" style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "48px 24px", textAlign: "center", gap: 16 }}>
                <Dots size="lg" />
                <p style={{ margin: 0, color: "var(--fg-2)", fontSize: 14, maxWidth: 360 }}>
                  Cinco especialistas consultados em paralelo, com aprovação humana quando o covenant exige.
                  Clique para iniciar a análise.
                </p>
                <Button variant="primary" icon={I.play && <I.play size={13} />} onClick={start}>Iniciar análise</Button>
              </div>
            ) : (
              <React.Fragment>
                <ProgressBar phases={D.phases} current={currentPhase} />
                <RunTimeline status={run} onReset={reset} title="Execução · análise de hedge cambial">
                  {D.events.slice(0, shown).map((e, idx) => {
                    const isLast = idx === shown - 1;
                    const status = run === "done" ? (e.status || "done") : isLast ? "running" : (e.status || "done");
                    return (
                      <div key={e.id} className="st-enter">
                        <AgentCard name={e.name} color={e.color} icon={iconFor(e.icon)} status={status} message={e.msg} />
                      </div>
                    );
                  })}
                </RunTimeline>
              </React.Fragment>
            )}
          </main>

          {/* RIGHT — recommendation */}
          <aside>
            {run === "done" ? (
              <RecommendationCard
                action={D.recommendation.action}
                summary={D.recommendation.summary}
                confidence={D.recommendation.confidence}
                metrics={D.recommendation.metrics}
                nextStep={D.recommendation.nextStep}
              />
            ) : (
              <div className="st-card" style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "56px 20px", textAlign: "center", gap: 12, minHeight: 280 }}>
                <span style={{ width: 40, height: 40, borderRadius: 999, background: "var(--card-2)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--fg-3)" }}>
                  {I.chart && <I.chart size={18} />}
                </span>
                <p style={{ margin: 0, fontSize: 12.5, color: "var(--fg-2)" }}>
                  {run === "running" ? "Aguardando conclusão dos especialistas…" : "Inicie a análise para ver a recomendação ao CFO."}
                </p>
                {run === "running" && <Badge status="running">Processando</Badge>}
              </div>
            )}
          </aside>
        </div>
      </div>
    );
  }
  window.AgentScreen = AgentScreen;
})();
