// VerifyView — the public audit trail. Fetches /api/reconciliation and shows the
// decision→order→fill→P&L table (including cancels/rejects and decisions never
// acted on), plus how to verify the Bitcoin-anchored OpenTimestamps proofs.
function VerifyView() {
  const [rec, setRec] = useState(null);
  const [error, setError] = useState(null);
  useEffect(() => {
    const load = async () => {
      try {
        const r = await fetch(`/api/reconciliation?t=${Date.now()}`, { cache: "no-store" });
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        setRec(await r.json());
      } catch (apiErr) {
        try {
          const r = await fetch(`data/reconciliation.json?t=${Date.now()}`, { cache: "no-store" });
          if (!r.ok) throw apiErr;
          setRec(await r.json());
        } catch {
          setError(apiErr.message);
        }
      }
    };
    load();
  }, []);

  if (error) return <div style={{ padding: 40, fontFamily: "var(--mono)" }}>Failed to load audit trail: {error}</div>;
  if (!rec) return <div style={{ height: "60vh", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-3)", fontFamily: "var(--mono)" }}>Loading audit trail…</div>;

  const s = rec.summary || {};
  const bs = s.by_status || {};
  const link = s.decision_link_coverage || {};
  const errs = s.model_errors_14d || {};
  const today = new Date().toISOString().slice(0, 10);
  const pnl = (v) => v == null ? "" : (v >= 0 ? "+" : "") + "$" + Math.abs(v).toLocaleString(undefined, { maximumFractionDigits: 0 });
  const card = { border: "1px solid var(--line)", borderRadius: 10, padding: "14px 16px", background: "var(--bg-card)" };
  const stat = (label, val, sub) => (
    <div style={card}>
      <div style={{ fontSize: 11, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.04em" }}>{label}</div>
      <div style={{ fontSize: 22, fontFamily: "var(--serif)", marginTop: 4 }}>{val}</div>
      {sub && <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2 }}>{sub}</div>}
    </div>
  );

  return (
    <section style={{ paddingTop: 40, paddingBottom: 40 }}>
      <div className="container">
        <div className="eyebrow" style={{ marginBottom: 10 }}>Independently verifiable</div>
        <h2 className="h-section" style={{ marginBottom: 8 }}>The audit trail — including the trades we'd rather you didn't see.</h2>
        <p className="muted" style={{ maxWidth: 760, marginBottom: 24, fontSize: 14 }}>
          Every trade is linked to the AI decision behind it, the Alpaca order id, the broker's fill
          time, and realized P&amp;L. We deliberately show losers, cancelled and dead orders, model
          errors, and decisions the AI made but never acted on. Each day's record is hashed and
          anchored to the Bitcoin blockchain (OpenTimestamps) so it can't be backdated. Generated
          from the database every publish — not hand-authored.
        </p>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 12, marginBottom: 22 }}>
          {stat("Trades on record", s.trades_total ?? "—", `${(bs.FILLED || 0) + (bs.BACKFILL || 0)} filled`)}
          {stat("Cancelled / dead", (bs.CANCELLED || 0) + (bs.ORDER_GONE || 0), "kept, not hidden")}
          {stat("Recommended, not placed", s.recommended_not_placed ?? "—", `${s.placed ?? "—"} were placed`)}
          {stat("Realized P&L", pnl(s.realized_pnl_to_date), "FIFO, to date")}
          {stat("Decision links", `${link.fk || 0} FK`, `${link.matched || 0} matched · ${link.none || 0} backfill`)}
          {stat("Model errors (14d)", `${errs.failed_runs || 0} / ${errs.structured_output_retries || 0}`, "failed runs / retries")}
        </div>

        <div style={{ ...card, marginBottom: 24 }}>
          <div style={{ fontFamily: "var(--serif)", fontSize: 18, marginBottom: 8 }}>Verify it yourself — free, no account</div>
          <p className="muted" style={{ fontSize: 13, marginBottom: 10 }}>
            The day's audit record is anchored to Bitcoin via OpenTimestamps (we pay nothing; you need
            no wallet). Confirm it existed and wasn't edited:
          </p>
          <pre style={{ background: "var(--bg)", border: "1px solid var(--line)", borderRadius: 8, padding: "12px 14px", fontSize: 12, overflowX: "auto", fontFamily: "var(--mono)" }}>{`pip install opentimestamps-client
curl -O /data/audit/${today}.json
curl -O /data/audit/${today}.json.ots
ots verify ${today}.json.ots`}</pre>
          <div style={{ display: "flex", gap: 14, flexWrap: "wrap", fontSize: 12.5, marginTop: 8 }}>
            <a href={`/data/audit/${today}.json`} target="_blank" style={{ color: "var(--accent)" }}>audit record (JSON)</a>
            <a href={`/data/audit/${today}.json.ots`} target="_blank" style={{ color: "var(--accent)" }}>Bitcoin proof (.ots)</a>
            <a href="/api/verify" target="_blank" style={{ color: "var(--accent)" }}>/api/verify</a>
            <a href="/data/broker_activity.json" target="_blank" style={{ color: "var(--accent)" }}>broker-sourced fills</a>
            <a href="/api/reconciliation" target="_blank" style={{ color: "var(--accent)" }}>full reconciliation JSON</a>
          </div>
          <p className="muted" style={{ fontSize: 11.5, marginTop: 10 }}>
            OpenTimestamps proves existence-by-time, not correctness, and is forward-only from launch.
            A "pending" result just means Bitcoin confirmation (a few hours) hasn't landed yet.
          </p>
        </div>

        <div className="card" style={{ padding: "8px 0 4px", overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
            <thead>
              <tr style={{ textAlign: "left", color: "var(--ink-3)", fontSize: 11, textTransform: "uppercase", letterSpacing: "0.04em" }}>
                <th style={{ padding: "8px 12px" }}>Decision time</th>
                <th style={{ padding: "8px 12px" }}>Signal</th>
                <th style={{ padding: "8px 12px" }}>Ticker</th>
                <th style={{ padding: "8px 12px" }}>Side</th>
                <th style={{ padding: "8px 12px" }}>Qty</th>
                <th style={{ padding: "8px 12px" }}>Price</th>
                <th style={{ padding: "8px 12px" }}>Status</th>
                <th style={{ padding: "8px 12px" }}>P&L</th>
                <th style={{ padding: "8px 12px" }}>Alpaca order</th>
              </tr>
            </thead>
            <tbody>
              {(rec.rows || []).slice(0, 60).map((r) => (
                <tr key={r.trade_id} style={{ borderTop: "1px solid var(--line)" }}>
                  <td className="tnum" style={{ padding: "7px 12px", color: "var(--ink-3)" }}>{r.decision_time ? r.decision_time.replace("T", " ").slice(0, 16) : "—"}</td>
                  <td style={{ padding: "7px 12px" }}>{r.signal || "—"}</td>
                  <td style={{ padding: "7px 12px", fontWeight: 600 }}>{r.ticker}</td>
                  <td style={{ padding: "7px 12px", color: r.side === "BUY" ? "var(--pos, #2e7d32)" : "var(--neg, #b3462d)" }}>{r.side}</td>
                  <td className="tnum" style={{ padding: "7px 12px" }}>{r.qty || "—"}</td>
                  <td className="tnum" style={{ padding: "7px 12px" }}>{r.price ? "$" + r.price : "—"}</td>
                  <td style={{ padding: "7px 12px", fontSize: 11 }}>{r.status}</td>
                  <td className="tnum" style={{ padding: "7px 12px", color: (r.realized_pnl || 0) >= 0 ? "var(--pos, #2e7d32)" : "var(--neg, #b3462d)" }}>{r.realized_pnl != null ? pnl(r.realized_pnl) : ""}</td>
                  <td className="tnum" style={{ padding: "7px 12px", color: "var(--ink-3)", fontSize: 10.5 }} title={r.order_id || ""}>{r.order_id ? r.order_id.slice(0, 8) + "…" : "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <p className="muted" style={{ fontSize: 11.5, marginTop: 10 }}>
          Showing the most recent {Math.min((rec.rows || []).length, 60)} of {s.trades_total ?? "—"} trades.
          Decision link: <strong>FK</strong> = hard foreign-key to the decision row; <strong>matched</strong> =
          best-effort by ticker+date; <strong>backfill</strong> = reconciliation row with no stored decision
          (older/manual/orphan fills). Full set at <a href="/api/reconciliation" style={{ color: "var(--accent)" }}>/api/reconciliation</a>.
        </p>
      </div>
    </section>
  );
}
