// Modules — LiteLLM budget viewer, model intelligence ranking, EC2 budget, shortcuts, activity.

const { MoneyBig, Bar, Pill, Panel, Sparkline, BarsDaily, StatusDot, fmtInt, fmtMoney } = window.SEIS_PRIM;

function DataLoading() {
  return <div className="tiny" style={{ color: "var(--muted)", padding: "12px 0" }}>LOADING...</div>;
}

// ── §02 LITELLM BUDGETS ────────────────────────────────────────
function fmtTokens(n) {
  if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + "M";
  if (n >= 1_000)     return (n / 1_000).toFixed(1) + "K";
  return n.toString();
}

function ProviderBudget({ b, models }) {
  const tone = b.mode === "unlimited"
    ? "default"
    : (b.used / b.monthly) > 0.85 ? "danger"
    : (b.used / b.monthly) > 0.65 ? "warn" : "default";
  const pct = b.monthly ? (b.used / b.monthly) * 100 : 0;

  const myModels = models.filter(m => m.bucket === b.id).sort((a, b) => b.spent - a.spent);
  const top = myModels[0];

  return (
    <div style={{ borderTop: "1px solid var(--rule-soft)", padding: "14px 0" }}>
      <div className="row between" style={{ alignItems: "baseline" }}>
        <div>
          <div style={{ fontWeight: 600, fontSize: 13, letterSpacing: "0.04em" }}>{b.label}
            <span style={{ color: "var(--muted)", marginLeft: 10, fontWeight: 400 }} className="serif">{b.sub}</span>
          </div>
        </div>
        <div className="row gap-12" style={{ alignItems: "baseline" }}>
          {b.mode === "unlimited" ? (
            <>
              <span className="num" style={{ fontSize: 18, fontWeight: 500 }}>${b.used.toFixed(4)}</span>
              <span className="tiny" style={{ color: b.rateLimited ? "var(--accent)" : "var(--muted)" }}>
                {b.rateLimited ? "● RATE LIMITED" : `UNLIMITED · ${(b.rateLimit || {}).currentRpm || 0}/${(b.rateLimit || {}).rpm || 240} RPM`}
              </span>
            </>
          ) : (
            <>
              <span className="num" style={{ fontSize: 18, fontWeight: 500 }}>
                ${b.used.toFixed(4)}<span style={{ color: "var(--muted)", fontSize: 12 }}> / ${b.monthly.toFixed(0)}</span>
              </span>
              <span className="tiny" style={{ color: tone === "danger" ? "var(--accent)" : "var(--muted)" }}>{pct.toFixed(0)}%</span>
            </>
          )}
        </div>
      </div>
      <div style={{ marginTop: 8 }}>
        {b.mode === "unlimited" ? (
          <Bar value={(b.rateLimit || {}).currentRpm || 0} max={(b.rateLimit || {}).rpm || 240} thin tone={b.rateLimited ? "danger" : "default"} />
        ) : (
          <Bar value={b.used} max={b.monthly} tone={tone} thin />
        )}
      </div>
      {myModels.length > 0 && (
        <>
          <div className="micro" style={{ marginTop: 10, marginBottom: 6, color: "var(--muted)" }}>BY MODEL · SORTED BY SPEND</div>
          <div className="stack-2">
            {myModels.map(m => {
              const tokens = (m.tokensIn || 0) + (m.tokensOut || 0);
              const share  = b.mode === "unlimited" ? 0 : (m.spent / b.monthly) * 100;
              const topSpent = top ? top.spent : 1;
              return (
                <div key={m.id}>
                  <div className="row between" style={{ fontSize: 12, alignItems: "baseline" }}>
                    <span>
                      <span style={{ fontWeight: 500 }}>{m.name}</span>
                      {tokens > 0 && (
                        <span className="tiny num" style={{ color: "var(--muted)", marginLeft: 10 }}>
                          {fmtTokens(tokens)} TOK <span style={{ opacity: 0.6 }}>· {fmtTokens(m.tokensIn || 0)} IN · {fmtTokens(m.tokensOut || 0)} OUT</span>
                        </span>
                      )}
                    </span>
                    <span className="num">
                      ${m.spent.toFixed(4)}
                      {b.mode !== "unlimited" && (
                        <span style={{ color: "var(--muted)", marginLeft: 8 }}>{share.toFixed(1)}%</span>
                      )}
                    </span>
                  </div>
                  <div style={{ marginTop: 3 }}>
                    <Bar value={m.spent} max={topSpent} thin />
                  </div>
                </div>
              );
            })}
          </div>
        </>
      )}
    </div>
  );
}

function LiteLLMBudget({ budgets, models, loading }) {
  const totalCapped = (budgets || []).filter(b => b.mode === "capped").reduce((s, b) => s + (b.monthly || 0), 0);
  const totalUsed   = (budgets || []).reduce((s, b) => s + (b.used || 0), 0);

  return (
    <Panel idx="LIT-001" title="LITELLM · BUDGETS BY PROVIDER" right="LIVE · 30S POLL" live>
      {loading && !budgets.length ? <DataLoading /> : (
        <>
          <div className="row between" style={{ alignItems: "baseline", marginBottom: 4 }}>
            <div className="micro">CAPPED TOTAL · THIS MONTH</div>
            <div className="tiny" style={{ color: "var(--muted)" }}>{(budgets || []).length} PROVIDERS</div>
          </div>
          <MoneyBig value={totalUsed} of={totalCapped} />
          <div className="tiny" style={{ color: "var(--muted)", marginTop: 4 }}>
            + OPEN-SOURCE TIER (UNLIMITED · RATE-LIMITED)
          </div>
          {(budgets || []).map(b => <ProviderBudget key={b.id} b={b} models={models || []} />)}
          <div className="micro" style={{ marginTop: 14, color: "var(--muted)", lineHeight: 1.5 }}>
            * OPEN-SOURCE TIER IS UNLIMITED UNTIL RATE-LIMITED FOR HEAVY USE.<br />
            SESSION-MODE MODELS BILL TO SUBSCRIPTIONS — SEE §02 MODELS.
          </div>
        </>
      )}
    </Panel>
  );
}

// ── §03 MODEL INTELLIGENCE RANKING ─────────────────────────────
function ModelRanking({ models, loading }) {
  const sorted = [...(models || [])].sort((a, b) => (b.iq || 0) - (a.iq || 0));

  return (
    <Panel idx="MDL-002" title="INTELLIGENCE RANKING · TOKEN REMAINING" right="LIVE · LITELLM POLL 30S" live>
      {loading && !models.length ? <DataLoading /> : (
        <>
          <table className="idx">
            <thead>
              <tr>
                <th style={{ width: 40 }}>#</th>
                <th>MODEL</th>
                <th>VENDOR</th>
                <th className="num">SPEND</th>
                <th>MODE</th>
                <th className="num">CALLS</th>
                <th className="num">P95</th>
              </tr>
            </thead>
            <tbody>
              {sorted.map((m, i) => (
                <tr key={m.id}>
                  <td style={{ color: "var(--muted)" }}>{String(i + 1).padStart(2, "0")}</td>
                  <td style={{ fontWeight: 500 }}>{m.name}</td>
                  <td style={{ color: "var(--muted)" }}>{m.vendor}</td>
                  <td className="num" style={{ fontWeight: 600 }}>${(m.spent || 0).toFixed(4)}</td>
                  <td>
                    <span className="tiny" style={{ color: m.mode === "unlimited" ? "var(--muted)" : "var(--ink-2)" }}>
                      {(m.mode || "metered").toUpperCase()}
                    </span>
                  </td>
                  <td className="num" style={{ color: "var(--muted)" }}>{m.calls ? fmtInt(m.calls) : "—"}</td>
                  <td className="num" style={{ color: "var(--muted)" }}>{m.p95 ? `${m.p95.toFixed(2)}s` : "—"}</td>
                </tr>
              ))}
              {sorted.length === 0 && (
                <tr><td colSpan={7} className="tiny" style={{ color: "var(--muted)", textAlign: "center", padding: "12px 0" }}>NO MODEL DATA</td></tr>
              )}
            </tbody>
          </table>
        </>
      )}
    </Panel>
  );
}

// ── §04 EC2 BUDGET METER ───────────────────────────────────────
function EC2Budget({ budget, loading, onLaunch }) {
  const monthly  = budget?.monthly  || 600;
  const used     = budget?.used     || 0;
  const daysLeft = budget?.daysLeft || 0;
  const free     = monthly - used;
  const pct      = (used / monthly) * 100;
  const tone     = pct > 85 ? "danger" : pct > 65 ? "warn" : "default";
  const noKey    = budget?.error === "EC2_CREDENTIALS_NOT_CONFIGURED";

  return (
    <Panel idx="EC2-003" title="EC2 · MONTHLY BUDGET" right={noKey ? "NO CREDENTIALS" : "COST EXPLORER"}>
      <div className="stack-3">
        <div className="micro">USED · THIS MONTH</div>
        {loading && !budget ? <DataLoading /> : (
          <>
            <MoneyBig value={used} of={monthly} />
            <Bar value={used} max={monthly} tone={tone} />
            <div className="row between tiny" style={{ color: "var(--muted)" }}>
              <span>{pct.toFixed(1)}% CONSUMED</span>
              <span>FREE ${free.toFixed(4)}</span>
              <span>{daysLeft}D LEFT</span>
            </div>
            {noKey && (
              <div className="micro" style={{ color: "var(--accent)", marginTop: 4 }}>
                ⚠ SET EC2_AWS_ACCESS_KEY_ID IN .ENV TO ENABLE
              </div>
            )}
          </>
        )}
        <div style={{ marginTop: 12 }}>
          <button className="btn solid" style={{ width: "100%", justifyContent: "center" }} onClick={onLaunch}>
            <span style={{ color: "var(--accent)" }}>+</span> LAUNCH SPOT INSTANCE <span className="arr">→</span>
          </button>
        </div>
      </div>
    </Panel>
  );
}

// ── ACTIVE SERVERS ─────────────────────────────────────────────
function ActiveServers({ instances, loading, onOpenInstance, hasSshKey }) {
  const [terminating, setTerminating] = React.useState(null);
  const doTerminate = async (ident) => {
    if (!window.confirm(`Terminate ${ident}? This cannot be undone.`)) return;
    setTerminating(ident);
    try {
      const r = await fetch(`/api/ec2/terminate/${ident}`, { method: "POST", credentials: "include" });
      if (!r.ok) { const b = await r.json().catch(() => ({})); alert(b.detail || "Terminate failed"); }
    } catch { alert("Network error"); }
    finally { setTerminating(null); }
  };

  return (
    <Panel idx="EC2-004" title="ACTIVE SERVERS" right="LIVE · 30S POLL">
      {loading && !instances.length ? <DataLoading /> : instances.length === 0 ? (
        <div className="tiny" style={{ color: "var(--muted)", padding: "12px 0" }}>NO RUNNING INSTANCES</div>
      ) : (
        <table className="idx">
          <thead>
            <tr>
              <th>NAME</th>
              <th>INSTANCE</th>
              <th>OWNER</th>
              <th>UPTIME</th>
              <th className="num">SPENT</th>
              <th>STATUS</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {instances.map(s => (
              <tr key={s.id}>
                <td style={{ fontWeight: 500 }}>{s.name}<div className="micro" style={{ color: "var(--muted)", marginTop: 2 }}>{s.id}</div></td>
                <td>{s.instance}</td>
                <td style={{ color: "var(--muted)" }}>@{s.userHandle || s.user}</td>
                <td className="num" style={{ color: "var(--muted)" }}>{s.uptime}</td>
                <td className="num">${(s.cost || 0).toFixed(4)}</td>
                <td><StatusDot status={s.status} /><span className="tiny">{s.status.toUpperCase()}</span></td>
                <td style={{ textAlign: "right", whiteSpace: "nowrap" }}>
                  <button className="btn ghost" style={{ padding: "4px 10px", fontSize: 9, marginRight: 6 }}
                    onClick={() => onOpenInstance && onOpenInstance(s.id)}
                    title={hasSshKey ? "Open terminal" : "Open instance panel"}>
                    {hasSshKey ? "SSH →" : "PANEL →"}
                  </button>
                  <button className="btn ghost" style={{ padding: "4px 10px", fontSize: 9 }}
                    disabled={terminating === s.id}
                    onClick={() => doTerminate(s.id)}>
                    {terminating === s.id ? "..." : "TERM"} <span className="arr">→</span>
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </Panel>
  );
}

// ── EC2 LAUNCH HISTORY ─────────────────────────────────────────
function EC2History({ history, loading }) {
  const rows       = history || [];
  const totalActual = rows.reduce((s, r) => s + (r.costActual    || 0), 0);
  const totalEst    = rows.reduce((s, r) => s + (r.costEstimated || 0), 0);
  const running     = rows.filter(r => r.status === "running").length;
  const [page, setPage] = React.useState(0);
  const perPage = 5;
  const totalPages = Math.ceil(rows.length / perPage);
  const showRows = rows.slice(page * perPage, (page + 1) * perPage);

  React.useEffect(() => { if (page >= totalPages && totalPages > 0) setPage(totalPages - 1); }, [rows.length]);

  const statusColor = s => s === "running" ? "var(--accent)" : s === "failed" ? "var(--accent)" : "var(--muted)";

  return (
    <Panel idx="EC2-006" title="EC2 · LAUNCH HISTORY" right={`PAGE ${page+1}/${totalPages||1} · ${rows.length} TOTAL`}>
      {loading && !rows.length ? <DataLoading /> : (
        <>
          <div className="row gap-24" style={{ marginBottom: 14 }}>
            <div>
              <div className="micro" style={{ color: "var(--muted)" }}>TOTAL SPENT (ACTUAL)</div>
              <div className="num" style={{ fontSize: 22, fontWeight: 600 }}>${totalActual.toFixed(4)}</div>
            </div>
            <div>
              <div className="micro" style={{ color: "var(--muted)" }}>TOTAL ESTIMATED</div>
              <div className="num" style={{ fontSize: 22 }}>${totalEst.toFixed(4)}</div>
            </div>
            <div>
              <div className="micro" style={{ color: "var(--muted)" }}>LAUNCHES</div>
              <div className="num" style={{ fontSize: 22 }}>{rows.length}</div>
            </div>
            {running > 0 && (
              <div>
                <div className="micro" style={{ color: "var(--muted)" }}>RUNNING NOW</div>
                <div className="num" style={{ fontSize: 22, color: "var(--accent)" }}>{running}</div>
              </div>
            )}
          </div>
          {showRows.length === 0 ? (
            <div className="tiny" style={{ color: "var(--muted)", padding: "12px 0" }}>NO LAUNCHES YET</div>
          ) : (
            <>
              <table className="idx" style={{ fontSize: 11 }}>
                <thead>
                  <tr>
                    <th>#</th>
                    <th>NAME</th>
                    <th>WHO</th>
                    <th>TYPE</th>
                    <th>REGION / AZ</th>
                    <th className="num">HRS REQ</th>
                    <th className="num">HRS ACTUAL</th>
                    <th className="num">EST</th>
                    <th className="num">ACTUAL</th>
                    <th>STATUS</th>
                    <th>LAUNCHED</th>
                    <th>TERM BY</th>
                  </tr>
                </thead>
                <tbody>
                  {showRows.map(r => (
                    <tr key={r.id}>
                      <td style={{ color: "var(--muted)", fontVariantNumeric: "tabular-nums" }}>{r.id}</td>
                      <td style={{ fontWeight: 500 }}>
                        {r.nameTag || "—"}
                        {r.instanceId && <div className="micro" style={{ color: "var(--muted)", marginTop: 2 }}>{r.instanceId}</div>}
                      </td>
                      <td style={{ color: "var(--muted)" }}>@{r.user}</td>
                      <td>{r.instanceType}</td>
                      <td style={{ color: "var(--muted)" }}>{r.az || r.region}</td>
                      <td className="num">{r.hoursReq != null ? (+r.hoursReq).toFixed(4) + "h" : "—"}</td>
                      <td className="num" style={{ color: "var(--muted)" }}>{r.hoursActual != null ? `${r.hoursActual.toFixed(1)}h` : "—"}</td>
                      <td className="num">{r.costEstimated != null ? `$${r.costEstimated.toFixed(4)}` : "—"}</td>
                      <td className="num" style={{ fontWeight: 600 }}>{r.costActual != null ? `$${r.costActual.toFixed(4)}` : "—"}</td>
                      <td><span style={{ color: statusColor(r.status) }}>{r.status.toUpperCase()}</span></td>
                      <td style={{ color: "var(--muted)" }}>{r.launchedAt ? r.launchedAt.slice(0, 10) : "—"}</td>
                      <td style={{ color: "var(--muted)" }}>{r.terminatedBy || "—"}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {totalPages > 1 && (
                <div className="row gap-8" style={{ marginTop: 10, justifyContent: "center", alignItems: "center" }}>
                  <button className="btn ghost" style={{ fontSize: 9, padding: "4px 8px" }} disabled={page === 0} onClick={() => setPage(p => p - 1)}>◀ PREV</button>
                  {(() => {
                    const btns = [];
                    const add = (i) => btns.push(<button key={i} className={page === i ? "btn solid" : "btn ghost"}
                      style={{ fontSize: 9, padding: "4px 10px", minWidth: 32 }}
                      onClick={() => setPage(i)}>{i + 1}</button>);
                    const addDots = (key) => btns.push(<span key={key} className="micro" style={{ color: "var(--muted)" }}>…</span>);

                    if (totalPages <= 7) {
                      for (let i = 0; i < totalPages; i++) add(i);
                    } else {
                      add(0);
                      if (page > 3) addDots("l");
                      const start = Math.max(1, page - 1);
                      const end = Math.min(totalPages - 2, page + 1);
                      if (page <= 3) {
                        for (let i = 1; i <= 4; i++) add(i);
                        addDots("r");
                      } else if (page >= totalPages - 4) {
                        addDots("l");
                        for (let i = totalPages - 5; i < totalPages; i++) add(i);
                      } else {
                        for (let i = start; i <= end; i++) add(i);
                        if (end < totalPages - 2) addDots("r");
                      }
                      add(totalPages - 1);
                    }
                    return btns;
                  })()}
                  <button className="btn ghost" style={{ fontSize: 9, padding: "4px 8px" }} disabled={page >= totalPages - 1} onClick={() => setPage(p => p + 1)}>NEXT ▶</button>
                </div>
              )}
            </>
          )}
        </>
      )}
    </Panel>
  );
}

// ── §05 SHORTCUTS ──────────────────────────────────────────────
function Shortcuts({ shortcuts }) {
  return (
    <Panel idx="LNK-005" title="INTERNAL · TOOLS & ATAJOS" right="STUDIO ONLY">
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 0, borderLeft: "1px solid var(--rule-soft)" }}>
        {(shortcuts || []).map(group => (
          <div key={group.group} style={{ borderRight: "1px solid var(--rule-soft)" }}>
            <div className="micro" style={{ padding: "0 14px 10px", color: "var(--muted)" }}>{group.group}</div>
            <div>
              {group.items.map(it => (
                <a key={it.label} href={it.url} target="_blank" rel="noopener" className="row between" style={{
                  padding: "12px 14px",
                  borderTop: "1px solid var(--rule-soft)",
                  fontSize: 12,
                  transition: "background 120ms",
                }} onMouseEnter={e => e.currentTarget.style.background = "var(--bg-2)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                  <span>{it.label}</span>
                  <span className="row gap-8" style={{ alignItems: "center" }}>
                    <span className="micro" style={{ color: "var(--muted)" }}>{it.hint}</span>
                    <span className="serif" style={{ fontStyle: "italic" }}>→</span>
                  </span>
                </a>
              ))}
            </div>
          </div>
        ))}
      </div>
    </Panel>
  );
}

// ── ACTIVITY FEED ──────────────────────────────────────────────
function ActivityFeed({ activity, loading }) {
  return (
    <Panel idx="LOG-007" title="RECENT · ACTIVITY" right="EC2 + GITLAB · UTC">
      {loading && !activity.length ? <DataLoading /> : activity.length === 0 ? (
        <div className="tiny" style={{ color: "var(--muted)", padding: "12px 0" }}>NO ACTIVITY YET</div>
      ) : (
        <div className="stack-2">
          {activity.map((a, i) => (
            <div key={i} className="row gap-12" style={{ fontSize: 12, alignItems: "baseline" }}>
              <span className="tiny num" style={{ color: "var(--muted)", minWidth: 38 }}>{a.t}</span>
              <span><b>@{a.who}</b> <span style={{ color: "var(--muted)" }}>{a.what}</span> {a.target}</span>
            </div>
          ))}
        </div>
      )}
    </Panel>
  );
}

// ── YOUR INSTANCES ──────────────────────────────────────────
function YourInstances({ instances, instanceTypes, userHandle, onOpenInstance, hasSshKey }) {
  const [now, setNow] = React.useState(Date.now());
  const [terminating, setTerminating] = React.useState(null);
  React.useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);

  const doTerminate = async (ident) => {
    if (!window.confirm(`Terminate ${ident}? This cannot be undone.`)) return;
    setTerminating(ident);
    try {
      const r = await fetch(`/api/ec2/terminate/${ident}`, { method: "POST", credentials: "include" });
      if (!r.ok) { const b = await r.json().catch(() => ({})); alert(b.detail || "Terminate failed"); }
    } catch { alert("Network error"); }
    finally { setTerminating(null); }
  };

  const my = (instances || []).filter(i => i.userHandle === userHandle && i.status === "running");
  if (my.length === 0) return null;

  return (
    <div className="panel" style={{ marginTop: 16 }}>
      <div className="panel-head">
        <span className="idx">EC2-007</span>
        <span className="title">YOUR INSTANCES</span>
        <span className="right" style={{ color: "var(--accent)" }}>● {my.length} RUNNING</span>
      </div>
      <div className="panel-body">
        <div className="stack-3">
          {my.map(inst => {
            const spec = (instanceTypes || []).find(t => t.id === inst.instance);
            const startedMs = inst.startedAt ? new Date(inst.startedAt).getTime() : null;
            const elapsedH  = startedMs ? (now - startedMs) / 3600000 : 0;
            const hoursReq  = inst.hoursReq || 0;
            const remaining = Math.max(0, hoursReq - elapsedH);
            const endsMs    = startedMs ? startedMs + hoursReq * 3600000 : null;
            const termTime  = endsMs ? new Date(endsMs).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", timeZoneName: "short" }) : "—";
            const costLive  = inst.spotPrice ? (inst.spotPrice * elapsedH).toFixed(4) : null;
            const pct        = hoursReq > 0 ? Math.min(100, (elapsedH / hoursReq) * 100) : 0;
            const tone       = pct > 85 ? "danger" : pct > 65 ? "warn" : "default";

            const remH  = Math.floor(remaining);
            const remM  = Math.floor((remaining - remH) * 60);
            const remStr = remaining < 0.017 ? "EXPIRED"
              : remH > 0 ? `${remH}h ${remM}m left`
              : `${remM}m left`;

            return (
              <div key={inst.id} style={{ borderTop: "1px solid var(--rule-soft)", paddingTop: 14, marginTop: 2 }}>
                <div className="row between" style={{ alignItems: "baseline", marginBottom: 4 }}>
                  <div>
                    <span style={{ fontWeight: 600, fontSize: 14 }}>{inst.name}</span>
                    <span className="micro" style={{ color: "var(--muted)", marginLeft: 10 }}>{inst.instance}</span>
                  </div>
                  <div className="row gap-8" style={{ alignItems: "center" }}>
                    <span className="num" style={{ fontSize: 16, fontWeight: 500 }}>
                      ${costLive || "—"}
                    </span>
                    <button className="btn ghost" style={{ padding: "4px 8px", fontSize: 9 }}
                      onClick={() => onOpenInstance && onOpenInstance(inst.id)}
                      title={hasSshKey ? "Open SSH terminal" : "Open instance panel"}>
                      {hasSshKey ? "SSH →" : "PANEL →"}
                    </button>
                    <button className="btn ghost" style={{ padding: "4px 8px", fontSize: 9 }}
                      disabled={terminating === inst.id}
                      onClick={() => doTerminate(inst.id)}>
                      {terminating === inst.id ? "..." : "TERM"} <span className="arr">→</span>
                    </button>
                  </div>
                </div>
                <div className="row gap-12 micro" style={{ color: "var(--muted)", marginBottom: 6 }}>
                  {spec && (
                    <>
                      <span>{spec.vcpu} vCPU</span>
                      <span>·</span>
                      <span>{spec.ram}</span>
                      <span>·</span>
                      <span>{spec.vram}</span>
                    </>
                  )}
                  {!spec && <span>{inst.instance}</span>}
                  <span className="micro" style={{ color: "var(--muted)", marginLeft: "auto" }}>
                    {inst.spotPrice ? `@ $${inst.spotPrice.toFixed(4)}/h` : ""}
                  </span>
                </div>
                <Bar value={elapsedH} max={hoursReq} tone={tone} thin />
                <div className="row between tiny" style={{ marginTop: 4, color: "var(--muted)" }}>
                  <span style={{ color: tone === "danger" ? "var(--danger)" : tone === "warn" ? "var(--warn)" : "var(--muted)" }}>
                    {remStr}
                  </span>
                  <span>
                    <span className="num" style={{ color: "var(--ink-2)" }}>{elapsedH.toFixed(1)}h</span>
                    <span> / </span>
                    <span className="num">{hoursReq.toFixed(1)}h</span>
                    <span className="micro" style={{ marginLeft: 10 }}>ENDS · {termTime}</span>
                  </span>
                </div>
                {remaining <= 0 && (
                  <div className="micro" style={{ color: "var(--danger)", marginTop: 4 }}>AWAITING AUTO-TERMINATE (SWEEPS EVERY 5M)</div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.SEIS_MODULES = { LiteLLMBudget, ModelRanking, EC2Budget, ActiveServers, EC2History, Shortcuts, ActivityFeed, YourInstances };

