// =============================================================================
// FINANCE TAB
// Top-line metrics, Novo balance + cashflow chart, Alpaca + pending trades,
// recent transactions, upcoming bills, spend-by-category.
// =============================================================================

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

  function Finance() {
    const financeQ = window.useJarvisData("finance");
    const fin = financeQ.data || {};
    const series = fin.series || [];
    const transactions = fin.transactions || [];
    const bills = fin.bills || [];
    const spend = fin.spendCategories || [];
    const positions = fin.positions || [];
    const pending = fin.pendingTrades || [];

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {financeQ.error && <ErrorBox message={financeQ.error.message} />}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12 }}>
          {[
            ["Total Liquid", fin.totalLiquid, C.green, fin.totalLiquid ? "across business + brokerage" : "connect via adapter"],
            ["Revenue MTD",  fin.revenueMTD,  C.gold,  "—"],
            ["Expenses MTD", fin.expensesMTD, C.red,   "—"],
            ["Bills Due 7d", fin.billsDue7d,  C.yellow, "—"],
          ].map(([l, v, c, sub]) => (
            <div key={l} style={card()}>
              <div style={{ fontSize: 12, color: C.muted, letterSpacing: "0.16em", textTransform: "uppercase", marginBottom: 6 }}>{l}</div>
              <div style={{ fontSize: 30, color: v ? c : C.muted, fontVariantNumeric: "tabular-nums" }}>{v || "—"}</div>
              <div style={{ fontSize: 13, color: C.muted, marginTop: 3 }}>{sub}</div>
            </div>
          ))}
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <div style={card()}>
            <div style={ct}>Business Banking · Novo</div>
            <div style={{ fontSize: 36, color: C.cream, margin: "8px 0 4px", fontVariantNumeric: "tabular-nums" }}>{fin.novoBalance || "—"}</div>
            <div style={{ fontSize: 14, color: C.muted, marginBottom: 10 }}>via adapter</div>
            <div style={{ fontSize: 12, color: C.muted, letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 6 }}>30-Day Cash Flow</div>
            <div style={{ height: 90, marginBottom: 8 }}>
              {financeQ.loading ? <Loading /> :
               series.length > 0 ? (
                <svg width="100%" height="90" viewBox="0 0 300 90" preserveAspectRatio="none">
                  <polyline points={series.map((d, i) => (i * 10) + "," + (90 - (d.in / 5000) * 82)).join(" ")} fill="none" stroke={C.green} strokeWidth="2" />
                  <polyline points={series.map((d, i) => (i * 10) + "," + (90 - (d.out / 5000) * 82)).join(" ")} fill="none" stroke={C.red} strokeWidth="2" />
                </svg>
              ) : <Empty label="No data" />}
            </div>
            {[["Revenue MTD", fin.revenueMTD], ["Expenses MTD", fin.expensesMTD], ["Net MTD", fin.netMTD], ["Avg Daily Inflow", fin.avgDailyInflow]].map(([l, v]) => (
              <div key={l} style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderBottom: "0.5px solid " + C.border, fontSize: 15 }}>
                <span style={{ color: "rgba(222,214,185,0.78)" }}>{l}</span><span style={{ color: C.muted }}>{v || "—"}</span>
              </div>
            ))}
          </div>
          <div style={card()}>
            <div style={ct}>Trading · Alpaca</div>
            <div style={{ fontSize: 36, color: C.cream, margin: "8px 0 4px", fontVariantNumeric: "tabular-nums" }}>{fin.alpacaBalance || "—"}</div>
            <div style={{ fontSize: 14, color: C.muted, marginBottom: 12 }}>via adapter</div>
            {pending.length === 0 && <Empty label="No pending trade requests" />}
            {pending.map((tr, i) => (
              <div key={i} style={{ padding: "10px 12px", background: "rgba(212,160,23,0.1)", borderRadius: 8, border: "0.5px solid rgba(212,160,23,0.3)", marginBottom: 12 }}>
                <div style={{ fontSize: 14, color: C.yellow, marginBottom: 6, fontWeight: 500 }}>{tr.symbol} {tr.side} · {tr.qty} sh · ${tr.price} · Pending approval</div>
                <div style={{ fontSize: 12, color: C.muted, marginBottom: 8 }}>Agent rationale: {tr.rationale}</div>
                <div style={{ display: "flex", gap: 6 }}>
                  <button onClick={() => window.JD.mutate("approveTrade", tr.symbol).then(() => financeQ.reload())} style={bgg}>Approve</button>
                  <button onClick={() => window.JD.mutate("rejectTrade", tr.symbol).then(() => financeQ.reload())} style={br}>Reject</button>
                  <button style={{ ...bg, fontSize: 13 }}>Ask Why</button>
                </div>
              </div>
            ))}
            {positions.map(([t, q, v, d, c]) => (
              <div key={t} style={{ display: "grid", gridTemplateColumns: "1fr 60px 90px 70px", gap: 8, padding: "8px 0", borderBottom: "0.5px solid " + C.border, fontSize: 14, alignItems: "baseline" }}>
                <span style={{ color: C.cream, fontWeight: 500 }}>{t}</span>
                <span style={{ color: C.muted, fontSize: 13 }}>{q}</span>
                <span style={{ color: C.cream, fontVariantNumeric: "tabular-nums", textAlign: "right" }}>{v}</span>
                <span style={{ color: c, fontSize: 13, textAlign: "right" }}>{d}</span>
              </div>
            ))}
          </div>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 14 }}>
          <div style={card()}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
              <div style={ct}>Recent Transactions</div>
              <span style={{ fontSize: 13, color: C.muted }}>Last 7 days</span>
            </div>
            {transactions.length === 0 ? <Empty label="No transactions" /> : transactions.map((t, i) => (
              <div key={i} style={{ display: "grid", gridTemplateColumns: "60px 1fr 90px 100px", gap: 10, padding: "9px 0", borderBottom: "0.5px solid " + C.border, fontSize: 14, alignItems: "center" }}>
                <span style={{ color: C.muted, fontSize: 13 }}>{t.d}</span>
                <span style={{ color: C.cream }}>{t.p}</span>
                <span style={{ fontSize: 11, padding: "2px 8px", borderRadius: 10, background: "rgba(74,159,212,0.12)", color: C.blue, letterSpacing: "0.08em", justifySelf: "start" }}>{t.cat}</span>
                <span style={{ color: t.c, fontVariantNumeric: "tabular-nums", textAlign: "right" }}>{t.a}</span>
              </div>
            ))}
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div style={card()}>
              <div style={ct}>Upcoming Bills</div>
              {bills.length === 0 ? <Empty label="No bills" /> : bills.map(([n, a, d, c]) => (
                <div key={n} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 0", borderBottom: "0.5px solid " + C.border, fontSize: 14 }}>
                  <div>
                    <div style={{ color: C.cream }}>{n}</div>
                    <div style={{ color: C.muted, fontSize: 12 }}>Due {d}</div>
                  </div>
                  <span style={{ color: c, fontVariantNumeric: "tabular-nums" }}>{a}</span>
                </div>
              ))}
            </div>
            <div style={card()}>
              <div style={ct}>Spend by Category · MTD</div>
              {spend.length === 0 ? <Empty label="No data" /> : spend.map(([l, v, p, c]) => (
                <div key={l} style={{ padding: "6px 0" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14, marginBottom: 3 }}>
                    <span style={{ color: "rgba(222,214,185,0.82)" }}>{l}</span>
                    <span style={{ color: c, fontVariantNumeric: "tabular-nums" }}>{v}</span>
                  </div>
                  <div style={{ height: 4, background: "rgba(222,214,185,0.08)", borderRadius: 2, overflow: "hidden" }}><div style={{ width: (p * 100) + "%", height: "100%", background: c }} /></div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.JD_TABS = window.JD_TABS || {};
  window.JD_TABS.Finance = Finance;
})();
