// Recursive MLS — Admin screens (super-admin back office).
// Four screens: Admin dashboard, Agents & users, Compliance, Moderation.
// Reuses btnPrimary/btnOutline (Dashboard.jsx) and Icon (Chrome.jsx).

function pill(map, k, sm) { const c = map[k] || { c: "#6b706a", b: "#f0efe9" }; return { fontSize: sm ? 10.5 : 11, fontWeight: 600, color: c.c, background: c.b, borderRadius: 999, padding: sm ? "2px 8px" : "3px 10px", whiteSpace: "nowrap", display: "inline-block" }; }

// ============ ADMIN DASHBOARD ============
function AdminDashboard({ go }) {
  const A = window.RC_ADMIN;
  const s = A.stats;
  const Stat = ({ label, val, sub, tone, icon }) => (
    <div style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "15px 17px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 9 }}>
        <span style={{ width: 30, height: 30, borderRadius: 8, background: tone.b, display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name={icon} size={16} color={tone.c} /></span>
        <span style={{ fontSize: 11, fontWeight: 600, textTransform: "uppercase", letterSpacing: ".7px", color: "#8a8e88" }}>{label}</span>
      </div>
      <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 25, fontWeight: 700, letterSpacing: "-0.8px", color: "#1d241f", lineHeight: 1 }}>{val}</div>
      {sub && <div style={{ fontSize: 12, color: "#8a8e88", marginTop: 5 }}>{sub}</div>}
    </div>
  );
  const tealT = { c: "#2a6f8a", b: "#e8f0f3" }, greenT = { c: "#1f8a5b", b: "#e8f4ee" }, orangeT = { c: "#c0612f", b: "#faece3" }, amberT = { c: "#9a6a12", b: "#fbf2dc" };
  return (
    <div style={{ padding: "22px 28px 60px", maxWidth: 1280, margin: "0 auto" }}>
      <div style={{ marginBottom: 18 }}>
        <h1 style={{ margin: 0, fontSize: 25, fontWeight: 600, letterSpacing: "-0.6px", color: "#1d241f" }}>Administrator dashboard</h1>
        <p style={{ margin: "5px 0 0", fontSize: 14, color: "#8a8e88" }}>MLS-wide operations — members, compliance, and message moderation across {A.stats.offices.toLocaleString()} offices.</p>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 14 }}>
        <Stat label="Total agents" val={s.agents.toLocaleString()} sub={`${s.active30d.toLocaleString()} active · 30d`} tone={tealT} icon="users-round" />
        <Stat label="Pending / suspended" val={`${s.pending} / ${s.suspended}`} sub="awaiting action" tone={amberT} icon="user-cog" />
        <Stat label="Open compliance" val={s.complianceOpen} sub={`${s.complianceCritical} critical`} tone={orangeT} icon="shield-alert" />
        <Stat label="Fines outstanding" val={A.usd(s.finesOutstanding)} sub="across the MLS" tone={greenT} icon="badge-dollar-sign" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <Card title="Compliance needing review" action={<LinkBtn onClick={() => go("admin_compliance")}>Open compliance</LinkBtn>}>
          {A.issues.filter((i) => i.status === "Open").slice(0, 4).map((i) => (
            <Row key={i.id} onClick={() => go("admin_compliance")}>
              <span style={pill(A.sevColor, i.severity, true)}>{i.severity}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{i.ruleTitle}</div>
                <div style={{ fontSize: 11.5, color: "#8a8e88" }}>{i.listing} · {i.agent}</div>
              </div>
              <span style={{ fontSize: 11, color: "#bcbfba" }}>{i.detected}</span>
            </Row>
          ))}
        </Card>
        <Card title="Moderation queue" action={<LinkBtn onClick={() => go("admin_moderation")}>Open moderation</LinkBtn>}>
          {A.modQueue.filter((m) => m.status !== "Dismissed").slice(0, 4).map((m) => (
            <Row key={m.id} onClick={() => go("admin_moderation")}>
              <span style={pill(A.modStatusColor, m.status, true)}>{m.status}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f" }}>{m.policy}</div>
                <div style={{ fontSize: 11.5, color: "#8a8e88", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{m.from} → {m.to}</div>
              </div>
              <span style={{ fontSize: 11, color: "#bcbfba" }}>{m.time}</span>
            </Row>
          ))}
        </Card>
      </div>

      <div style={{ marginTop: 14 }}>
        <Card title="Member management" action={<LinkBtn onClick={() => go("admin_users")}>Manage agents & users</LinkBtn>}>
          <div style={{ display: "flex", gap: 24, flexWrap: "wrap", padding: "4px 2px" }}>
            {[["Add a new agent", "user-plus"], ["Review 38 pending invites", "user-check"], ["12 suspended accounts", "user-x"], ["License renewals due", "badge-alert"]].map(([t, ic]) => (
              <button key={t} onClick={() => go("admin_users")} style={{ display: "inline-flex", alignItems: "center", gap: 8, fontFamily: "inherit", fontSize: 13, fontWeight: 600, color: "#006747", background: "none", border: 0, cursor: "pointer" }}>
                <Icon name={ic} size={16} color="#006747" /> {t}
              </button>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

// ============ AGENTS & USERS ============
function AdminUsers() {
  const A = window.RC_ADMIN;
  const [q, setQ] = useState("");
  const [status, setStatus] = useState("All");
  const [sel, setSel] = useState(null);
  const [page, setPage] = useState(1);
  const totalPages = Math.ceil(A.stats.agents / 8);
  let rows = A.agents.filter((u) => (status === "All" || u.status === status) && (!q || u.name.toLowerCase().includes(q.toLowerCase()) || u.email.toLowerCase().includes(q.toLowerCase()) || u.office.toLowerCase().includes(q.toLowerCase())));

  return (
    <div style={{ padding: "22px 28px 40px", height: "100%", boxSizing: "border-box", display: "flex", flexDirection: "column", maxWidth: 1320, margin: "0 auto" }}>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 14, flexWrap: "wrap", marginBottom: 16 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 25, fontWeight: 600, letterSpacing: "-0.6px", color: "#1d241f" }}>Agents &amp; users</h1>
          <p style={{ margin: "5px 0 0", fontSize: 14, color: "#8a8e88" }}>{A.stats.agents.toLocaleString()} members · {A.stats.offices.toLocaleString()} offices · {A.stats.pending} pending · {A.stats.suspended} suspended</p>
        </div>
        <button style={btnPrimary}><Icon name="user-plus" size={15} color="#fff" /> Add Agent</button>
      </div>

      {/* search + filters (server-side at scale) */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14, flexWrap: "wrap" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, background: "#fff", borderRadius: 8, padding: "9px 12px", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.1)", flex: 1, minWidth: 240 }}>
          <Icon name="search" size={15} color="#a8aca6" />
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search 104,200 members by name, email, office, or license…" style={{ flex: 1, border: 0, outline: 0, background: "transparent", fontFamily: "inherit", fontSize: 13.5 }} />
        </div>
        <div style={{ display: "inline-flex", background: "#fff", borderRadius: 8, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.08)", padding: 3 }}>
          {["All", "Active", "Pending", "Flagged", "Suspended"].map((f) => (
            <button key={f} onClick={() => setStatus(f)} style={{ fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, cursor: "pointer", border: 0, borderRadius: 6, padding: "6px 12px",
              background: status === f ? "#006747" : "transparent", color: status === f ? "#fff" : "#6b706a" }}>{f}</button>
          ))}
        </div>
        <button style={btnOutline}><Icon name="upload" size={15} color="#006747" /> Bulk Import</button>
      </div>

      {/* table */}
      <div style={{ flex: 1, minHeight: 0, background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <div style={{ flex: 1, overflowY: "auto" }}>
          <table style={{ borderCollapse: "collapse", width: "100%" }}>
            <thead style={{ position: "sticky", top: 0, background: "#faf9f5", zIndex: 1 }}>
              <tr>
                {["Member", "Office", "Role", "License", "Listings", "Status", ""].map((h, i) => (
                  <th key={i} style={{ textAlign: i === 4 ? "center" : "left", padding: "11px 16px", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".6px", color: "#a8aca6", borderBottom: "2px solid #ececec", whiteSpace: "nowrap" }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {rows.map((u) => (
                <tr key={u.id} onClick={() => setSel(u)} className="rc-row" style={{ cursor: "pointer", borderBottom: "1px solid #f4f3ee" }}>
                  <td style={{ padding: "10px 16px" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <span style={{ width: 32, height: 32, borderRadius: "50%", background: "#e7e1d4", color: "#006747", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 700, flex: "none" }}>{u.initials}</span>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f" }}>{u.name}</div>
                        <div style={{ fontSize: 11.5, color: "#a8aca6" }}>{u.email}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ padding: "10px 16px", fontSize: 12.5, color: "#4a504a" }}>{u.office}</td>
                  <td style={{ padding: "10px 16px", fontSize: 12.5, color: "#4a504a" }}>{u.role}</td>
                  <td style={{ padding: "10px 16px", fontSize: 12, color: "#4a504a", fontFamily: "'Space Mono', monospace" }}>
                    {u.license}{u.licenseAlert && <span title="License expiring" style={{ marginLeft: 6, color: "#c0612f" }}>⚠</span>}
                  </td>
                  <td style={{ padding: "10px 16px", fontSize: 13, color: "#1d241f", textAlign: "center", fontFamily: "'Space Mono', monospace" }}>{u.listings}</td>
                  <td style={{ padding: "10px 16px" }}><span style={pill(A.statusColor, u.status, true)}>{u.status}</span>{u.compliance > 0 && <span title={`${u.compliance} compliance issues`} style={{ marginLeft: 6, fontSize: 10.5, fontWeight: 700, color: "#c0612f" }}>⚑{u.compliance}</span>}</td>
                  <td style={{ padding: "10px 16px" }}><Icon name="chevron-right" size={16} color="#c4c7c1" /></td>
                </tr>
              ))}
            </tbody>
          </table>
          {rows.length === 0 && <div style={{ padding: 40, textAlign: "center", fontSize: 13, color: "#a8aca6" }}>No members match.</div>}
        </div>
        {/* pagination — only a page is loaded at a time (scales to 100k) */}
        <div style={{ flex: "none", display: "flex", alignItems: "center", justifyContent: "space-between", padding: "11px 16px", borderTop: "1px solid #f1f0ea" }}>
          <span style={{ fontSize: 12, color: "#8a8e88" }}>Showing <b style={{ fontFamily: "'Space Mono', monospace", color: "#1d241f" }}>1–{rows.length}</b> of <b style={{ fontFamily: "'Space Mono', monospace", color: "#1d241f" }}>{A.stats.agents.toLocaleString()}</b></span>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <button onClick={() => setPage(Math.max(1, page - 1))} style={{ ...btnOutline, padding: "6px 10px", fontSize: 12.5 }}><Icon name="chevron-left" size={14} color="#006747" /> Prev</button>
            <span style={{ fontSize: 12.5, color: "#4a504a", fontFamily: "'Space Mono', monospace", padding: "0 6px" }}>{page} / {totalPages.toLocaleString()}</span>
            <button onClick={() => setPage(page + 1)} style={{ ...btnOutline, padding: "6px 10px", fontSize: 12.5 }}>Next <Icon name="chevron-right" size={14} color="#006747" /></button>
          </div>
        </div>
      </div>

      {sel && <UserDrawer u={sel} A={A} onClose={() => setSel(null)} />}
    </div>
  );
}

function UserDrawer({ u, A, onClose }) {
  const [role, setRole] = useState(u.role);
  const [status, setStatus] = useState(u.status);
  const field = (label, val) => (
    <div style={{ display: "flex", justifyContent: "space-between", padding: "9px 0", borderBottom: "1px solid #f4f3ee", fontSize: 13 }}>
      <span style={{ color: "#8a8e88" }}>{label}</span><span style={{ color: "#1d241f", fontWeight: 600 }}>{val}</span>
    </div>
  );
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(20,24,20,.32)", zIndex: 60, display: "flex", justifyContent: "flex-end" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 420, maxWidth: "92vw", height: "100%", background: "#fbfaf7", boxShadow: "-8px 0 30px rgba(0,0,0,.2)", display: "flex", flexDirection: "column" }}>
        <div style={{ flex: "none", padding: "18px 20px", background: "#fff", borderBottom: "1px solid #f1f0ea", display: "flex", alignItems: "center", gap: 13 }}>
          <span style={{ width: 46, height: 46, borderRadius: "50%", background: "#006747", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16, fontWeight: 600, flex: "none" }}>{u.initials}</span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 17, fontWeight: 600, color: "#1d241f" }}>{u.name}</div>
            <div style={{ fontSize: 12.5, color: "#8a8e88" }}>{u.email}</div>
          </div>
          <button onClick={onClose} style={{ border: "1px solid #e2e0d8", background: "#fff", borderRadius: 7, width: 32, height: 32, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", flex: "none" }}><Icon name="x" size={16} color="#4a504a" /></button>
        </div>
        <div style={{ flex: 1, overflowY: "auto", padding: 20 }}>
          {u.licenseAlert && <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "10px 12px", borderRadius: 8, background: "#faece3", marginBottom: 16, fontSize: 12.5, color: "#9a4a24" }}><Icon name="badge-alert" size={16} color="#c0612f" /> License expires {u.licenseExp} — renewal reminder recommended.</div>}

          <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".6px", color: "#a8aca6", marginBottom: 6 }}>Role</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 7, marginBottom: 18 }}>
            {A.roles.map((r) => <button key={r} onClick={() => setRole(r)} style={{ fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, cursor: "pointer", padding: "6px 12px", borderRadius: 999, border: role === r ? "1px solid #006747" : "1px solid #e2e0d8", background: role === r ? "#eef4f1" : "#fff", color: role === r ? "#006747" : "#4a504a" }}>{r}</button>)}
          </div>

          <div style={{ background: "#fff", borderRadius: 8, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "4px 14px", marginBottom: 18 }}>
            {field("Office", u.office)}
            {field("License", u.license)}
            {field("License expires", u.licenseExp)}
            {field("Active listings", u.listings)}
            {field("Member since", u.joined)}
            {field("Last active", u.lastActive)}
            {field("Open compliance", u.compliance)}
          </div>

          <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".6px", color: "#a8aca6", marginBottom: 8 }}>Account status</div>
          <div style={{ display: "flex", gap: 8, marginBottom: 8 }}>
            {["Active", "Suspended"].map((st) => <button key={st} onClick={() => setStatus(st)} style={{ flex: 1, justifyContent: "center", display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "inherit", fontSize: 13, fontWeight: 600, cursor: "pointer", padding: "9px", borderRadius: 8, border: status === st ? `1px solid ${st === "Suspended" ? "#b3261e" : "#006747"}` : "1px solid #e2e0d8", background: status === st ? (st === "Suspended" ? "#fbe9e7" : "#eef4f1") : "#fff", color: status === st ? (st === "Suspended" ? "#b3261e" : "#006747") : "#6b706a" }}><Icon name={st === "Suspended" ? "user-x" : "user-check"} size={15} color={status === st ? (st === "Suspended" ? "#b3261e" : "#006747") : "#8a8e88"} /> {st}</button>)}
          </div>
        </div>
        <div style={{ flex: "none", display: "flex", gap: 9, padding: 16, borderTop: "1px solid #f1f0ea", background: "#fff" }}>
          <button onClick={onClose} style={{ ...btnPrimary, flex: 1, justifyContent: "center" }}><Icon name="save" size={15} color="#fff" /> Save changes</button>
          <button style={{ ...btnOutline, justifyContent: "center", color: "#b3261e", borderColor: "#f0d6d3" }}><Icon name="trash-2" size={15} color="#b3261e" /> Remove</button>
        </div>
      </div>
    </div>
  );
}

// ============ COMPLIANCE (back office + fines) ============
function AdminCompliance() {
  const A = window.RC_ADMIN;
  const [tab, setTab] = useState("issues");
  const [sel, setSel] = useState(A.issues[0]);
  const [statusF, setStatusF] = useState("Open");
  const rows = A.issues.filter((i) => statusF === "All" || i.status === statusF);
  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
      <div style={{ flex: "none", padding: "22px 28px 0" }}>
        <h1 style={{ margin: 0, fontSize: 25, fontWeight: 600, letterSpacing: "-0.6px", color: "#1d241f" }}>Compliance</h1>
        <p style={{ margin: "5px 0 0", fontSize: 14, color: "#8a8e88" }}>MLS-wide rule enforcement, issue review, and fines. {A.stats.complianceOpen} open · {A.stats.complianceCritical} critical · {A.usd(A.stats.finesOutstanding)} fines outstanding.</p>
        <div style={{ display: "flex", gap: 4, marginTop: 16 }}>
          {[["issues", "Issues"], ["rules", "Rule library"], ["builder", "AI rule builder"]].map(([id, lab]) => (
            <button key={id} onClick={() => setTab(id)} style={{ fontFamily: "inherit", fontSize: 13.5, fontWeight: 600, cursor: "pointer", border: 0, background: "transparent", padding: "9px 14px", color: tab === id ? "#006747" : "#8a8e88", borderBottom: tab === id ? "2px solid #006747" : "2px solid transparent" }}>{lab}</button>
          ))}
        </div>
      </div>

      {tab === "issues" ? (
        <div style={{ flex: 1, display: "grid", gridTemplateColumns: "minmax(360px, 0.95fr) 1.4fr", minHeight: 0, padding: "14px 28px 28px", gap: 0 }}>
          <div style={{ display: "flex", flexDirection: "column", minHeight: 0, background: "#fff", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", borderRadius: "3px 0 0 3px" }}>
            <div style={{ padding: "10px 12px", borderBottom: "1px solid #f1f0ea", display: "flex", gap: 6 }}>
              {["Open", "Resolved", "All"].map((f) => <button key={f} onClick={() => setStatusF(f)} style={{ fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, cursor: "pointer", border: 0, borderRadius: 6, padding: "6px 11px", background: statusF === f ? "#eef4f1" : "transparent", color: statusF === f ? "#006747" : "#8a8e88" }}>{f}</button>)}
            </div>
            <div style={{ flex: 1, overflowY: "auto" }}>
              {rows.map((i) => {
                const on = sel && sel.id === i.id;
                return (
                  <div key={i.id} onClick={() => setSel(i)} className="rc-row" style={{ padding: "12px 14px", cursor: "pointer", borderBottom: "1px solid #f6f5f0", background: on ? "#f3f6f4" : "transparent", borderLeft: on ? "2.5px solid #006747" : "2.5px solid transparent" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 5 }}>
                      <span style={pill(A.sevColor, i.severity, true)}>{i.severity}</span>
                      <span style={{ fontSize: 11, color: "#bcbfba", fontFamily: "'Space Mono', monospace" }}>{i.id}</span>
                      <span style={{ marginLeft: "auto", fontSize: 11, color: "#bcbfba" }}>{i.detected}</span>
                    </div>
                    <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f" }}>{i.ruleTitle}</div>
                    <div style={{ fontSize: 12, color: "#8a8e88", marginTop: 2 }}>{i.listing} · {i.area} · {i.agent}</div>
                    <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 7 }}>
                      <span style={pill(A.issueStatusColor, i.status, true)}>{i.status}</span>
                      {i.fine > 0 && <span style={{ fontSize: 11, fontWeight: 600, color: "#4a504a" }}>{A.usd(i.fine)} · <span style={{ color: (A.fineStatusColor[i.fineStatus] || {}).c }}>{i.fineStatus}</span></span>}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
          <div style={{ minHeight: 0, background: "#fbfaf7", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", borderRadius: "0 3px 3px 0", overflowY: "auto" }}>
            {sel && <IssueDetail key={sel.id} i={sel} A={A} />}
          </div>
        </div>
      ) : tab === "rules" ? (
        <div style={{ flex: 1, overflowY: "auto", padding: "14px 28px 28px" }}>
          <RuleLibrary A={A} />
        </div>
      ) : (
        <div style={{ flex: 1, overflowY: "auto", padding: "14px 28px 28px" }}>
          <RuleBuilder A={A} />
        </div>
      )}
    </div>
  );
}

function IssueDetail({ i, A, }) {
  const [fineStatus, setFineStatus] = useState(i.fineStatus);
  const [amount, setAmount] = useState(i.fine);
  const [resolved, setResolved] = useState(i.status);
  const sev = A.sevColor[i.severity];
  return (
    <div style={{ padding: 20 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 12 }}>
        <span style={pill(A.sevColor, i.severity)}>{i.severity}</span>
        <span style={pill(A.issueStatusColor, resolved)}>{resolved}</span>
        <span style={{ marginLeft: "auto", fontSize: 12, color: "#bcbfba", fontFamily: "'Space Mono', monospace" }}>{i.id} · {i.rule}</span>
      </div>
      <h2 style={{ margin: "0 0 5px", fontSize: 19, fontWeight: 600, color: "#1d241f" }}>{i.ruleTitle}</h2>
      <div style={{ fontSize: 13, color: "#8a8e88", marginBottom: 14 }}>{i.listing} · {i.area}</div>

      <div style={{ background: "#fff", borderRadius: 8, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "13px 15px", marginBottom: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
          <span style={{ width: 34, height: 34, borderRadius: "50%", background: "#e7e1d4", color: "#006747", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700, flex: "none" }}>{i.agent.split(" ").map((w) => w[0]).join("")}</span>
          <div style={{ flex: 1 }}><div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f" }}>{i.agent}</div><div style={{ fontSize: 11.5, color: "#8a8e88" }}>{i.office}</div></div>
          <button style={{ ...btnOutline, padding: "6px 11px", fontSize: 12.5 }}>View member</button>
        </div>
      </div>

      <div style={{ background: "#fff", borderRadius: 8, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "13px 15px", marginBottom: 14 }}>
        <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".5px", color: "#a8aca6", marginBottom: 7 }}>What was flagged</div>
        <p style={{ margin: 0, fontSize: 13, color: "#2d332e", lineHeight: 1.6 }}>{i.detail}</p>
      </div>

      {/* FINES (VestaPlus CheckMate-style) */}
      <div style={{ background: "#fff", borderRadius: 8, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "14px 15px", marginBottom: 14 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
          <span style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", display: "flex", alignItems: "center", gap: 7 }}><Icon name="badge-dollar-sign" size={16} color="#006747" /> Fine</span>
          <span style={pill(A.fineStatusColor, fineStatus)}>{fineStatus}</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 13 }}>
          <div style={{ position: "relative", flex: "none" }}>
            <span style={{ position: "absolute", left: 11, top: "50%", transform: "translateY(-50%)", fontFamily: "'Space Mono', monospace", color: "#8a8e88", fontSize: 15 }}>$</span>
            <input type="number" value={amount} onChange={(e) => setAmount(+e.target.value)} style={{ width: 120, boxSizing: "border-box", border: "1px solid #e2e0d8", borderRadius: 8, padding: "9px 11px 9px 22px", fontFamily: "'Space Mono', monospace", fontSize: 16, fontWeight: 700, color: "#1d241f", outline: "none" }} />
          </div>
          <span style={{ fontSize: 12, color: "#8a8e88" }}>Default for {i.rule}: {A.usd((A.rules.find((r) => r.code === i.rule) || {}).autoFine || 0)}</span>
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <button onClick={() => setFineStatus("Issued")} style={{ ...btnPrimary, padding: "8px 13px", fontSize: 12.5 }}><Icon name="gavel" size={14} color="#fff" /> Issue fine to agent</button>
          <button onClick={() => setFineStatus("Waived")} style={{ ...btnOutline, padding: "8px 13px", fontSize: 12.5 }}>Waive</button>
          <button onClick={() => setFineStatus("Paid")} style={{ ...btnOutline, padding: "8px 13px", fontSize: 12.5 }}>Mark paid</button>
        </div>

        {/* billing lifecycle — invoice, payment tracking, appeals */}
        {(function () {
          const bill = (window.RC_ADMIN.fineLifecycle || {})[i.id];
          if (!bill) return null;
          const kindMeta = { issued: { ic: "gavel", c: "#9a6a12" }, invoice: { ic: "file-text", c: "#2a6f8a" }, pending: { ic: "clock", c: "#9a6a12" }, paid: { ic: "check-circle-2", c: "#1f8a5b" }, appeal: { ic: "scale", c: "#6b706a" }, waived: { ic: "shield-check", c: "#1f8a5b" } };
          return (
            <div style={{ marginTop: 14, paddingTop: 14, borderTop: "1px solid #f1f0ea" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap", marginBottom: 12 }}>
                {[["Invoice", bill.invoice], ["Bill to", bill.billTo], bill.due ? ["Due", bill.due] : null, bill.paid ? ["Paid", bill.paid] : null, bill.appeal ? ["Appeal", bill.appeal] : null].filter(Boolean).map(([k, v]) => (
                  <div key={k}><div style={{ fontSize: 10, color: "#a8aca6", textTransform: "uppercase", letterSpacing: ".5px" }}>{k}</div><div style={{ fontSize: 12.5, fontWeight: 600, color: "#1d241f", marginTop: 2 }}>{v}</div></div>
                ))}
              </div>
              <div style={{ display: "flex", flexDirection: "column" }}>
                {bill.events.map((e, idx) => {
                  const m = kindMeta[e.kind] || { ic: "dot", c: "#a8aca6" };
                  return (
                    <div key={idx} style={{ display: "flex", gap: 11, paddingBottom: idx < bill.events.length - 1 ? 12 : 0 }}>
                      <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
                        <span style={{ width: 26, height: 26, borderRadius: "50%", background: "#f4f3ef", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name={m.ic} size={13} color={m.c} /></span>
                        {idx < bill.events.length - 1 && <div style={{ width: 1.5, flex: 1, background: "#ececec", marginTop: 3 }} />}
                      </div>
                      <div style={{ flex: 1, paddingTop: 3 }}>
                        <div style={{ display: "flex", justifyContent: "space-between", gap: 8 }}>
                          <span style={{ fontSize: 12.5, fontWeight: 600, color: "#1d241f" }}>{e.t}</span>
                          <span style={{ fontSize: 11, color: "#bcbfba", flex: "none" }}>{e.time}</span>
                        </div>
                        <div style={{ fontSize: 11.5, color: "#8a8e88", marginTop: 1 }}>{e.note}</div>
                      </div>
                    </div>
                  );
                })}
              </div>
              <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
                <button style={{ ...btnOutline, padding: "6px 11px", fontSize: 12 }}><Icon name="receipt" size={13} color="#006747" /> View invoice</button>
                <button style={{ ...btnOutline, padding: "6px 11px", fontSize: 12 }}><Icon name="scale" size={13} color="#006747" /> Record appeal</button>
              </div>
            </div>
          );
        })()}
      </div>

      {/* resolution */}
      <div style={{ display: "flex", gap: 8 }}>
        <button onClick={() => setResolved("Resolved")} style={{ ...btnPrimary, flex: 1, justifyContent: "center" }}><Icon name="check" size={15} color="#fff" /> Mark resolved</button>
        <button onClick={() => setResolved("Dismissed")} style={{ ...btnOutline, flex: 1, justifyContent: "center" }}>Dismiss</button>
        <button style={{ ...btnOutline, justifyContent: "center" }}><Icon name="send" size={15} color="#006747" /> Notify agent</button>
      </div>
    </div>
  );
}

function RuleLibrary({ A }) {
  const [rules, setRules] = useState(A.rules);
  const toggle = (id) => setRules(rules.map((r) => r.id === id ? { ...r, active: !r.active } : r));
  return (
    <div style={{ maxWidth: 1000 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <span style={{ fontSize: 13, color: "#8a8e88" }}>Rules the MLS automatically enforces. Each carries a default fine; super admins can toggle, edit, or add rules.</span>
        <button style={btnPrimary}><Icon name="plus" size={15} color="#fff" /> New Rule</button>
      </div>
      <div style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", overflow: "hidden" }}>
        <table style={{ borderCollapse: "collapse", width: "100%" }}>
          <thead><tr>{["Rule", "Category", "Severity", "Auto-fine", "Active"].map((h, i) => <th key={i} style={{ textAlign: i > 2 ? "center" : "left", padding: "11px 16px", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".6px", color: "#a8aca6", borderBottom: "2px solid #ececec" }}>{h}</th>)}</tr></thead>
          <tbody>
            {rules.map((r) => (
              <tr key={r.id} style={{ borderBottom: "1px solid #f4f3ee" }}>
                <td style={{ padding: "12px 16px" }}><div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f" }}>{r.title}</div><div style={{ fontSize: 11, color: "#a8aca6", fontFamily: "'Space Mono', monospace" }}>{r.code}</div></td>
                <td style={{ padding: "12px 16px", fontSize: 12.5, color: "#4a504a" }}>{r.category}</td>
                <td style={{ padding: "12px 16px" }}><span style={pill(A.sevColor, r.severity, true)}>{r.severity}</span></td>
                <td style={{ padding: "12px 16px", textAlign: "center", fontFamily: "'Space Mono', monospace", fontSize: 13, fontWeight: 700, color: "#1d241f" }}>{A.usd(r.autoFine)}</td>
                <td style={{ padding: "12px 16px", textAlign: "center" }}>
                  <button onClick={() => toggle(r.id)} style={{ position: "relative", width: 36, height: 20, borderRadius: 999, border: 0, cursor: "pointer", background: r.active ? "#006747" : "#d2d0c7" }}><span style={{ position: "absolute", top: 2, left: r.active ? 18 : 2, width: 16, height: 16, borderRadius: "50%", background: "#fff", transition: "left .15s" }} /></button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ============ AI RULE BUILDER ============
// Super admins upload their rulebooks/photo standards/bylaws, pull state statutes,
// and an AI model proposes the rules engine (incl. vision rules for photos).
function RuleBuilder({ A }) {
  const [sources, setSources] = useState(A.ruleSources);
  const [statutes, setStatutes] = useState(A.statutes);
  const [phase, setPhase] = useState("ready"); // ready | analyzing | done
  const [proposed, setProposed] = useState([]);
  const [accepted, setAccepted] = useState({});
  const toggleStatute = (id) => setStatutes(statutes.map((s) => s.id === id ? { ...s, on: !s.on } : s));

  const generate = () => {
    setPhase("analyzing"); setProposed([]);
    setTimeout(() => { setProposed(A.generatedRules); setPhase("done"); }, 1400);
  };
  const decide = (id, val) => setAccepted({ ...accepted, [id]: val });
  const acceptedCount = Object.values(accepted).filter((v) => v === "in").length;

  return (
    <div style={{ maxWidth: 1060 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 6 }}>
        <Icon name="sparkles" size={17} color="#006747" />
        <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600, color: "#1d241f" }}>Build your rules engine with AI</h3>
        <span style={{ fontSize: 11, fontWeight: 600, color: "#006747", background: "#eef4f1", borderRadius: 999, padding: "2px 8px" }}>reCURSIVE AI</span>
      </div>
      <p style={{ margin: "0 0 16px", fontSize: 13, color: "#8a8e88", lineHeight: 1.5, maxWidth: 760 }}>Upload your MLS rulebook, photo standards, and bylaws, and pull in state &amp; federal statutes. The model reads them — including analyzing example photos to build vision rules — and proposes a complete rule set for your review.</p>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 16 }}>
        {/* uploaded docs */}
        <div style={{ background: "#fff", borderRadius: 8, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: 16 }}>
          <div style={{ fontSize: 12.5, fontWeight: 600, color: "#1d241f", marginBottom: 11, display: "flex", alignItems: "center", gap: 7 }}><Icon name="folder-up" size={15} color="#006747" /> Source documents</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 11 }}>
            {sources.map((s) => (
              <div key={s.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 11px", borderRadius: 7, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)" }}>
                <Icon name={s.icon} size={16} color="#8a8e88" />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: "#1d241f", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{s.name}</div>
                  <div style={{ fontSize: 11, color: "#a8aca6" }}>{s.kind} · {s.pages}p · {s.rules} rules found</div>
                </div>
                {s.vision && <span title="Photo / vision analysis" style={{ fontSize: 9.5, fontWeight: 700, color: "#2a6f8a", background: "#e8f0f3", borderRadius: 4, padding: "1px 6px", display: "inline-flex", alignItems: "center", gap: 3 }}><Icon name="eye" size={10} color="#2a6f8a" /> VISION</span>}
                <Icon name="check-circle-2" size={15} color="#1f8a5b" />
              </div>
            ))}
          </div>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6, padding: "16px", borderRadius: 8, border: "1.5px dashed #c8c6bc", background: "#faf9f5", cursor: "pointer", textAlign: "center" }}>
            <Icon name="upload-cloud" size={22} color="#8a8e88" />
            <div style={{ fontSize: 12.5, fontWeight: 600, color: "#006747" }}>Drop rulebooks, photo standards, or bylaws</div>
            <div style={{ fontSize: 11, color: "#a8aca6" }}>PDF, DOCX, or images · the AI reads text and photos</div>
          </div>
        </div>

        {/* statutes */}
        <div style={{ background: "#fff", borderRadius: 8, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: 16 }}>
          <div style={{ fontSize: 12.5, fontWeight: 600, color: "#1d241f", marginBottom: 11, display: "flex", alignItems: "center", gap: 7 }}><Icon name="landmark" size={15} color="#006747" /> State &amp; federal statutes</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 11 }}>
            {statutes.map((s) => (
              <div key={s.id} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 11px", borderRadius: 7, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)" }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: "#1d241f" }}>{s.cite}</div>
                  <div style={{ fontSize: 11, color: "#a8aca6" }}>{s.state} · {s.rules} candidate rules</div>
                </div>
                <button onClick={() => toggleStatute(s.id)} style={{ position: "relative", width: 34, height: 20, borderRadius: 999, border: 0, cursor: "pointer", background: s.on ? "#006747" : "#d2d0c7", flex: "none" }}><span style={{ position: "absolute", top: 2, left: s.on ? 16 : 2, width: 16, height: 16, borderRadius: "50%", background: "#fff", transition: "left .15s" }} /></button>
              </div>
            ))}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, background: "#f4f3ef", borderRadius: 7, padding: "9px 11px" }}>
            <Icon name="search" size={14} color="#a8aca6" />
            <input placeholder="Add a state (e.g. California §10130)…" style={{ flex: 1, border: 0, outline: 0, background: "transparent", fontFamily: "inherit", fontSize: 12.5 }} />
          </div>
        </div>
      </div>

      {/* generate */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 16 }}>
        <button onClick={generate} disabled={phase === "analyzing"} style={{ ...btnPrimary, opacity: phase === "analyzing" ? 0.7 : 1 }}>
          <Icon name={phase === "analyzing" ? "loader" : "wand-2"} size={15} color="#fff" style={phase === "analyzing" ? { animation: "rc-spin 1s linear infinite" } : {}} />
          {phase === "done" ? "Re-generate rules" : "Generate rules engine"}
        </button>
        {phase === "analyzing" && <span style={{ fontSize: 12.5, color: "#8a8e88", display: "inline-flex", alignItems: "center", gap: 7 }}>Reading documents, analyzing photos, and cross-referencing statutes…</span>}
        {phase === "done" && <span style={{ fontSize: 12.5, color: "#6b706a" }}><b style={{ color: "#1d241f" }}>{proposed.length}</b> rules proposed · {acceptedCount} added</span>}
      </div>

      {/* proposed rules */}
      {phase === "analyzing" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {[0, 1, 2].map((i) => <div key={i} style={{ height: 64, borderRadius: 8, background: "linear-gradient(90deg,#f4f3ee,#faf9f5,#f4f3ee)", backgroundSize: "200% 100%", animation: "rc-shimmer 1.2s linear infinite" }} />)}
        </div>
      )}
      {phase === "done" && (
        <div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
            <span style={{ fontSize: 12.5, fontWeight: 600, color: "#1d241f" }}>Proposed rules — review &amp; approve</span>
            <button onClick={() => { const all = {}; proposed.forEach((r) => all[r.id] = "in"); setAccepted(all); }} style={{ ...btnOutline, padding: "6px 12px", fontSize: 12.5 }}><Icon name="check-check" size={14} color="#006747" /> Approve all</button>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {proposed.map((r) => {
              const dec = accepted[r.id];
              return (
                <div key={r.id} style={{ background: "#fff", borderRadius: 8, boxShadow: dec === "in" ? "inset 0 0 0 1.5px #cfe0d7" : dec === "out" ? "inset 0 0 0 1px #ececec" : "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "13px 15px", opacity: dec === "out" ? 0.55 : 1 }}>
                  <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap", marginBottom: 4 }}>
                        <span style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f" }}>{r.title}</span>
                        <span style={pill(A.sevColor, r.severity, true)}>{r.severity}</span>
                        {r.vision && <span style={{ fontSize: 9.5, fontWeight: 700, color: "#2a6f8a", background: "#e8f0f3", borderRadius: 4, padding: "1px 6px", display: "inline-flex", alignItems: "center", gap: 3 }}><Icon name="eye" size={10} color="#2a6f8a" /> VISION</span>}
                        <span style={{ fontSize: 10.5, color: "#bcbfba", fontFamily: "'Space Mono', monospace" }}>{r.code}</span>
                      </div>
                      <div style={{ fontSize: 12.5, color: "#6b706a", lineHeight: 1.5, marginBottom: 7 }}>{r.detail}</div>
                      <div style={{ display: "flex", alignItems: "center", gap: 14, fontSize: 11.5, color: "#a8aca6", flexWrap: "wrap" }}>
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><Icon name="quote" size={11} color="#a8aca6" /> {r.source}</span>
                        <span>Auto-fine <b style={{ color: "#1d241f", fontFamily: "'Space Mono', monospace" }}>{A.usd(r.autoFine)}</b></span>
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>Confidence
                          <span style={{ width: 44, height: 5, borderRadius: 3, background: "#eeede7", display: "inline-block", position: "relative", overflow: "hidden" }}><span style={{ position: "absolute", inset: 0, width: `${r.confidence * 100}%`, background: r.confidence > 0.9 ? "#1f8a5b" : "#9a6a12" }} /></span>
                          <b style={{ color: "#1d241f", fontFamily: "'Space Mono', monospace" }}>{Math.round(r.confidence * 100)}%</b>
                        </span>
                      </div>
                    </div>
                    <div style={{ display: "flex", gap: 7, flex: "none" }}>
                      {dec === "in"
                        ? <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12, fontWeight: 600, color: "#1f8a5b", background: "#e8f4ee", borderRadius: 7, padding: "7px 11px" }}><Icon name="check" size={14} color="#1f8a5b" /> Added</span>
                        : <React.Fragment>
                            <button onClick={() => decide(r.id, "in")} style={{ ...btnPrimary, padding: "7px 12px", fontSize: 12.5 }}>Add rule</button>
                            <button onClick={() => decide(r.id, "out")} style={{ ...btnOutline, padding: "7px 11px", fontSize: 12.5 }}>Skip</button>
                          </React.Fragment>}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
          {acceptedCount > 0 && (
            <button style={{ ...btnPrimary, marginTop: 16 }}><Icon name="save" size={15} color="#fff" /> Add {acceptedCount} rule{acceptedCount !== 1 ? "s" : ""} to the rule library</button>
          )}
        </div>
      )}
    </div>
  );
}

// ============ MODERATION ============
function AdminModeration() {
  const A = window.RC_ADMIN;
  const [tab, setTab] = useState("queue");
  const [sel, setSel] = useState(A.modQueue[0]);
  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
      <div style={{ flex: "none", padding: "22px 28px 0" }}>
        <h1 style={{ margin: 0, fontSize: 25, fontWeight: 600, letterSpacing: "-0.6px", color: "#1d241f" }}>Message moderation</h1>
        <p style={{ margin: "5px 0 0", fontSize: 14, color: "#8a8e88" }}>Messages screened against MLS policy. {A.stats.modPending} awaiting review · {A.stats.modBlocked30d} blocked in the last 30 days.</p>
        <div style={{ display: "flex", gap: 4, marginTop: 16 }}>
          {[["queue", "Flagged messages"], ["policies", "Policies"]].map(([id, lab]) => (
            <button key={id} onClick={() => setTab(id)} style={{ fontFamily: "inherit", fontSize: 13.5, fontWeight: 600, cursor: "pointer", border: 0, background: "transparent", padding: "9px 14px", color: tab === id ? "#006747" : "#8a8e88", borderBottom: tab === id ? "2px solid #006747" : "2px solid transparent" }}>{lab}</button>
          ))}
        </div>
      </div>

      {tab === "queue" ? (
        <div style={{ flex: 1, display: "grid", gridTemplateColumns: "minmax(340px, 0.9fr) 1.4fr", minHeight: 0, padding: "14px 28px 28px" }}>
          <div style={{ display: "flex", flexDirection: "column", minHeight: 0, background: "#fff", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", borderRadius: "3px 0 0 3px", overflowY: "auto" }}>
            {A.modQueue.map((m) => {
              const on = sel && sel.id === m.id;
              return (
                <div key={m.id} onClick={() => setSel(m)} className="rc-row" style={{ padding: "12px 14px", cursor: "pointer", borderBottom: "1px solid #f6f5f0", background: on ? "#f3f6f4" : "transparent", borderLeft: on ? "2.5px solid #006747" : "2.5px solid transparent" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 5 }}>
                    <span style={pill(A.modStatusColor, m.status, true)}>{m.status}</span>
                    <span style={{ fontSize: 11.5, fontWeight: 600, color: "#9a2820" }}>{m.policy}</span>
                    <span style={{ marginLeft: "auto", fontSize: 11, color: "#bcbfba" }}>{m.time}</span>
                  </div>
                  <div style={{ fontSize: 12.5, color: "#4a504a" }}>{m.from} → {m.to}</div>
                  <div style={{ fontSize: 12, color: "#a8aca6", marginTop: 4, fontStyle: "italic", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{m.excerpt}</div>
                </div>
              );
            })}
          </div>
          <div style={{ minHeight: 0, background: "#fbfaf7", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", borderRadius: "0 3px 3px 0", overflowY: "auto" }}>
            {sel && <ModDetail key={sel.id} m={sel} A={A} />}
          </div>
        </div>
      ) : (
        <div style={{ flex: 1, overflowY: "auto", padding: "14px 28px 28px" }}>
          <ModPolicies A={A} />
        </div>
      )}
    </div>
  );
}

function ModDetail({ m, A }) {
  const [status, setStatus] = useState(m.status);
  return (
    <div style={{ padding: 20 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 14 }}>
        <span style={pill(A.modStatusColor, status)}>{status}</span>
        <span style={{ fontSize: 12, fontWeight: 700, color: "#b3261e", background: "#fbe9e7", borderRadius: 999, padding: "3px 10px", textTransform: "uppercase", letterSpacing: ".4px" }}>{m.policy}</span>
        <span style={{ marginLeft: "auto", fontSize: 12, color: "#bcbfba", fontFamily: "'Space Mono', monospace" }}>{m.id}</span>
      </div>

      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
        <span style={{ width: 34, height: 34, borderRadius: "50%", background: "#e7e1d4", color: "#006747", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700 }}>{m.from.split(" ").map((w) => w[0]).join("")}</span>
        <div style={{ fontSize: 13, color: "#1d241f" }}><b>{m.from}</b> <span style={{ color: "#a8aca6" }}>({m.fromOffice})</span></div>
        <Icon name="arrow-right" size={15} color="#bcbfba" />
        <div style={{ fontSize: 13, color: "#1d241f" }}><b>{m.to}</b></div>
      </div>

      <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".5px", color: "#a8aca6", marginBottom: 7 }}>Message content</div>
      <div style={{ background: "#fff", borderRadius: 8, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "13px 15px", fontSize: 13.5, color: "#2d332e", lineHeight: 1.6, marginBottom: 14 }}>{m.excerpt}</div>

      <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".5px", color: "#a8aca6", marginBottom: 7 }}>Flagged terms</div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 18 }}>
        {m.flagged.map((f) => <span key={f} style={{ fontSize: 11.5, color: "#9a2820", background: "#fbe3df", borderRadius: 4, padding: "3px 9px" }}>“{f}”</span>)}
      </div>

      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
        <button onClick={() => setStatus("Blocked")} style={{ ...btnPrimary, padding: "9px 14px", justifyContent: "center" }}><Icon name="ban" size={15} color="#fff" /> Uphold block</button>
        <button onClick={() => setStatus("Dismissed")} style={{ ...btnOutline, padding: "9px 14px", justifyContent: "center" }}>Dismiss flag</button>
        <button style={{ ...btnOutline, padding: "9px 14px", justifyContent: "center", color: "#c0612f", borderColor: "#f0d8cc" }}><Icon name="user-x" size={15} color="#c0612f" /> Warn sender</button>
      </div>
    </div>
  );
}

function ModPolicies({ A }) {
  const [policies, setPolicies] = useState(A.modPolicies);
  const toggle = (id) => setPolicies(policies.map((p) => p.id === id ? { ...p, on: !p.on } : p));
  return (
    <div style={{ maxWidth: 760 }}>
      <div style={{ fontSize: 13, color: "#8a8e88", marginBottom: 14 }}>Outbound messages are automatically screened against these policies before sending. Super admins control which are enforced.</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {policies.map((p) => (
          <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 14, background: "#fff", borderRadius: 8, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "14px 16px" }}>
            <span style={{ width: 36, height: 36, borderRadius: 9, background: p.on ? "#eef4f1" : "#f0efe9", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="shield-check" size={18} color={p.on ? "#006747" : "#a8aca6"} /></span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f" }}>{p.label}</div>
              <div style={{ fontSize: 12, color: "#8a8e88", marginTop: 2 }}>{p.on ? `${p.blocked30d} blocked in last 30 days` : "Not enforced"}</div>
            </div>
            <button onClick={() => toggle(p.id)} style={{ position: "relative", width: 40, height: 22, borderRadius: 999, border: 0, cursor: "pointer", background: p.on ? "#006747" : "#d2d0c7", flex: "none" }}><span style={{ position: "absolute", top: 2, left: p.on ? 20 : 2, width: 18, height: 18, borderRadius: "50%", background: "#fff", transition: "left .15s" }} /></button>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---- shared admin atoms ----
function Card({ title, action, children }) {
  return (
    <div style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "13px 16px", borderBottom: "1px solid #f1f0ea" }}>
        <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600, color: "#1d241f" }}>{title}</h3>{action}
      </div>
      <div style={{ padding: "8px 16px 12px" }}>{children}</div>
    </div>
  );
}
function Row({ children, onClick }) {
  return <div onClick={onClick} className="rc-row" style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 2px", cursor: onClick ? "pointer" : "default", borderRadius: 6 }}>{children}</div>;
}
function LinkBtn({ children, onClick }) {
  return <button onClick={onClick} style={{ fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "#006747", background: "none", border: 0, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 4 }}>{children} <Icon name="arrow-right" size={13} color="#006747" /></button>;
}

// ============ ROLES & PERMISSIONS ============
function AdminRoles() {
  const A = window.RC_ADMIN;
  const [roles, setRoles] = useState(A.roleDefs);
  const [selId, setSelId] = useState(A.roleDefs[2].id); // default to Office admin (most interesting)
  const sel = roles.find((r) => r.id === selId) || roles[0];
  const setPerm = (areaId, scope) => setRoles(roles.map((r) => r.id === selId ? { ...r, perms: { ...r.perms, [areaId]: scope } } : r));
  // group permission areas
  const groups = [...new Set(A.permAreas.map((p) => p.group))];

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
      <div style={{ flex: "none", padding: "22px 28px 16px" }}>
        <h1 style={{ margin: 0, fontSize: 25, fontWeight: 600, letterSpacing: "-0.6px", color: "#1d241f" }}>Roles &amp; permissions</h1>
        <p style={{ margin: "5px 0 0", fontSize: 14, color: "#8a8e88" }}>Define role types and exactly what each can see and do. Scope every permission to <b>None</b>, the member's <b>own</b> records, their <b>office</b>, or the whole <b>MLS</b>.</p>
      </div>

      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "260px 1fr", minHeight: 0, padding: "0 28px 28px", gap: 16 }}>
        {/* role list */}
        <div style={{ display: "flex", flexDirection: "column", gap: 8, minHeight: 0 }}>
          <div style={{ flex: 1, overflowY: "auto", display: "flex", flexDirection: "column", gap: 8 }}>
            {roles.map((r) => {
              const on = r.id === selId;
              return (
                <button key={r.id} onClick={() => setSelId(r.id)} style={{ textAlign: "left", fontFamily: "inherit", cursor: "pointer", border: on ? "1px solid #006747" : "1px solid #e7e5df", background: on ? "#f3f6f4" : "#fff", borderRadius: 10, padding: "13px 14px" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                    <span style={{ width: 10, height: 10, borderRadius: 3, background: r.color, flex: "none" }} />
                    <span style={{ fontSize: 14, fontWeight: 600, color: "#1d241f", flex: 1 }}>{r.name}</span>
                    {r.system && <span style={{ fontSize: 9.5, fontWeight: 700, color: "#8a8e88", background: "#f0efe9", borderRadius: 4, padding: "1px 6px", textTransform: "uppercase", letterSpacing: ".4px" }}>System</span>}
                  </div>
                  <div style={{ fontSize: 12, color: "#8a8e88", marginTop: 4, fontFamily: "'Space Mono', monospace" }}>{r.members.toLocaleString()} members</div>
                </button>
              );
            })}
          </div>
          <button style={{ ...btnOutline, justifyContent: "center" }}><Icon name="plus" size={15} color="#006747" /> New Role</button>
        </div>

        {/* permission matrix */}
        <div style={{ minHeight: 0, background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
          <div style={{ flex: "none", display: "flex", alignItems: "center", gap: 11, padding: "15px 18px", borderBottom: "1px solid #f1f0ea" }}>
            <span style={{ width: 12, height: 12, borderRadius: 3, background: sel.color, flex: "none" }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 16, fontWeight: 600, color: "#1d241f" }}>{sel.name}</div>
              <div style={{ fontSize: 12, color: "#8a8e88" }}>{sel.members.toLocaleString()} members · {sel.system ? "system role" : "custom role"}</div>
            </div>
            <button style={{ ...btnOutline, padding: "7px 11px", fontSize: 12.5 }}><Icon name="copy" size={14} color="#006747" /> Duplicate</button>
            {!sel.system && <button style={{ ...btnPrimary, padding: "7px 11px", fontSize: 12.5 }}><Icon name="save" size={14} color="#fff" /> Save</button>}
          </div>

          <div style={{ flex: 1, overflowY: "auto", padding: "8px 18px 18px" }}>
            {groups.map((g) => (
              <div key={g} style={{ marginTop: 16 }}>
                <div style={{ fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".7px", color: "#a8aca6", marginBottom: 6 }}>{g}</div>
                {A.permAreas.filter((p) => p.group === g).map((area) => (
                  <div key={area.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 0", borderBottom: "1px solid #f6f5f0" }}>
                    <span style={{ flex: 1, fontSize: 13.5, color: "#1d241f", fontWeight: 500 }}>{area.label}</span>
                    <div style={{ display: "inline-flex", background: "#f1f0ea", borderRadius: 8, padding: 3 }}>
                      {A.scopes.map((sc) => {
                        const on = sel.perms[area.id] === sc;
                        const col = A.scopeColor[sc];
                        return (
                          <button key={sc} onClick={() => setPerm(area.id, sc)} disabled={sel.system} title={sel.system ? "System role — duplicate to customize" : ""}
                            style={{ fontFamily: "inherit", fontSize: 12, fontWeight: 600, cursor: sel.system ? "not-allowed" : "pointer", border: 0, borderRadius: 6, padding: "5px 12px",
                              background: on ? "#fff" : "transparent", color: on ? col.c : "#a8aca6", boxShadow: on ? "0 1px 2px rgba(0,0,0,.14)" : "none", opacity: sel.system && !on ? 0.5 : 1 }}>{sc}</button>
                        );
                      })}
                    </div>
                  </div>
                ))}
              </div>
            ))}
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 18, fontSize: 11.5, color: "#a8aca6" }}>
              <Icon name="info" size={13} color="#a8aca6" />
              <span><b>Own</b> = the member's own records · <b>Office</b> = anyone in their brokerage · <b>MLS</b> = the entire system. System roles are read-only; duplicate to make a custom role.</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.AdminDashboard = AdminDashboard;
window.AdminUsers = AdminUsers;
window.AdminCompliance = AdminCompliance;
window.AdminModeration = AdminModeration;
window.AdminRoles = AdminRoles;
