// ===== Análise · Comitê em tempo real (WOW) =====

// Sequência de eventos por agente (terminal-style logs)
const AGENT_LOGS = {
  hunter: [
    { t: 0,    type: "info", text: "Iniciando varredura PNCP-SP, PNCP-MG, ComprasNet…" },
    { t: 280,  type: "info", text: "Lendo edital · 84 páginas · 12.4 MB" },
    { t: 620,  type: "ok",   text: "Modalidade Pregão Eletrônico · LC 14.133/21" },
    { t: 920,  type: "ok",   text: "Objeto extraído: gêneros alimentícios · lote 3" },
    { t: 1180, type: "ok",   text: "Match 89/100 — perfil compatível" },
  ],
  analyst: [
    { t: 400,  type: "info", text: "Cruzando histórico do órgão · 312 licitações" },
    { t: 720,  type: "info", text: "Preço médio vencedor: R$ 1,82/un · σ ±8%" },
    { t: 1040, type: "warn", text: "3 concorrentes recorrentes mapeados" },
    { t: 1320, type: "ok",   text: "Win probability calculada: 34%" },
  ],
  legal: [
    { t: 800,  type: "info", text: "Analisando 47 cláusulas · LC 123/06 · TCU" },
    { t: 1100, type: "warn", text: "Cláusula §4º — exigência ME/EPP atípica" },
    { t: 1380, type: "err",  text: "Risco de inabilitação · sugerir impugnação" },
    { t: 1620, type: "ok",   text: "Peça de impugnação gerada (rascunho)" },
  ],
  finance: [
    { t: 800,  type: "info", text: "Calculando BDI · CT 2.480/24 · INCC" },
    { t: 1080, type: "info", text: "Margem alvo: 18% · custo fixo R$ 0,42/un" },
    { t: 1340, type: "ok",   text: "Preço sugerido: R$ 1,78/un (-2.2% mediana)" },
    { t: 1580, type: "ok",   text: "Fluxo de caixa OK · pagamento médio 28d" },
  ],
  docs: [
    { t: 1200, type: "info", text: "Checando cofre · 12 certidões cadastradas" },
    { t: 1480, type: "ok",   text: "FGTS/CRF · CNDT · Receita Federal · OK" },
    { t: 1720, type: "warn", text: "CND Federal vence em 8 dias — renovar" },
    { t: 1960, type: "err",  text: "Balanço 2025 não encontrado · solicitar contador" },
  ],
  coach: [
    { t: 1200, type: "info", text: "Sintetizando análise para o Comitê…" },
    { t: 1620, type: "info", text: "Traduzindo achados em PT-BR claro" },
    { t: 1900, type: "ok",   text: "5 ações priorizadas para você" },
    { t: 2140, type: "ok",   text: "Veredito: ⚠️ regularize e participe" },
  ],
};

const LOG_COLORS = {
  info: "text-pleita-stone-2", ok: "text-verdict-go",
  warn: "text-verdict-caution", err: "text-verdict-stop",
};
const LOG_GLYPHS = { info: "→", ok: "✓", warn: "⚠", err: "✕" };

function AgentTerminal({ agentKey, elapsed, isDone }) {
  const a = AGENTS[agentKey];
  const logs = AGENT_LOGS[agentKey] || [];
  const visible = logs.filter((l) => l.t <= elapsed);
  const current = visible[visible.length - 1];
  const status = !visible.length ? "aguardando" : isDone ? "concluído" : "analisando";

  const accent = {
    hunter:  "#2563EB", analyst: "#7C3AED", legal: "#B45309",
    finance: "#0891B2", docs:    "#059669", coach: "#DC2626",
  }[agentKey];

  return (
    <article
      className="rounded-[10px] bg-surface-card border border-pleita-line/60 overflow-hidden flex flex-col"
      style={{ borderTopWidth: 3, borderTopColor: accent }}
    >
      <header className="flex items-center justify-between px-4 py-3 border-b border-pleita-line/60">
        <div className="flex items-center gap-2.5 min-w-0">
          <div className="size-8 rounded-md grid place-items-center text-lg" style={{ background: `${accent}18` }}>{a.emoji}</div>
          <div className="min-w-0">
            <div className="font-display text-sm text-pleita-ink leading-tight truncate">{a.name}</div>
            <div className="pl-num text-[9px] uppercase tracking-wider text-pleita-stone-2">{a.model}</div>
          </div>
        </div>
        <span
          className="pl-num text-[9px] uppercase tracking-wider px-2 py-0.5 rounded-full font-semibold"
          style={{
            background: status === "concluído" ? "rgb(34 197 94 / .15)" : status === "analisando" ? `${accent}22` : "rgb(var(--pleita-line) / .5)",
            color: status === "concluído" ? "rgb(22 163 74)" : status === "analisando" ? accent : "rgb(var(--pleita-stone-2))",
          }}
        >
          {status === "concluído" ? "✓ concluído" : status === "analisando" ? "analisando…" : "aguardando"}
        </span>
      </header>
      <div
        className="flex-1 pl-num text-[10.5px] leading-[1.5] px-3 py-2.5 min-h-[112px] font-mono"
        style={{ background: "#020810", color: "#9CA3AF" }}
      >
        {!visible.length && <div className="text-pleita-stone-2/60">$ waiting…</div>}
        {visible.map((l, i) => (
          <div key={i} className="flex gap-1.5">
            <span className={LOG_COLORS[l.type]}>{LOG_GLYPHS[l.type]}</span>
            <span className={i === visible.length - 1 && !isDone ? "text-pleita-paper" : ""} style={{ color: i === visible.length - 1 && !isDone ? "#E5E7EB" : undefined }}>
              {l.text}
              {i === visible.length - 1 && !isDone && <span className="ml-0.5 inline-block w-1.5 h-3 align-middle animate-pulse" style={{ background: accent }} />}
            </span>
          </div>
        ))}
      </div>
      <div className="h-1 bg-pleita-line/40">
        <div className="h-full transition-all" style={{ width: `${Math.min(100, (visible.length / Math.max(1, logs.length)) * 100)}%`, background: accent }} />
      </div>
    </article>
  );
}

function GaugeCircle({ value, label, size = 140 }) {
  const r = size / 2 - 10;
  const c = 2 * Math.PI * r;
  const off = c - (value / 100) * c;
  return (
    <div className="relative" style={{ width: size, height: size }}>
      <svg viewBox={`0 0 ${size} ${size}`} className="-rotate-90">
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="rgb(var(--pleita-line))" strokeWidth="8" />
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="rgb(var(--pleita-lime))" strokeWidth="8" strokeLinecap="round" strokeDasharray={c} strokeDashoffset={off} style={{ transition: "stroke-dashoffset 300ms" }} />
      </svg>
      <div className="absolute inset-0 grid place-items-center text-center">
        <div>
          <div className="pl-num font-semibold text-3xl text-pleita-ink leading-none">{Math.round(value)}<span className="text-base text-pleita-stone-2">%</span></div>
          {label && <div className="pl-num text-[9px] uppercase tracking-wider text-pleita-stone-2 mt-1">{label}</div>}
        </div>
      </div>
    </div>
  );
}

function ScoreSemiGauge({ value, max = 100, size = 220 }) {
  const w = size, h = size * 0.6;
  const r = w / 2 - 16;
  const cx = w / 2, cy = h - 8;
  const start = Math.PI, end = 0;
  const pct = value / max;
  const ang = start - (start - end) * pct;
  const px = cx + r * Math.cos(ang);
  const py = cy + r * Math.sin(ang) * -1;
  const arcPath = `M ${cx - r} ${cy} A ${r} ${r} 0 0 1 ${cx + r} ${cy}`;
  const filledPath = `M ${cx - r} ${cy} A ${r} ${r} 0 0 1 ${px} ${cy - r * Math.sin(start - ang)}`;
  // simpler: render as stroke-dasharray
  const arcLen = Math.PI * r;
  const off = arcLen - pct * arcLen;
  return (
    <div className="relative" style={{ width: w, height: h }}>
      <svg viewBox={`0 0 ${w} ${h}`} className="w-full h-full">
        <path d={arcPath} fill="none" stroke="rgb(var(--pleita-line))" strokeWidth="14" strokeLinecap="round" />
        <path d={arcPath} fill="none" stroke="rgb(var(--pleita-lime))" strokeWidth="14" strokeLinecap="round" strokeDasharray={arcLen} strokeDashoffset={off} style={{ transition: "stroke-dashoffset 500ms" }} />
      </svg>
      <div className="absolute inset-0 flex items-end justify-center pb-1">
        <div className="text-center">
          <div className="pl-num font-semibold text-pleita-ink leading-none" style={{ fontSize: size * 0.22 }}>{value}<span className="text-pleita-stone-2" style={{ fontSize: size * 0.1 }}>/{max}</span></div>
          <div className="pl-num text-[10px] uppercase tracking-wider text-pleita-stone-2 mt-1">Score de Prontidão</div>
        </div>
      </div>
    </div>
  );
}

// ----- Fase B: Comitê live -----

function PhaseCommittee({ elapsed }) {
  const overall = Math.min(100, (elapsed / 2200) * 100);
  const agentOrder = ["hunter", "analyst", "legal", "finance", "docs", "coach"];
  const isDone = (k) => {
    const logs = AGENT_LOGS[k];
    return elapsed >= logs[logs.length - 1].t + 200;
  };

  return (
    <div className="min-h-full text-pleita-paper" style={{ background: "rgb(var(--pleita-ink))" }}>
      <div className="max-w-7xl mx-auto px-6 md:px-10 py-10">
        <header className="text-center mb-10">
          <div className="relative inline-grid place-items-center mb-5">
            <div className="absolute size-24 rounded-full border-2 border-pleita-lime/30 animate-[spin_4s_linear_infinite]" style={{ borderRightColor: "transparent", borderBottomColor: "transparent" }} />
            <div className="absolute size-32 rounded-full border border-pleita-paper/10 animate-[spin_8s_linear_infinite_reverse]" style={{ borderTopColor: "transparent" }} />
            <div className="size-16 rounded-[14px] bg-pleita-lime grid place-items-center">
              <svg viewBox="0 0 24 24" className="size-7"><path d="M8 5 L19 12 L8 19 Z" fill="rgb(var(--pleita-ink))" /></svg>
            </div>
          </div>
          <h1 className="font-display text-3xl md:text-4xl text-pleita-paper">Comitê analisando<span className="text-pleita-lime">.</span></h1>
          <p className="text-sm text-pleita-paper/70 mt-2">Orquestrando 6 agentes especializados em paralelo · LGPD: dados isolados por tenant</p>
        </header>

        <div className="grid grid-cols-12 gap-6">
          <div className="col-span-12 md:col-span-9 grid sm:grid-cols-2 lg:grid-cols-3 gap-3">
            {agentOrder.map((k) => <AgentTerminal key={k} agentKey={k} elapsed={elapsed} isDone={isDone(k)} />)}
          </div>
          <aside className="col-span-12 md:col-span-3">
            <div className="rounded-[10px] p-6 border border-pleita-paper/10" style={{ background: "rgb(var(--pleita-ink-2))" }}>
              <div className="grid place-items-center">
                <GaugeCircle value={overall} label="overall" />
              </div>
              <div className="mt-6 space-y-2">
                {agentOrder.map((k) => {
                  const a = AGENTS[k];
                  const logs = AGENT_LOGS[k];
                  const v = Math.min(100, (Math.max(0, logs.filter(l => l.t <= elapsed).length) / logs.length) * 100);
                  return (
                    <div key={k} className="flex items-center gap-2">
                      <span className="text-sm w-5 text-center">{a.emoji}</span>
                      <span className="text-xs text-pleita-paper/80 flex-1 truncate">{a.name}</span>
                      <div className="w-16 h-1 rounded-full overflow-hidden bg-pleita-paper/10">
                        <div className="h-full bg-pleita-lime transition-all" style={{ width: `${v}%` }} />
                      </div>
                      <span className="pl-num text-[10px] text-pleita-paper/60 w-7 text-right">{Math.round(v)}%</span>
                    </div>
                  );
                })}
              </div>
              <div className="mt-5 pt-5 border-t border-pleita-paper/10 pl-num text-[10px] uppercase tracking-wider text-pleita-paper/50">
                Decorrido: <span className="text-pleita-lime">{(elapsed / 1000).toFixed(1)}s</span>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}

// ----- Fase A: Upload -----
function PhaseUpload({ onStart }) {
  const [ready, setReady] = React.useState({ edital: false, contrato: false, cnpj: false });
  const allReady = ready.edital && ready.contrato && ready.cnpj;
  return (
    <div className="min-h-full grid place-items-center" style={{ background: "rgb(var(--pleita-ink))" }}>
      <div className="max-w-2xl w-full px-6 md:px-10 py-12">
        <div className="text-center mb-8">
          <div className="size-12 rounded-[12px] bg-pleita-lime grid place-items-center mx-auto mb-4">
            <svg viewBox="0 0 24 24" className="size-5"><path d="M8 5 L19 12 L8 19 Z" fill="rgb(var(--pleita-ink))" /></svg>
          </div>
          <h1 className="font-display text-3xl text-pleita-paper">Envie o edital para o Comitê analisar<span className="text-pleita-lime">.</span></h1>
          <p className="text-sm text-pleita-paper/70 mt-2">Análise em ~3,4 segundos · LGPD: dados isolados por tenant</p>
        </div>
        <div className="space-y-3">
          {[
            { k: "edital",    ico: "📄", t: "Edital da Licitação", h: "PDF · até 50MB" },
            { k: "contrato",  ico: "📋", t: "Contrato Social",     h: "PDF · cláusulas e capital social" },
          ].map((c) => (
            <button
              key={c.k}
              onClick={() => setReady((r) => ({ ...r, [c.k]: !r[c.k] }))}
              className={`w-full rounded-[10px] border-2 border-dashed p-5 text-left flex items-center gap-4 transition-colors ${ready[c.k] ? "border-pleita-lime bg-pleita-lime/10" : "border-pleita-paper/20 hover:border-pleita-paper/40 bg-pleita-ink-2"}`}
            >
              <div className="size-12 rounded-md grid place-items-center text-2xl" style={{ background: ready[c.k] ? "rgb(159 232 112 / .3)" : "rgb(255 255 255 / .05)" }}>{c.ico}</div>
              <div className="flex-1">
                <div className="font-display text-base text-pleita-paper">{c.t}</div>
                <div className="pl-num text-[11px] text-pleita-paper/60">{ready[c.k] ? "✓ exemplo-edital.pdf · 12.4 MB" : c.h + " · arraste ou clique"}</div>
              </div>
              {ready[c.k] && <span className="text-pleita-lime text-xl">✓</span>}
            </button>
          ))}
          <div className={`rounded-[10px] border-2 p-5 transition-colors ${ready.cnpj ? "border-pleita-lime bg-pleita-lime/10" : "border-pleita-paper/20 bg-pleita-ink-2"}`}>
            <div className="flex items-center gap-4">
              <div className="size-12 rounded-md grid place-items-center text-2xl" style={{ background: ready.cnpj ? "rgb(159 232 112 / .3)" : "rgb(255 255 255 / .05)" }}>🏢</div>
              <div className="flex-1">
                <div className="font-display text-base text-pleita-paper">CNPJ da Empresa</div>
                <input
                  placeholder="XX.XXX.XXX/XXXX-XX"
                  onChange={(e) => setReady((r) => ({ ...r, cnpj: e.target.value.length >= 14 }))}
                  className="pl-num text-sm bg-transparent text-pleita-paper outline-none border-b border-pleita-paper/20 focus:border-pleita-lime mt-1 w-full pb-1 placeholder:text-pleita-paper/30"
                />
              </div>
            </div>
          </div>
        </div>
        <button
          disabled={!allReady}
          onClick={onStart}
          className={`mt-6 w-full rounded-full py-3.5 text-sm font-semibold transition-all ${allReady ? "bg-pleita-lime text-pleita-ink hover:bg-pleita-lime-2 hover:-translate-y-px" : "bg-pleita-paper/10 text-pleita-paper/40 cursor-not-allowed"}`}
        >
          Analisar com o Comitê →
        </button>
      </div>
    </div>
  );
}

// ----- Fase C: Painel de Prontidão -----
const READINESS_ITEMS = [
  { st: "ok",   t: "CNPJ Ativo",            d: "Receita Federal · situação regular" },
  { st: "ok",   t: "SICAF Nível II",        d: "Cadastro ativo · 14/08/2026" },
  { st: "warn", t: "CND Federal",           d: "Vence em 8 dias · renove agora" },
  { st: "ok",   t: "FGTS / CRF",            d: "Válido até 20/10/2026" },
  { st: "ok",   t: "CNDT",                  d: "Válido até 15/08/2026" },
  { st: "err",  t: "Balanço Patrimonial 2025", d: "Não encontrado · solicite ao contador" },
  { st: "warn", t: "Cláusula §4º",          d: "Exigência ilegal detectada · impugnar" },
  { st: "ok",   t: "Qualificação Técnica",  d: "Atestado cobre 50% do objeto" },
];
const STATUS_META = {
  ok:   { color: "rgb(22 163 74)",  bg: "rgb(34 197 94 / .12)",  ico: "✓" },
  warn: { color: "rgb(245 158 11)", bg: "rgb(245 158 11 / .12)", ico: "⚠" },
  err:  { color: "rgb(239 68 68)",  bg: "rgb(239 68 68 / .12)",  ico: "✕" },
};

function PhaseReport({ onRestart }) {
  return (
    <div className="min-h-full bg-surface-1">
      <div className="max-w-7xl mx-auto px-6 md:px-10 py-10">
        <div className="flex items-end justify-between flex-wrap gap-4 mb-8">
          <div>
            <div className="pl-num text-xs uppercase tracking-[0.14em] text-pleita-lime mb-2">Painel de Prontidão · Comitê concluído em 3,4s</div>
            <h1 className="font-display text-3xl md:text-4xl text-pleita-ink leading-tight">Análise concluída<span className="text-pleita-lime">.</span></h1>
            <p className="text-sm text-pleita-stone mt-2">Pregão Eletrônico 042/2026 · Sec. Educação GO · R$ 890.000 estimado</p>
          </div>
          <div className="flex gap-2 items-center">
            <span className="pl-num text-xs px-2.5 py-1 rounded-full bg-verdict-go/15 text-verdict-go font-semibold">✓ 5 prontos</span>
            <span className="pl-num text-xs px-2.5 py-1 rounded-full bg-verdict-caution/15 text-verdict-caution font-semibold">⚠ 2 atenção</span>
            <span className="pl-num text-xs px-2.5 py-1 rounded-full bg-verdict-stop/10 text-verdict-stop font-semibold">✕ 1 bloqueio</span>
            <button onClick={onRestart} className="ml-2 pl-num text-xs text-pleita-stone-2 hover:text-pleita-ink">↺ nova análise</button>
          </div>
        </div>

        <div className="grid grid-cols-12 gap-6">
          {/* Coluna principal */}
          <div className="col-span-12 lg:col-span-8 space-y-6">
            <section className="rounded-[10px] bg-surface-card border border-pleita-line p-6 shadow-pl-sm">
              <h2 className="font-display text-lg text-pleita-ink mb-4">Checklist da licitação</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                {READINESS_ITEMS.map((it, i) => {
                  const m = STATUS_META[it.st];
                  return (
                    <div key={i} className="flex items-start gap-3 p-3 rounded-md border border-pleita-line/60">
                      <div className="size-7 rounded-md grid place-items-center text-sm font-bold shrink-0" style={{ background: m.bg, color: m.color }}>{m.ico}</div>
                      <div className="min-w-0">
                        <div className="text-sm text-pleita-ink font-medium" style={{ color: m.color }}>{it.t}</div>
                        <div className="text-xs text-pleita-stone-2 mt-0.5">{it.d}</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </section>

            <section className="grid grid-cols-1 md:grid-cols-3 gap-3">
              {[
                { st: "err",  t: "Providenciar Balanço 2025", d: "Solicite ao seu contador. Sem isso, inabilitação certa.", cta: "Resolver →" },
                { st: "warn", t: "Renovar CND Federal",       d: "Faltam 8 dias. Emissão online em 3 minutos.",            cta: "Emitir →" },
                { st: "ok",   t: "Impugnar Cláusula §4º",    d: "Peça pronta com fundamentação TCU AC 1.234/2021.",       cta: "Ver peça →" },
              ].map((a, i) => {
                const m = STATUS_META[a.st];
                return (
                  <div key={i} className="rounded-[10px] bg-surface-card border border-pleita-line p-5" style={{ borderLeftWidth: 3, borderLeftColor: m.color }}>
                    <div className="text-xs pl-num uppercase tracking-wider mb-2" style={{ color: m.color }}>Ação prioritária</div>
                    <div className="font-display text-base text-pleita-ink">{a.t}</div>
                    <p className="text-xs text-pleita-stone mt-2 leading-relaxed">{a.d}</p>
                    <button className="mt-4 w-full rounded-md py-2 text-sm font-medium" style={{ background: m.bg, color: m.color }}>{a.cta}</button>
                  </div>
                );
              })}
            </section>
          </div>

          {/* Coluna lateral */}
          <aside className="col-span-12 lg:col-span-4 space-y-4">
            <div className="rounded-[10px] bg-surface-card border border-pleita-line p-6 shadow-pl-sm text-center">
              <ScoreSemiGauge value={67} />
              <div className="mt-3 inline-flex items-center gap-1.5 rounded-full bg-verdict-caution/15 text-verdict-caution px-3 py-1 text-xs font-semibold pl-num">⚠ Regularize e participe</div>
            </div>

            <div className="rounded-[10px] bg-surface-card border border-pleita-line p-6 shadow-pl-sm">
              <div className="pl-num text-[10px] uppercase tracking-[0.14em] text-pleita-stone-2 mb-3">Inteligência de mercado</div>
              <dl className="space-y-3">
                {[
                  ["Preço sugerido",    "R$ 1,78/un",  "text-pleita-ink"],
                  ["Preço médio vencedor", "R$ 1,82/un", "text-pleita-stone"],
                  ["Probabilidade de vitória", "34%",   "text-pleita-lime font-semibold"],
                  ["Concorrentes mapeados",    "3",     "text-pleita-stone"],
                ].map(([l, v, cls]) => (
                  <div key={l} className="flex items-baseline justify-between border-b border-pleita-line/40 pb-2 last:border-0">
                    <dt className="text-xs text-pleita-stone-2">{l}</dt>
                    <dd className={`pl-num text-sm ${cls}`}>{v}</dd>
                  </div>
                ))}
              </dl>
            </div>

            <button className="w-full rounded-full bg-pleita-lime text-pleita-ink py-3 text-sm font-semibold hover:bg-pleita-lime-2 transition-colors">
              Ver 5 ações para maximizar →
            </button>
          </aside>
        </div>
      </div>
    </div>
  );
}

function ScreenAnalise() {
  const [phase, setPhase] = React.useState("upload"); // upload | committee | report
  const [elapsed, setElapsed] = React.useState(0);

  React.useEffect(() => {
    if (phase !== "committee") return;
    setElapsed(0);
    let start = performance.now();
    let raf;
    const tick = (now) => {
      const e = now - start;
      setElapsed(e);
      if (e < 2600) raf = requestAnimationFrame(tick);
      else setTimeout(() => setPhase("report"), 400);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [phase]);

  if (phase === "upload")    return <PhaseUpload onStart={() => setPhase("committee")} />;
  if (phase === "committee") return <PhaseCommittee elapsed={elapsed} />;
  return <PhaseReport onRestart={() => setPhase("upload")} />;
}

window.ScreenAnalise = ScreenAnalise;
