// cockpit-extensions.jsx — RegimeBanner, JournalTab, AuditTab
// Loaded via <script type="text/babel"> — no build step, CDN React only.

const POSTURE_STYLES = {
  green: { bg: "#0d2b1a", border: "#22c55e", badge: "#16a34a", text: "#86efac" },
  amber: { bg: "#2b1f05", border: "#f59e0b", badge: "#d97706", text: "#fcd34d" },
  red:   { bg: "#2b0d0d", border: "#ef4444", badge: "#dc2626", text: "#fca5a5" },
};

function RegimeBanner({ regime }) {
  if (!regime) return null;
  const s = POSTURE_STYLES[regime.posture_color] || POSTURE_STYLES.red;
  const pct = `${((regime.size_multiplier || 0) * 100).toFixed(0)}%`;

  return (
    <div style={{
      background: s.bg, border: `1px solid ${s.border}`,
      borderRadius: 6, padding: "10px 16px", marginBottom: 12,
      fontFamily: "JetBrains Mono, monospace",
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
        <span style={{
          background: s.badge, color: "#fff", fontWeight: 700,
          fontSize: 13, padding: "3px 10px", borderRadius: 4,
        }}>
          RISK POSTURE: {(regime.posture || "UNKNOWN").toUpperCase()} ({pct})
        </span>
        <span style={{ color: s.text, fontSize: 13 }}>
          Regime: {(regime.regime || "UNKNOWN").replace(/_/g, " ")}
        </span>
        <span style={{ color: "#94a3b8", fontSize: 12 }}>
          Confidence {((regime.confidence || 0) * 100).toFixed(0)}%
        </span>
        {regime.stale && (
          <span style={{ color: "#fca5a5", fontSize: 12, fontWeight: 600 }}>⚠ STALE DATA</span>
        )}
        {regime.transitioning && (
          <span style={{ color: "#fcd34d", fontSize: 12 }}>
            ⟳ shifting → {(regime.candidate_regime || "").replace(/_/g, " ")} (day {regime.candidate_days})
          </span>
        )}
        {regime.classified_at && (
          <span style={{ color: "#64748b", fontSize: 11, marginLeft: "auto" }}>
            as of {regime.classified_at.slice(0, 16).replace("T", " ")} UTC
          </span>
        )}
      </div>
      <div style={{ marginTop: 6, color: "#94a3b8", fontSize: 11, display: "flex", gap: 16, flexWrap: "wrap" }}>
        {regime.vix != null && <span>VIX {Number(regime.vix).toFixed(1)}</span>}
        <span>Breadth {regime.breadth != null ? (regime.breadth * 100).toFixed(0) + "%" : "—"}</span>
        <span>
          SPY vs 200d {regime.spy_vs_ema200 != null
            ? (regime.spy_vs_ema200 >= 0 ? "+" : "") + (regime.spy_vs_ema200 * 100).toFixed(1) + "%"
            : "—"}
        </span>
        {regime.error && <span style={{ color: "#fca5a5" }}>Error: {regime.error}</span>}
      </div>
    </div>
  );
}

function StatCard({ label, value, color }) {
  return (
    <div style={{
      background: "#0f172a", border: "1px solid #1e293b",
      borderRadius: 6, padding: "10px 16px", minWidth: 120,
    }}>
      <div style={{ color: "#64748b", fontSize: 11, marginBottom: 4 }}>{label}</div>
      <div style={{ color: color || "#cbd5e1", fontSize: 18, fontWeight: 700 }}>{value}</div>
    </div>
  );
}

function JournalTab({ journal }) {
  if (!journal) return <p style={{ color: "#64748b" }}>No journal data.</p>;
  if (journal.error) return <p style={{ color: "#fca5a5" }}>Journal error: {journal.error}</p>;

  const m = journal.metrics || {};
  const fmt$ = (v) => v != null ? `$${Number(v).toFixed(2)}` : "—";
  const fmtPct = (v) => v != null ? `${(v * 100).toFixed(1)}%` : "—";

  return (
    <div>
      <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 16 }}>
        <StatCard label="Net PnL"     value={fmt$(m.net_pnl)}                 color={(m.net_pnl || 0) >= 0 ? "#86efac" : "#fca5a5"} />
        <StatCard label="Trades"      value={m.trade_count ?? "—"}             color="#94a3b8" />
        <StatCard label="Win Rate"    value={fmtPct(m.win_rate)}               color="#fcd34d" />
        <StatCard label="Avg AI Conf" value={fmtPct(m.avg_ai_confidence)}      color="#c4b5fd" />
        <StatCard label="Signal Conv" value={fmtPct(m.signal_conversion_rate)} color="#7dd3fc" />
      </div>
      {journal.latest_narrative
        ? (
          <div>
            <p style={{ color: "#64748b", fontSize: 11, marginBottom: 6 }}>
              Journal dated {journal.latest_narrative_date || "unknown"}
            </p>
            <pre style={{
              color: "#cbd5e1", fontSize: 12, background: "#0f172a",
              border: "1px solid #1e293b", borderRadius: 6,
              padding: 12, whiteSpace: "pre-wrap", maxHeight: 400, overflowY: "auto",
            }}>
              {journal.latest_narrative}
            </pre>
          </div>
        )
        : <p style={{ color: "#64748b", fontSize: 12 }}>No journal narrative in Debriefs/ yet.</p>
      }
    </div>
  );
}

function AuditTab({ audit }) {
  if (!audit) return <p style={{ color: "#64748b" }}>No audit data.</p>;
  if (audit.error) return <p style={{ color: "#fca5a5" }}>Audit error: {audit.error}</p>;

  if (!audit.sufficient_data) {
    return (
      <div style={{
        background: "#1c1e2b", border: "1px solid #334155",
        borderRadius: 6, padding: 16, color: "#fcd34d",
      }}>
        <strong>Insufficient data: </strong>
        {audit.overlap_warning || "Not enough live trade history for audit."}
      </div>
    );
  }

  const matched = audit.matched || [];
  const cols = ["Symbol", "Strategy", "Live Date", "BT Date", "Live PnL", "BT PnL", "Outcome"];

  return (
    <div>
      <div style={{ marginBottom: 12, color: "#86efac", fontFamily: "JetBrains Mono, monospace" }}>
        Match Rate: {audit.match_rate != null ? (audit.match_rate * 100).toFixed(1) + "%" : "—"}
        {" "}({matched.length} matched)
      </div>
      {matched.length > 0 && (
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12, color: "#cbd5e1" }}>
            <thead>
              <tr>
                {cols.map(h => (
                  <th key={h} style={{
                    padding: "6px 10px", textAlign: "left",
                    borderBottom: "1px solid #334155", color: "#64748b",
                  }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {matched.map((row, i) => {
                const isFlip = (row.outcome_match || "").startsWith("flip");
                return (
                  <tr key={i} style={{ background: i % 2 === 0 ? "#0f172a" : "#0a0d12" }}>
                    {[
                      row.symbol, row.strategy,
                      row.live_date, row.bt_date,
                      row.live_pnl != null ? `$${Number(row.live_pnl).toFixed(2)}` : "—",
                      row.bt_pnl  != null ? `$${Number(row.bt_pnl).toFixed(2)}`  : "—",
                      <span style={{ color: isFlip ? "#fca5a5" : "#86efac" }}>
                        {(row.outcome_match || "—").replace(/_/g, " ")}
                      </span>,
                    ].map((val, ci) => (
                      <td key={ci} style={{ padding: "5px 10px", borderBottom: "1px solid #1e293b" }}>
                        {val}
                      </td>
                    ))}
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

// Expose to parent JSX (no module system available)
window.CockpitExtensions = { RegimeBanner, JournalTab, AuditTab };
