// =============================================================================
// MARKET MARK TAB — Trading ecosystem boss
// Alpaca paper trading → live after ≥1 month vetted + approved.
// Boss: Market Mark Boss (claude-sonnet-4-6)
// Approve/Reject trade proposals before any order is placed.
// =============================================================================

(function () {
  const { useState } = React;
  const { C } = window.JD_THEME;
  const { card, ct, inp, bg, br, bgg, Empty, Loading, ErrorBox } = window.JD_STYLES;

  function MarketMark() {
    const finQ = window.useJarvisData("finance");
    const fin = finQ.data || {};
    const [bossMsg, setBossMsg] = useState("");
    const [bossMsgs, setBossMsgs] = useState([]);

    const sendBoss = async () => {
      if (!bossMsg.trim()) return;
      const msg = bossMsg;
      setBossMsgs(m => [...m, { role: "user", msg }]);
      setBossMsg("");
      try {
        const reply = await window.JD.mutate("sendMarketMarkMessage", msg);
        if (reply && reply.msg) setBossMsgs(m => [...m, reply]);
      } catch (e) {
        setBossMsgs(m => [...m, { role: "assistant", msg: "Agent error: " + e.message }]);
      }
    };

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {/* Header */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div>
            <div style={{ fontSize: 22, color: C.gold }}>Market Mark</div>
            <div style={{ fontSize: 14, color: C.muted, marginTop: 2 }}>Paper trading · Alpaca · Vetting phase</div>
          </div>
          <div style={{ padding: "6px 14px", borderRadius: 20, background: "rgba(212,160,23,0.12)", border: "0.5px solid rgba(212,160,23,0.35)", fontSize: 13, color: C.yellow }}>
            Paper Trading Mode
          </div>
        </div>

        {/* Portfolio + pending trades */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <div style={card()}>
            <div style={ct}>Portfolio · Alpaca</div>
            <div style={{ fontSize: 36, color: fin.alpacaBalance ? C.cream : C.muted, fontVariantNumeric: "tabular-nums", margin: "6px 0 2px" }}>
              {fin.alpacaBalance || "—"}
            </div>
            <div style={{ fontSize: 14, color: C.muted, marginBottom: 12 }}>
              {fin.alpacaBalance ? "via Alpaca adapter" : "Connect Alpaca API via adapter to populate"}
            </div>
            {(fin.positions || []).length === 0
              ? <Empty label="No positions" sub="Wire Alpaca adapter to see holdings" />
              : (fin.positions || []).map(([t, q, v, d, c]) => (
                <div key={t} style={{ display: "flex", justifyContent: "space-between", padding: "7px 0", borderBottom: "0.5px solid " + C.border, fontSize: 15 }}>
                  <span style={{ color: C.cream, fontWeight: 500 }}>{t}</span>
                  <span style={{ color: c }}>{v}</span>
                </div>
              ))
            }
          </div>

          <div style={card({ border: "0.5px solid rgba(212,160,23,0.25)" })}>
            <div style={{ fontSize: 13, color: C.yellow, letterSpacing: "0.16em", textTransform: "uppercase", marginBottom: 10 }}>
              Pending Trade Proposals
            </div>
            {finQ.loading ? <Loading /> :
             (fin.pendingTrades || []).length === 0
              ? <Empty label="No trades pending approval" sub="Market Mark will surface proposals here" />
              : (fin.pendingTrades || []).map((tr, i) => (
                <div key={i} style={{ padding: "10px 12px", background: "rgba(212,160,23,0.08)", borderRadius: 8, border: "0.5px solid rgba(212,160,23,0.2)", marginBottom: 8 }}>
                  <div style={{ fontSize: 15, color: C.yellow, marginBottom: 4 }}>
                    {tr.symbol} · {tr.side} · {tr.qty} shares
                  </div>
                  <div style={{ fontSize: 13, color: C.muted, marginBottom: 8, lineHeight: 1.5 }}>{tr.rationale}</div>
                  <div style={{ display: "flex", gap: 6 }}>
                    <button onClick={() => window.JD.mutate("approveTrade", tr.symbol).then(() => finQ.reload())} style={bgg}>Approve</button>
                    <button onClick={() => window.JD.mutate("rejectTrade", tr.symbol).then(() => finQ.reload())} style={br}>Reject</button>
                  </div>
                </div>
              ))
            }
          </div>
        </div>

        {/* Agent team + boss chat */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <div style={card()}>
            <div style={ct}>Agent Team</div>
            <Empty label="No agents registered yet" sub="Strategy Researcher · Signal Detector · Trade Proposer · Risk Checker" />
          </div>

          <div style={card()}>
            <div style={ct}>Talk to Market Mark Boss</div>
            <div style={{ maxHeight: 160, overflow: "auto", marginBottom: 8, padding: "6px 0" }}>
              {bossMsgs.length === 0
                ? <div style={{ fontSize: 13, color: C.muted, fontStyle: "italic", textAlign: "center", padding: "12px 0" }}>No messages yet</div>
                : bossMsgs.map((m, i) => (
                  <div key={i} style={{ marginBottom: 8, padding: "6px 8px", background: m.role === "user" ? "rgba(159,117,9,0.06)" : "rgba(212,160,23,0.06)", borderRadius: 6, border: "0.5px solid " + (m.role === "user" ? "rgba(159,117,9,0.15)" : "rgba(212,160,23,0.2)") }}>
                    <div style={{ fontSize: 11, color: m.role === "user" ? C.gold : C.yellow, letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 2 }}>{m.role === "user" ? "You" : "Market Mark"}</div>
                    <div style={{ fontSize: 14, color: "rgba(222,214,185,0.82)", lineHeight: 1.5 }}>{m.msg}</div>
                  </div>
                ))
              }
            </div>
            <div style={{ display: "flex", gap: 6 }}>
              <input value={bossMsg} onChange={e => setBossMsg(e.target.value)} onKeyDown={e => e.key === "Enter" && sendBoss()} placeholder="Ask Market Mark..." style={{ ...inp, flex: 1 }} />
              <button onClick={sendBoss} style={bg}>Send</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.JD_TABS = window.JD_TABS || {};
  window.JD_TABS["Market Mark"] = MarketMark;
})();
