/* Tract Console v2 — shell views: Login, Sidebar, Deals list, Notifications, Account, Team, Create deal. */
const { Icon: SI, Avatar: SAv, Modal: SModal, useStore: useStoreS, Store: StoreS, useState: uSs, useEffect: uEs } = window;
const Ds = window.V2DATA;

function dealsForRole(state, role) {
  const all = state.order.map((id) => state.deals[id]);
  if (role === "buyer") return all.filter((d) => d.parties.buyer === Ds.PEOPLE.buyer.name);
  return all;
}

/* ---------------- Login ---------------- */
function Login({ onLogin }) {
  const [role, setRole] = uSs("buyer");
  const emails = { advisor: "marcus@tract.co", buyer: "jordan@coastalcap.com", attorney: "dana@whitfieldlegal.com", admin: "priya@tract.co" };
  return (
    <div className="login">
      <div className="brand" style={{ fontSize: 24, marginBottom: 22 }}><span className="glyph" style={{ width: 28, height: 28 }}><i /><i className="on" /><i /><i /></span>Tract</div>
      <div className="login-card">
        <div className="eyebrow">Commercial real estate closings</div>
        <h1 style={{ fontSize: 23, fontWeight: 700, letterSpacing: "-.02em", margin: "6px 0 3px" }}>Sign in</h1>
        <p className="muted" style={{ fontSize: 13.5, marginTop: 0, marginBottom: 20 }}>Choose who you are to explore that workspace.</p>
        <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
          <label><div className="sec-title" style={{ marginBottom: 6 }}>I am the…</div>
            <select className="input" value={role} onChange={(e) => setRole(e.target.value)}>
              <option value="buyer">Buyer — Jordan Reyes</option>
              <option value="advisor">Advisor — Marcus Lee</option>
              <option value="attorney">Attorney — Dana Whitfield</option>
              <option value="admin">Admin — Priya Nair</option>
            </select>
          </label>
          <label><div className="sec-title" style={{ marginBottom: 6 }}>Email</div>
            <div style={{ display: "flex", alignItems: "center", gap: 9, height: 40, padding: "0 13px", border: "1px solid var(--line-2)", borderRadius: "var(--r-sm)", background: "var(--bg)" }}><SI name="mail" size={16} color="var(--ink-3)" /><input value={emails[role]} readOnly style={{ flex: 1, border: "none", outline: "none", background: "transparent", font: "inherit", fontSize: 14, color: "var(--ink)" }} /></div>
          </label>
          <label><div className="sec-title" style={{ marginBottom: 6 }}>Password</div>
            <div style={{ display: "flex", alignItems: "center", gap: 9, height: 40, padding: "0 13px", border: "1px solid var(--line-2)", borderRadius: "var(--r-sm)", background: "var(--bg)" }}><SI name="lock" size={16} color="var(--ink-3)" /><input type="password" defaultValue="demo-password" style={{ flex: 1, border: "none", outline: "none", background: "transparent", font: "inherit", fontSize: 14, color: "var(--ink)" }} /></div>
          </label>
          <button className="btn btn--acc btn--lg" style={{ marginTop: 4 }} onClick={() => onLogin(role)}><SI name="arrow-right" size={17} />Continue</button>
        </div>
        <div style={{ display: "flex", gap: 9, alignItems: "flex-start", fontSize: 12, color: "var(--ink-2)", marginTop: 16, paddingTop: 16, borderTop: "1px solid var(--line)" }}><SI name="shield-check" size={15} color="var(--green)" /><span>Tract prepares documents and runs the workflow. A licensed attorney reviews and approves — it does not give legal advice.</span></div>
      </div>
      <p className="faint" style={{ fontSize: 12, marginTop: 18 }}>Demo · switch personas anytime from the top bar.</p>
    </div>
  );
}

/* ---------------- Sidebar ---------------- */
function Sidebar({ role, view, onView, onSignOut, inDeal, onExitDeal, collapsed }) {
  const st = useStoreS();
  const unread = (Ds.notifications[role] || []).filter((n) => n.unread).length;
  const me = Ds.PEOPLE[role];
  const items = [{ id: "deals", label: "Deals", icon: "building-2" }];
  if (role === "admin") items.push({ id: "team", label: "Team", icon: "users" });
  if (role !== "buyer") items.push({ id: "funds", label: "Funds", icon: "wallet" });
  items.push({ id: "notifs", label: "Notifications", icon: "bell", badge: unread });
  items.push({ id: "account", label: "Account", icon: "user-round" });
  return (
    <aside className="sidebar" style={collapsed ? { flex: "0 0 0px", width: 0, minWidth: 0, paddingLeft: 0, paddingRight: 0, opacity: 0, pointerEvents: "none", borderRight: "none" } : null}>
      <div className="side-brand"><span className="glyph" style={{ width: 22, height: 22 }}><i /><i className="on" /><i /><i /></span>Tract</div>
      <div className="side-sec">Workspace</div>
      {items.map((it) => (
        <button key={it.id} className={"side-item" + (!inDeal && view === it.id ? " side-item--on" : "")} onClick={() => onView(it.id)}>
          <SI name={it.icon} size={18} />{it.label}{it.badge ? <span className="side-item__c">{it.badge}</span> : null}
        </button>
      ))}
      {inDeal && (
        <>
          <div className="side-sec">Open deal</div>
          <button className="side-item side-item--on" onClick={onExitDeal} style={{ background: "var(--bg-soft)", color: "var(--ink)" }}>
            <SI name="dot" size={18} color="var(--green)" /><span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{st.deals[st.activeId] ? st.deals[st.activeId].name : "Deal"}</span>
          </button>
        </>
      )}
      <div className="side-foot">
        <button className="side-item" onClick={onSignOut} style={{ marginBottom: 4 }}><SI name="log-out" size={17} />Sign out</button>
        <div className="uchip" style={{ background: "var(--bg-soft)" }}><SAv who={role} size={32} /><div style={{ minWidth: 0 }}><div style={{ fontWeight: 700, fontSize: 13 }}>{me.name}</div><div className="faint" style={{ fontSize: 11.5 }}>{me.handle}</div></div></div>
      </div>
    </aside>
  );
}

/* ---------------- Deals list ---------------- */
function DealCard({ deal, role, onOpen }) {
  const cm = window.Panels.costModel(deal);
  const active = Ds.STAGES.find((s) => deal.stageState[s.id] === "active");
  const tidbit = deal.frozen ? "Closed · recorded" : role === "buyer" ? "Est. " + Ds.money(cm.estimate) : role === "advisor" ? (cm.needed + " items flagged · " + cm.ordered + " ordered") : role === "attorney" ? "Reviewer · " + deal.state : "Revenue " + Ds.money(cm.advisorEarn + cm.attorneyEarn);
  return (
    <button className="dcard" onClick={onOpen}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 16, letterSpacing: "-.01em" }}>{deal.name}</div>
          <div className="faint" style={{ fontSize: 12.5, marginTop: 2 }}>{deal.address}</div>
        </div>
        {deal.frozen ? <span className="pill pill--dark"><SI name="lock" size={12} />Closed</span> : <span className="pill pill--acc">{active ? active.short : "—"}</span>}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 14, margin: "14px 0 13px" }}>
        <span className="num" style={{ fontWeight: 700, fontSize: 15 }}>{Ds.money(deal.price)}</span>
        <span className="faint" style={{ fontSize: 13 }}>{deal.cap} cap</span>
        <span className="sdots" style={{ marginLeft: "auto" }}>{Ds.STAGES.map((s) => <span key={s.id} className={"sdot sdot--" + deal.stageState[s.id]} title={s.short + " · " + deal.stageState[s.id]} />)}</span>
      </div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", paddingTop: 12, borderTop: "1px solid var(--line)" }}>
        <span style={{ display: "flex" }}>{["advisor", "buyer", "attorney"].map((r, i) => <span key={r} style={{ marginLeft: i ? -7 : 0, borderRadius: "50%", boxShadow: "0 0 0 2px var(--card)" }}><SAv who={r} size={24} /></span>)}</span>
        <span className="faint" style={{ fontSize: 12.5, fontWeight: 600 }}>{tidbit}</span>
      </div>
    </button>
  );
}
function DealsList({ role, onOpen, onNew }) {
  const st = useStoreS();
  const list = dealsForRole(st, role);
  const canCreate = role === "advisor";
  return (
    <div className="wrap" style={{ paddingTop: 22, paddingBottom: 30 }}>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 20, gap: 14, flexWrap: "wrap" }}>
        <div>
          <h1 style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-.025em", margin: 0 }}>{role === "buyer" ? "Your deals" : role === "attorney" ? "Assigned deals" : "Deals"}</h1>
          <p className="muted" style={{ fontSize: 13.5, margin: "4px 0 0" }}>{list.length} deal{list.length === 1 ? "" : "s"} · {role === "buyer" ? "acquisitions you're running with Tract" : role === "attorney" ? "deals where you're the reviewing attorney" : "all active and closed deals"}</p>
        </div>
        {canCreate && <button className="btn btn--acc" onClick={onNew}><SI name="plus" size={16} />New deal</button>}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(330px, 1fr))", gap: 16 }}>
        {list.map((d) => <DealCard key={d.id} deal={d} role={role} onOpen={() => onOpen(d.id)} />)}
        {canCreate && <button className="dcard" onClick={onNew} style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 8, borderStyle: "dashed", color: "var(--ink-3)", minHeight: 150, background: "transparent", boxShadow: "none" }}>
          <SI name="plus" size={24} /><span style={{ fontWeight: 600, fontSize: 14 }}>Start a new deal</span>
        </button>}
      </div>
    </div>
  );
}

/* ---------------- Notifications ---------------- */
function NotificationsView({ role, onOpenDeal }) {
  const list = Ds.notifications[role] || [];
  return (
    <div className="wrap" style={{ paddingTop: 22, paddingBottom: 30, maxWidth: 720 }}>
      <h1 style={{ fontSize: 23, fontWeight: 700, letterSpacing: "-.02em", margin: "0 0 16px" }}>Notifications</h1>
      <div className="card">
        {list.map((n, i) => (
          <div key={i} style={{ display: "flex", gap: 13, padding: "15px 18px", borderTop: i ? "1px solid var(--line)" : "none", alignItems: "flex-start", background: n.unread ? "var(--green-soft)" : "transparent" }}>
            <span style={{ flex: "none", width: 34, height: 34, borderRadius: 9, background: "var(--card)", border: "1px solid var(--line)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-2)" }}><SI name={n.ic} size={17} /></span>
            <div style={{ flex: 1 }}><div style={{ fontWeight: 600, fontSize: 14 }}>{n.t}</div><div className="faint" style={{ fontSize: 12.5, marginTop: 1 }}>{n.s}</div></div>
            <span className="faint" style={{ fontSize: 11.5 }}>{n.at}</span>
          </div>
        ))}
        {list.length === 0 && <div className="empty">You're all caught up.</div>}
      </div>
    </div>
  );
}

/* ---------------- Account ---------------- */
function AccountView({ role }) {
  const me = Ds.PEOPLE[role];
  return (
    <div className="wrap" style={{ paddingTop: 22, paddingBottom: 30, maxWidth: 620 }}>
      <h1 style={{ fontSize: 23, fontWeight: 700, letterSpacing: "-.02em", margin: "0 0 16px" }}>Account</h1>
      <div className="card" style={{ padding: 20 }}>
        <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
          <SAv who={role} size={56} />
          <div><div style={{ fontWeight: 700, fontSize: 18 }}>{me.name}</div><div className="muted" style={{ fontSize: 13.5 }}>{me.handle} · {me.org}</div></div>
        </div>
        <div style={{ marginTop: 18, display: "flex", flexDirection: "column", gap: 12 }}>
          <Field l="Email" v={me.email} />
          <Field l="Role" v={me.handle} />
          <Field l="Two-factor" v="Enabled · authenticator app" />
        </div>
      </div>
    </div>
  );
}
function Field({ l, v }) { return <div style={{ display: "flex", justifyContent: "space-between", paddingBottom: 12, borderBottom: "1px solid var(--line)" }}><span className="muted" style={{ fontSize: 13.5 }}>{l}</span><span style={{ fontWeight: 600, fontSize: 13.5 }}>{v}</span></div>; }

/* ---------------- Team (admin) ---------------- */
function TeamView() {
  const members = [Ds.PEOPLE.advisor, Ds.PEOPLE.attorney, Ds.PEOPLE.admin];
  return (
    <div className="wrap" style={{ paddingTop: 22, paddingBottom: 30, maxWidth: 720 }}>
      <h1 style={{ fontSize: 23, fontWeight: 700, letterSpacing: "-.02em", margin: "0 0 4px" }}>Team</h1>
      <p className="muted" style={{ fontSize: 13.5, margin: "0 0 16px" }}>Advisors and reviewing attorneys onboarded to Tract.</p>
      <div className="card">
        {members.map((m, i) => (
          <div key={m.email} style={{ display: "flex", gap: 13, padding: "15px 18px", borderTop: i ? "1px solid var(--line)" : "none", alignItems: "center" }}>
            <SAv who={m.role} size={38} />
            <div style={{ flex: 1 }}><div style={{ fontWeight: 600, fontSize: 14 }}>{m.name}</div><div className="faint" style={{ fontSize: 12.5 }}>{m.handle} · {m.org}</div></div>
            <span className="pill pill--acc"><SI name="check" size={12} />Active</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------------- Create deal ---------------- */
function CreateDeal({ role, onClose, onDone }) {
  const [f, setF] = uSs({ name: "", address: "", price: "", asset: "Single-tenant NNN retail", st: "FL", buyer: "jordan@coastalcap.com" });
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const price = Number((f.price || "").replace(/[^0-9]/g, "")) || 0;
  const sub = Ds.SUBSCRIPTION;
  const create = () => {
    StoreS.dispatch({ type: "CREATE_DEAL", name: f.name.trim(), address: f.address.trim() || "—", price, asset: f.asset, cap: "—", st: f.st });
    onDone(StoreS.getState().activeId);
  };
  return (
    <SModal icon="building-2" iconColor="var(--green)" title="New deal — invite the buyer" onClose={onClose}
      footer={<><button className="btn btn--ghost" onClick={onClose}>Cancel</button><button className="btn btn--acc" disabled={!f.name.trim() || !f.buyer.trim()} onClick={create}><SI name="send" size={15} />Create &amp; invite buyer</button></>}>
      <p className="muted" style={{ fontSize: 13.5, lineHeight: 1.55, marginTop: 0, marginBottom: 14 }}>As the advisor, you start the deal and invite the buyer. They get an email, pay the Tract subscription to activate, and the deal opens at stage 1 — assessment & valuation.</p>
      <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
        <label><div className="sec-title" style={{ marginBottom: 6 }}>Deal / property name</div><input className="input" value={f.name} onChange={set("name")} placeholder="e.g. Wendy's NNN — Brandon" /></label>
        <label><div className="sec-title" style={{ marginBottom: 6 }}>Address</div><input className="input" value={f.address} onChange={set("address")} placeholder="123 Main St, Tampa, FL" /></label>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <label><div className="sec-title" style={{ marginBottom: 6 }}>Asset type</div><select className="input" value={f.asset} onChange={set("asset")}><option>Single-tenant NNN retail</option><option>Multi-tenant retail plaza</option><option>Single-tenant ground lease</option><option>Office / medical</option></select></label>
          <label><div className="sec-title" style={{ marginBottom: 6 }}>State</div><select className="input" value={f.st} onChange={set("st")}><option value="FL">Florida (FL)</option><option value="GA">Georgia (GA)</option></select></label>
        </div>
        <label><div className="sec-title" style={{ marginBottom: 6 }}>Offer price</div><div style={{ display: "flex", alignItems: "center", gap: 8, height: 40, padding: "0 13px", border: "1px solid var(--line-2)", borderRadius: "var(--r-sm)", background: "var(--bg)" }}><span className="faint">$</span><input value={f.price} onChange={set("price")} placeholder="4,250,000" style={{ flex: 1, border: "none", outline: "none", background: "transparent", font: "inherit", fontSize: 14, color: "var(--ink)" }} /></div></label>
        <label><div className="sec-title" style={{ marginBottom: 6 }}>Invite buyer by email</div><div style={{ display: "flex", alignItems: "center", gap: 9, height: 40, padding: "0 13px", border: "1px solid var(--line-2)", borderRadius: "var(--r-sm)", background: "var(--bg)" }}><SI name="mail" size={16} color="var(--ink-3)" /><input value={f.buyer} onChange={set("buyer")} placeholder="buyer@email.com" style={{ flex: 1, border: "none", outline: "none", background: "transparent", font: "inherit", fontSize: 14, color: "var(--ink)" }} /></div></label>
        <div style={{ border: "1px solid var(--line)", borderRadius: 11, overflow: "hidden" }}>
          <div style={{ display: "flex", justifyContent: "space-between", padding: "11px 14px", borderBottom: "1px solid var(--line)", fontSize: 13 }}><span>Tract subscription — charged to the buyer on accept</span><span className="num" style={{ fontWeight: 600 }}>{Ds.money(sub)}</span></div>
          <div style={{ display: "flex", gap: 9, padding: "10px 14px", background: "var(--bg-soft)", fontSize: 12, color: "var(--ink-2)", lineHeight: 1.45, alignItems: "center" }}><SI name="info" size={15} /><span>Due-diligence items are ordered à la carte later — the buyer only pays for what they choose.</span></div>
        </div>
      </div>
    </SModal>
  );
}

Object.assign(window, { Login, Sidebar, DealsList, NotificationsView, AccountView, TeamView, CreateDeal, FundsView });

/* ---------------- Funds (account-level: payment + refund requests across deals) ---------------- */
function FStat({ l, v, sub, accent }) { return <div className="card" style={{ padding: 15 }}><div className="eyebrow">{l}</div><div className="num" style={{ fontSize: 24, fontWeight: 700, marginTop: 5, color: accent || "var(--ink)" }}>{v}</div><div className="faint" style={{ fontSize: 11.5, marginTop: 2 }}>{sub}</div></div>; }
function FPill({ s }) {
  const M = { requested: ["pill pill--amber", "Requested"], released: ["pill pill--acc", "Released"], approved: ["pill pill--acc", "Approved"], declined: ["pill", "Declined"] };
  const m = M[s] || M.requested;
  return <span className={m[0]}>{(s === "released" || s === "approved") && <SI name="check" size={12} />}{m[1]}</span>;
}
function FundsView({ role, onOpenDeal }) {
  const st = useStoreS();
  const money = Ds.money;
  const deals = st.order.map((id) => st.deals[id]);
  const cm = (d) => window.Panels.costModel(d);
  const [toast, setToast] = uSs(null);

  if (role === "admin") {
    const payouts = deals.flatMap((d) => (d.payouts || []).map((p) => ({ ...p, dealId: d.id, dealName: d.name })));
    const refunds = deals.flatMap((d) => (d.refunds || []).map((r) => ({ ...r, dealId: d.id, dealName: d.name })));
    const pendingPay = payouts.filter((p) => p.status === "requested");
    const pendingRef = refunds.filter((r) => r.status === "requested");
    const collected = deals.reduce((s, d) => s + cm(d).paidNow, 0);
    return (
      <div className="wrap" style={{ paddingTop: 22, paddingBottom: 30, maxWidth: 880 }}>
        <h1 style={{ fontSize: 23, fontWeight: 700, letterSpacing: "-.02em", margin: "0 0 4px" }}>Funds</h1>
        <p className="muted" style={{ fontSize: 13.5, margin: "0 0 18px" }}>Payouts to advisors and attorneys, and buyer refunds — across every deal.</p>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14, marginBottom: 20 }}>
          <FStat l="Collected from buyers" v={money(collected)} sub={deals.length + " deals"} />
          <FStat l="Payouts pending" v={money(pendingPay.reduce((s, p) => s + p.amount, 0))} sub={pendingPay.length + " request" + (pendingPay.length === 1 ? "" : "s")} accent="var(--amber)" />
          <FStat l="Refunds pending" v={money(pendingRef.reduce((s, r) => s + r.amount, 0))} sub={pendingRef.length + " request" + (pendingRef.length === 1 ? "" : "s")} accent="var(--amber)" />
        </div>
        <div className="card" style={{ marginBottom: 16 }}>
          <div className="card__h" style={{ justifyContent: "space-between" }}><span className="card__t">Payout requests</span><span className="pill">{pendingPay.length} pending</span></div>
          <div className="card__b" style={{ paddingTop: 4, paddingBottom: 4 }}>
            {payouts.length === 0 ? <div className="muted" style={{ fontSize: 13, padding: "8px 0" }}>No payout requests.</div>
              : payouts.map((p) => (
                <div key={p.dealId + p.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 0", borderTop: "1px solid var(--line)" }}>
                  <SAv who={p.role} size={32} />
                  <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontWeight: 600, fontSize: 13.5 }}>{p.who} <span className="faint" style={{ fontWeight: 500 }}>· {Ds.PEOPLE[p.role].handle}</span></div><button onClick={() => onOpenDeal(p.dealId)} className="faint" style={{ border: "none", background: "none", padding: 0, cursor: "pointer", fontSize: 12, textDecoration: "underline", textUnderlineOffset: 2 }}>{p.dealName}</button><span className="faint" style={{ fontSize: 12 }}> · {money(p.amount)} · {p.at}</span></div>
                  {p.status === "requested" ? <button className="btn btn--acc btn--sm" onClick={() => { StoreS.dispatch({ type: "RELEASE_PAYOUT", dealId: p.dealId, id: p.id }); setToast("Payout released"); }}><SI name="banknote" size={14} />Release</button> : <FPill s={p.status} />}
                </div>
              ))}
          </div>
        </div>
        <div className="card">
          <div className="card__h" style={{ justifyContent: "space-between" }}><span className="card__t">Refund requests</span><span className="pill">{pendingRef.length} pending</span></div>
          <div className="card__b" style={{ paddingTop: 4, paddingBottom: 4 }}>
            {refunds.length === 0 ? <div className="muted" style={{ fontSize: 13, padding: "8px 0" }}>No refund requests.</div>
              : refunds.map((r) => (
                <div key={r.dealId + r.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 0", borderTop: "1px solid var(--line)" }}>
                  <SAv who="buyer" size={32} />
                  <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontWeight: 600, fontSize: 13.5 }}>{r.who} · {money(r.amount)}</div><span className="faint" style={{ fontSize: 12 }}>{r.reason} · </span><button onClick={() => onOpenDeal(r.dealId)} className="faint" style={{ border: "none", background: "none", padding: 0, cursor: "pointer", fontSize: 12, textDecoration: "underline", textUnderlineOffset: 2 }}>{r.dealName}</button></div>
                  {r.status === "requested" ? <span style={{ display: "flex", gap: 6 }}><button className="btn btn--ghost btn--sm" onClick={() => { StoreS.dispatch({ type: "RESOLVE_REFUND", dealId: r.dealId, id: r.id, status: "declined" }); setToast("Refund declined"); }}>Decline</button><button className="btn btn--acc btn--sm" onClick={() => { StoreS.dispatch({ type: "RESOLVE_REFUND", dealId: r.dealId, id: r.id, status: "approved" }); setToast("Refund approved"); }}><SI name="check" size={14} />Approve</button></span> : <FPill s={r.status} />}
                </div>
              ))}
          </div>
        </div>
        {toast && <window.Toast msg={toast} onDone={() => setToast(null)} />}
      </div>
    );
  }

  // advisor / attorney
  const myName = Ds.PEOPLE[role].name;
  const rows = deals.map((d) => ({ d, earn: role === "attorney" ? cm(d).attorneyEarn : cm(d).advisorEarn, req: (d.payouts || []).find((p) => p.role === role) }));
  const totalEarn = rows.reduce((s, r) => s + r.earn, 0);
  const pending = rows.filter((r) => r.req && r.req.status === "requested").reduce((s, r) => s + r.req.amount, 0);
  const released = rows.filter((r) => r.req && r.req.status === "released").reduce((s, r) => s + r.req.amount, 0);
  return (
    <div className="wrap" style={{ paddingTop: 22, paddingBottom: 30, maxWidth: 820 }}>
      <h1 style={{ fontSize: 23, fontWeight: 700, letterSpacing: "-.02em", margin: "0 0 4px" }}>Funds</h1>
      <p className="muted" style={{ fontSize: 13.5, margin: "0 0 18px" }}>Your fees across every deal. Request a payout once your work on a deal is done — admin releases it.</p>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14, marginBottom: 20 }}>
        <FStat l="Total earned" v={money(totalEarn)} sub={deals.length + " deals"} />
        <FStat l="Requested" v={money(pending)} sub="awaiting admin" accent="var(--amber)" />
        <FStat l="Released" v={money(released)} sub="paid out" accent="var(--green-700)" />
      </div>
      <div className="card">
        <div className="card__h"><span className="card__t">Your deals</span></div>
        <div className="card__b" style={{ paddingTop: 4, paddingBottom: 4 }}>
          {rows.map((r, i) => (
            <div key={r.d.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "13px 0", borderTop: i ? "1px solid var(--line)" : "none" }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <button onClick={() => onOpenDeal(r.d.id)} style={{ border: "none", background: "none", padding: 0, cursor: "pointer", fontWeight: 600, fontSize: 13.5, color: "var(--ink)", textAlign: "left" }}>{r.d.name}</button>
                <div className="faint" style={{ fontSize: 12 }}>{money(r.earn)} earned{r.req ? " · requested " + r.req.at : ""}</div>
              </div>
              {!r.req ? <button className="btn btn--primary btn--sm" onClick={() => { StoreS.dispatch({ type: "REQUEST_PAYOUT", dealId: r.d.id, who: myName, role, amount: r.earn }); setToast("Payout requested"); }}><SI name="arrow-down-left" size={14} />Request payout</button> : <FPill s={r.req.status} />}
            </div>
          ))}
        </div>
      </div>
      {toast && <window.Toast msg={toast} onDone={() => setToast(null)} />}
    </div>
  );
}
