/* global React, window */
// =====================================================================
// AgentsView — "pit wall" de agentes en vivo (windmar-marketing).
// Lee marketing.agent_runs / agent_outputs vía RPCs públicas.
// =====================================================================
(function () {
  const { useState, useEffect } = React;

  function fmtDur(a, b) {
    if (!a) return "—";
    const end = b ? new Date(b) : new Date();
    const s = Math.max(0, (end - new Date(a)) / 1000);
    return s < 60 ? s.toFixed(0) + "s" : (s / 60).toFixed(1) + "m";
  }
  const statusColor = { running: "var(--wm-orange)", ok: "var(--op-green)", error: "var(--wm-red, #b5301f)" };

  function AgentsView({ lang = "es" }) {
    const [runs, setRuns] = useState(null);
    const [auds, setAuds] = useState(null);
    const [loading, setLoading] = useState(true);

    async function load() {
      if (!window.wm?.ready) { setLoading(false); return; }
      const [r, a] = await Promise.all([window.wm.agentRuns(), window.wm.agentOutputs("audience")]);
      setRuns(r); setAuds(a); setLoading(false);
    }
    useEffect(() => { load(); const id = setInterval(load, 15000); return () => clearInterval(id); }, []);

    const pending = !window.wm?.ready || runs === null;
    const running = (runs || []).filter(r => r.status === "running").length;
    const cost = (runs || []).reduce((s, r) => s + Number(r.cost_usd || 0), 0);

    return (
      <div style={{ padding: "4px 2px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
          <window.Icon name="cpu" size={20} />
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 800 }}>{lang === "es" ? "Agentes · pit wall" : "Agents · pit wall"}</h2>
          <window.LiveDot />
          <span style={{ marginLeft: "auto", fontSize: 11, color: "var(--wm-fg-muted)" }}>windmar-marketing · marketing.agent_runs</span>
        </div>

        {pending && (
          <div style={{ padding: 16, border: "1px dashed var(--op-line)", borderRadius: 12, color: "var(--wm-fg-muted)", fontSize: 13 }}>
            <window.Icon name="info" size={14} /> Telemetría pendiente de deploy: aplica el RPC <code>public.agent_feed</code> y despliega WT1 para ver los agentes en vivo.
          </div>
        )}

        {!pending && (
          <>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12, marginBottom: 16 }}>
              {[
                { l: lang === "es" ? "En pista" : "Running", v: running },
                { l: lang === "es" ? "Corridas" : "Runs", v: (runs || []).length },
                { l: lang === "es" ? "Costo" : "Cost", v: window.fmt.money(cost) },
                { l: lang === "es" ? "Audiencias" : "Audiences", v: (auds || []).length },
              ].map((s, i) => (
                <div key={i} style={{ background: "var(--op-card, #fff)", border: "1px solid var(--op-line)", borderRadius: 12, padding: "12px 14px" }}>
                  <div style={{ fontSize: 11, color: "var(--wm-fg-muted)", textTransform: "uppercase", letterSpacing: ".05em" }}>{s.l}</div>
                  <div style={{ fontSize: 24, fontWeight: 900, color: "var(--wm-blue)" }}>{s.v}</div>
                </div>
              ))}
            </div>

            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13, marginBottom: 22 }}>
              <thead><tr style={{ textAlign: "left", color: "var(--wm-fg-muted)", fontSize: 11, textTransform: "uppercase" }}>
                <th style={{ padding: "6px 8px" }}>Agente</th><th>Estado</th><th>Inicio</th><th>Duración</th><th style={{ textAlign: "right" }}>Tokens</th><th style={{ textAlign: "right" }}>Costo</th>
              </tr></thead>
              <tbody>
                {(runs || []).map((r, i) => (
                  <tr key={i} style={{ borderTop: "1px solid var(--op-line)" }}>
                    <td style={{ padding: "8px", fontWeight: 700 }}>{r.agent_slug}</td>
                    <td><span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontWeight: 700, color: statusColor[r.status] || "var(--wm-fg-muted)" }}><span style={{ width: 7, height: 7, borderRadius: 99, background: statusColor[r.status] }} />{r.status}</span></td>
                    <td>{r.started_at ? new Date(r.started_at).toLocaleString() : "—"}</td>
                    <td>{fmtDur(r.started_at, r.finished_at)}</td>
                    <td style={{ textAlign: "right" }}>{window.fmt.num(r.tokens)}</td>
                    <td style={{ textAlign: "right" }}>{window.fmt.money(r.cost_usd)}</td>
                  </tr>
                ))}
                {!(runs || []).length && <tr><td colSpan={6} style={{ padding: 16, color: "var(--wm-fg-muted)" }}>Sin corridas todavía.</td></tr>}
              </tbody>
            </table>

            <h3 style={{ fontSize: 14, fontWeight: 800, margin: "0 0 10px" }}><window.Icon name="radar" size={16} /> {lang === "es" ? "Audiencias descubiertas (CM-fit)" : "Discovered audiences"}</h3>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 12 }}>
              {(auds || []).map((a, i) => {
                const cm = Number(a.meta?.cm_fit || 0);
                const band = cm >= 0.85 ? "var(--op-green)" : cm >= 0.78 ? "var(--wm-blue)" : "var(--wm-orange)";
                return (
                  <div key={i} style={{ background: "var(--op-card,#fff)", border: "1px solid var(--op-line)", borderRadius: 12, padding: "12px 14px" }}>
                    <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
                      <div style={{ fontWeight: 700, fontSize: 13, lineHeight: 1.3 }}>{a.title}</div>
                      <div style={{ fontWeight: 900, color: band }}>{cm ? cm.toFixed(2) : "—"}</div>
                    </div>
                    <div style={{ display: "flex", gap: 6, flexWrap: "wrap", margin: "6px 0", fontSize: 11, color: "var(--wm-fg-muted)" }}>
                      {a.meta?.vertical && <span>{a.meta.vertical}</span>}
                      {a.meta?.est_size && <span>· ~{window.fmt.num(a.meta.est_size)}</span>}
                      {a.meta?.sports_angle && <span style={{ color: "var(--wm-orange)", fontWeight: 700 }}>· {a.meta.sports_angle}</span>}
                    </div>
                    <div style={{ height: 5, background: "var(--op-line)", borderRadius: 9, overflow: "hidden" }}><div style={{ width: (cm * 100) + "%", height: "100%", background: band }} /></div>
                  </div>
                );
              })}
              {!(auds || []).length && <div style={{ color: "var(--wm-fg-muted)", fontSize: 13 }}>El audience-explorer aún no ha corrido (o pendiente de deploy).</div>}
            </div>
          </>
        )}
      </div>
    );
  }
  window.AgentsView = AgentsView;
})();
