// Members page + Member detail sub-page

const MEMBERS = [
  { id:"vk", name:"Alex Pemberton", email:"alex@meridianstudio.io", role:"Owner",  status:"active", since:"2026-01-04", scope:"All projects", spend:244.53, requests:5980, lastActive:"just now", twoFA:true, sso:false, color:"#5b50ee" },
  { id:"sm", name:"Jamie Lowe",      email:"jamie@meridianstudio.io",   role:"Editor", status:"active", since:"2026-04-22", scope:"5 projects",   spend:33.35,  requests:755,  lastActive:"2h ago",   twoFA:true, sso:false, color:"#0f8a4f" },
  { id:"jm", name:"Sam Chen",      email:"sam@meridianstudio.io",   role:"Editor", status:"active", since:"2026-05-17", scope:"2 projects",   spend:0.00,   requests:0,    lastActive:"never",    twoFA:false,sso:false, color:"#d97757" },
];

const PENDING = [
  { email:"finance@meridianlegal.co.uk",      role:"Viewer", scope:"Q1 2026 reports", invitedBy:"Alex", sent:"2d ago",  expires:"in 5 days" },
  { email:"design@foxgrovestudio.com",role:"Viewer", scope:"foxgrove-cms",   invitedBy:"Alex", sent:"5d ago",  expires:"in 2 days" },
];

const ROLE_DEFS = {
  Owner:  { color:"var(--accent)",     bg:"var(--accent-soft)",   line:"var(--accent-line)",     scope:"full" },
  Admin:  { color:"var(--p-google)",   bg:"rgba(66,133,244,0.10)",line:"rgba(66,133,244,0.28)",  scope:"manage" },
  Editor: { color:"var(--pos)",        bg:"var(--pos-soft)",      line:"rgba(15,138,79,0.28)",   scope:"write" },
  Viewer: { color:"var(--fg-2)",       bg:"var(--bg-3)",          line:"var(--line-2)",          scope:"read" },
};

function Members({ setScreen, setMember }){
  const [search, setSearch] = useState("");
  const [role, setRole]     = useState("all");
  const [status, setStatus] = useState("all");

  let rows = MEMBERS;
  if (search) rows = rows.filter(m => m.name.toLowerCase().includes(search.toLowerCase()) || m.email.toLowerCase().includes(search.toLowerCase()));
  if (role !== "all") rows = rows.filter(m => m.role === role);
  if (status !== "all") rows = rows.filter(m => m.status === status);

  return (
    <div data-screen-label="06 Members" style={{ padding:"24px 28px 40px", maxWidth:1380, margin:"0 auto", display:"flex", flexDirection:"column", gap:20 }}>
      {/* Header */}
      <header style={{ display:"flex", alignItems:"flex-end", justifyContent:"space-between", gap:16 }}>
        <div>
          <div style={{ fontSize:11, letterSpacing:0.08, textTransform:"uppercase", color:"var(--fg-3)", fontWeight:600, marginBottom:6 }}>Workspace</div>
          <h1 style={{ margin:0, fontSize:28, fontWeight:600, letterSpacing:-0.5, color:"var(--fg-0)" }}>Members</h1>
          <div style={{ color:"var(--fg-2)", fontSize:13, marginTop:5 }}>
            <span className="mono" style={{ color:"var(--fg-1)" }}>{MEMBERS.length}</span> active · <span className="mono" style={{ color:"var(--fg-1)" }}>{PENDING.length}</span> pending invites · Meridian Studio
          </div>
        </div>
        <div style={{ display:"flex", gap:8 }}>
          <button style={btnSecondary()}><Icon name="download" size={13}/> Export CSV</button>
          <button style={btnSecondary()}><Icon name="layers" size={13}/> Bulk (CSV)</button>
          <button style={btnPrimary()}><Icon name="plus" size={14}/> Invite member</button>
        </div>
      </header>

      {/* KPI strip */}
      <div className="card" style={{ padding:0, display:"grid", gridTemplateColumns:"repeat(4, 1fr)", overflow:"hidden" }}>
        <MemberKPI label="Active members"  value={MEMBERS.length} sub="2 owners · 2 editors · 0 viewers" icon="user"/>
        <MemberKPI label="Pending invites" value={PENDING.length} sub="1 expiring this week"             icon="clock"   border tone={PENDING.length>0?"warn":"neutral"}/>
        <MemberKPI label="2FA enabled"     value="2 of 3"        sub="Jamie hasn't enrolled"             icon="check"   border tone="warn"/>
        <MemberKPI label="SSO"             value="Off"           sub="Available on Business+"            icon="cog"     border tone="neutral" cta="Enable"/>
      </div>

      {/* Pending invites — pinned at top */}
      {PENDING.length > 0 && (
        <section className="card" style={{ padding:0, overflow:"hidden", borderColor:"rgba(185,113,13,0.18)", background:"linear-gradient(180deg, var(--warn-soft), transparent 40%)" }}>
          <div style={{ padding:"14px 22px", display:"flex", alignItems:"center", justifyContent:"space-between" }}>
            <div style={{ display:"flex", alignItems:"center", gap:9 }}>
              <Icon name="clock" size={14} stroke="var(--warn)"/>
              <span style={{ fontSize:13, fontWeight:600, color:"var(--fg-0)" }}>Pending invites</span>
              <span className="badge badge--warn" style={{ fontSize:10 }}>{PENDING.length}</span>
            </div>
            <button style={btnSubtle()}>Manage all <Icon name="arrow" size={11}/></button>
          </div>
          <div>
            {PENDING.map((p,i) => (
              <div key={i} style={{ padding:"11px 22px", borderTop:"1px solid var(--line-1)", display:"grid", gridTemplateColumns:"minmax(220px, 2fr) 100px 1.4fr 100px 90px 200px", gap:12, alignItems:"center" }}>
                <div style={{ display:"flex", alignItems:"center", gap:10 }}>
                  <div style={{ width:30, height:30, borderRadius:"50%", background:"var(--bg-3)", color:"var(--fg-2)", display:"flex", alignItems:"center", justifyContent:"center", border:"1px dashed var(--line-2)" }}>
                    <Icon name="user" size={14}/>
                  </div>
                  <div style={{ minWidth:0 }}>
                    <div style={{ fontSize:12.5, color:"var(--fg-0)", fontWeight:500, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{p.email}</div>
                    <div style={{ fontSize:10.5, color:"var(--fg-3)" }}>invited by {p.invitedBy}</div>
                  </div>
                </div>
                <RoleBadge role={p.role}/>
                <span style={{ fontSize:12, color:"var(--fg-2)" }}>{p.scope}</span>
                <span className="mono" style={{ fontSize:11, color:"var(--fg-3)" }}>{p.sent}</span>
                <span className="mono" style={{ fontSize:11, color:"var(--warn)" }}>{p.expires}</span>
                <div style={{ display:"flex", gap:6, justifyContent:"flex-end" }}>
                  <button style={btnGhost()}><Icon name="refresh" size={11}/> Resend</button>
                  <button style={{ ...btnGhost(), color:"var(--neg)" }}>Revoke</button>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}

      {/* Filter row */}
      <section className="card" style={{ padding:0, overflow:"hidden" }}>
        <div style={{ padding:"14px 22px", borderBottom:"1px solid var(--line-1)", display:"flex", alignItems:"center", gap:10 }}>
          <div style={{ position:"relative", flex:1, maxWidth:340 }}>
            <span style={{ position:"absolute", left:10, top:"50%", transform:"translateY(-50%)", color:"var(--fg-3)" }}><Icon name="search" size={13} stroke="var(--fg-3)"/></span>
            <input
              placeholder="Search members or email…"
              value={search}
              onChange={e=>setSearch(e.target.value)}
              style={{ height:32, padding:"0 10px 0 32px", width:"100%", border:"1px solid var(--line-2)", borderRadius:8, background:"#fff", fontSize:12.5, outline:"none" }}
            />
          </div>
          <Segmented value={role} onChange={setRole} options={[
            { id:"all",    label:"All roles" },
            { id:"Owner",  label:"Owner" },
            { id:"Editor", label:"Editor" },
            { id:"Viewer", label:"Viewer" },
          ]}/>
          <div style={{ flex:1 }}/>
          <Segmented value={status} onChange={setStatus} options={[
            { id:"all",       label:"All" },
            { id:"active",    label:"Active" },
            { id:"suspended", label:"Suspended" },
          ]}/>
        </div>

        {/* Header */}
        <div style={{ display:"grid", gridTemplateColumns:"minmax(240px, 2fr) 100px 130px 110px 100px 90px 90px 36px", gap:10, padding:"11px 22px", fontSize:10.5, letterSpacing:0.06, textTransform:"uppercase", color:"var(--fg-2)", fontWeight:500, borderBottom:"1px solid var(--line-1)", background:"rgba(20,16,8,0.015)" }}>
          <div>Member</div>
          <div>Role</div>
          <div>Scope</div>
          <div className="right">Spend (MTD)</div>
          <div>Requests</div>
          <div>Last active</div>
          <div>Security</div>
          <div></div>
        </div>

        {/* Rows */}
        {rows.map(m => (
          <MemberRow key={m.id} m={m} onOpen={()=>{ setMember(m.id); setScreen("member-detail"); }}/>
        ))}
        {rows.length === 0 && (
          <div style={{ padding:"50px 24px", textAlign:"center", color:"var(--fg-2)" }}>No members match those filters.</div>
        )}
      </section>

      {/* Role permissions matrix */}
      <RolePermissionsMatrix/>

      <div style={{ textAlign:"center", color:"var(--fg-3)", fontSize:11 }}>Showing {rows.length} of {MEMBERS.length} members</div>
    </div>
  );
}

function MemberKPI({ label, value, sub, icon, delta, border, tone, cta }){
  const tones = {
    pos:    { fg:"var(--pos)" },
    warn:   { fg:"var(--warn)" },
    accent: { fg:"var(--accent)" },
    neutral:{ fg:"var(--fg-0)" },
  };
  const t = tones[tone] || tones.neutral;
  return (
    <div style={{ padding:"16px 20px", borderLeft: border ? "1px solid var(--line-1)" : "none", display:"flex", flexDirection:"column", gap:6 }}>
      <div style={{ display:"flex", alignItems:"center", justifyContent:"space-between" }}>
        <span style={{ display:"inline-flex", alignItems:"center", gap:7, fontSize:10.5, letterSpacing:0.08, textTransform:"uppercase", color:"var(--fg-3)", fontWeight:600 }}>
          <Icon name={icon} size={12.5} stroke="var(--fg-3)"/>{label}
        </span>
        {cta && <button style={{ ...btnSubtle(), color:"var(--accent)", padding:0 }}>{cta}</button>}
      </div>
      <div style={{ display:"flex", alignItems:"baseline", gap:8 }}>
        <span className="mono" style={{ fontSize:22, fontWeight:600, color:t.fg, letterSpacing:-0.3 }}>{value}</span>
        {delta != null && <Delta pct={delta}/>}
      </div>
      <div style={{ fontSize:11, color:"var(--fg-2)" }}>{sub}</div>
    </div>
  );
}

function MemberRow({ m, onOpen }){
  return (
    <div
      onClick={onOpen}
      style={{
        display:"grid", gridTemplateColumns:"minmax(240px, 2fr) 100px 130px 110px 100px 90px 90px 36px",
        gap:10, padding:"13px 22px", alignItems:"center",
        borderTop:"1px solid var(--line-1)",
        cursor:"pointer",
        transition:"background 80ms ease",
      }}
      onMouseEnter={e=>e.currentTarget.style.background="rgba(20,16,8,0.025)"}
      onMouseLeave={e=>e.currentTarget.style.background="transparent"}
    >
      {/* Member */}
      <div style={{ display:"flex", alignItems:"center", gap:11, minWidth:0 }}>
        <Avatar seed={m.id} name={m.name} size={36}/>
        <div style={{ minWidth:0 }}>
          <div style={{ fontSize:13, fontWeight:500, color:"var(--fg-0)", overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap" }}>{m.name}</div>
          <div className="mono" style={{ fontSize:11, color:"var(--fg-3)" }}>{m.email}</div>
        </div>
      </div>

      <RoleBadge role={m.role}/>

      <span style={{ fontSize:12, color:"var(--fg-2)" }}>{m.scope}</span>

      <div className="right"><Money value={m.spend} size="sm"/></div>

      <span className="mono" style={{ fontSize:12, color:"var(--fg-1)" }}>{m.requests.toLocaleString()}</span>

      <span className="mono" style={{ fontSize:11.5, color: m.lastActive==="never" ? "var(--fg-3)" : "var(--fg-2)" }}>{m.lastActive}</span>

      <div style={{ display:"flex", gap:5 }}>
        {m.twoFA
          ? <span title="2FA enabled" style={{ display:"inline-flex", alignItems:"center", justifyContent:"center", width:22, height:22, borderRadius:5, background:"var(--pos-soft)", color:"var(--pos)" }}><Icon name="check" size={11}/></span>
          : <span title="2FA missing" style={{ display:"inline-flex", alignItems:"center", justifyContent:"center", width:22, height:22, borderRadius:5, background:"var(--warn-soft)", color:"var(--warn)" }}><Icon name="alert" size={11}/></span>}
      </div>

      <div style={{ display:"flex", justifyContent:"flex-end", color:"var(--fg-3)" }}>
        <Icon name="chevron" size={13}/>
      </div>
    </div>
  );
}

function RoleBadge({ role }){
  const r = ROLE_DEFS[role] || ROLE_DEFS.Viewer;
  return (
    <span style={{ display:"inline-flex", alignItems:"center", gap:5, padding:"2px 8px", borderRadius:99, background:r.bg, color:r.color, border:"1px solid "+r.line, fontSize:11, fontWeight:500, width:"fit-content" }}>
      <span style={{ width:5, height:5, borderRadius:"50%", background:r.color }}/>{role}
    </span>
  );
}

// Role permissions matrix
function RolePermissionsMatrix(){
  const caps = [
    { cap:"View dashboards & reports",   Owner:true,  Admin:true,  Editor:true,  Viewer:true },
    { cap:"Generate reports",            Owner:true,  Admin:true,  Editor:true,  Viewer:false },
    { cap:"Share report links externally",Owner:true, Admin:true,  Editor:false, Viewer:false },
    { cap:"Edit projects & .haltonrc",   Owner:true,  Admin:true,  Editor:true,  Viewer:false },
    { cap:"Manage cost centres & budgets",Owner:true, Admin:true,  Editor:false, Viewer:false },
    { cap:"Invite & manage members",     Owner:true,  Admin:true,  Editor:false, Viewer:false },
    { cap:"Billing & subscription",      Owner:true,  Admin:false, Editor:false, Viewer:false },
    { cap:"Workspace deletion",          Owner:true,  Admin:false, Editor:false, Viewer:false },
  ];
  const roles = ["Owner","Admin","Editor","Viewer"];
  return (
    <section className="card" style={{ padding:0, overflow:"hidden" }}>
      <div style={{ padding:"16px 22px", borderBottom:"1px solid var(--line-1)", display:"flex", justifyContent:"space-between", alignItems:"center" }}>
        <div>
          <h2 style={{ margin:0, fontSize:14, fontWeight:600 }}>Role permissions</h2>
          <div style={{ fontSize:11.5, color:"var(--fg-2)", marginTop:3 }}>Capability matrix · custom roles available on Enterprise</div>
        </div>
        <button style={btnGhost()}>Customise roles <Icon name="arrow" size={11}/></button>
      </div>
      <div style={{ overflowX:"auto" }}>
        <table style={{ width:"100%", borderCollapse:"collapse" }}>
          <thead>
            <tr>
              <th style={{ textAlign:"left", padding:"11px 22px", fontSize:10.5, fontWeight:500, letterSpacing:0.06, textTransform:"uppercase", color:"var(--fg-2)", borderBottom:"1px solid var(--line-1)" }}>Capability</th>
              {roles.map(r => (
                <th key={r} style={{ textAlign:"center", padding:"11px 14px", fontSize:10.5, fontWeight:500, letterSpacing:0.06, textTransform:"uppercase", color:"var(--fg-2)", borderBottom:"1px solid var(--line-1)" }}>{r}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {caps.map((c,i) => (
              <tr key={i}>
                <td style={{ padding:"11px 22px", fontSize:12.5, color:"var(--fg-1)", borderBottom:i<caps.length-1?"1px solid var(--line-1)":"none" }}>{c.cap}</td>
                {roles.map(r => (
                  <td key={r} style={{ textAlign:"center", padding:"11px 14px", borderBottom:i<caps.length-1?"1px solid var(--line-1)":"none" }}>
                    {c[r] ? (
                      <span style={{ display:"inline-flex", width:18, height:18, borderRadius:"50%", background: ROLE_DEFS[r].bg, color: ROLE_DEFS[r].color, alignItems:"center", justifyContent:"center" }}>
                        <Icon name="check" size={11}/>
                      </span>
                    ) : (
                      <span style={{ color:"var(--fg-3)", fontSize:14 }}>—</span>
                    )}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────
//  Member detail sub-page
// ─────────────────────────────────────────────────────────────
function MemberDetail({ id, setScreen }){
  const m = MEMBERS.find(x => x.id === id) || MEMBERS[0];
  const [tab, setTab] = useState("overview");
  const role = ROLE_DEFS[m.role];

  // Synth member-level breakdown
  const memberProjects = m.id === "vk"
    ? PROJECTS.filter(p => p.spend > 1).slice(0, 8)
    : PROJECTS.filter(p => p.spend > 0.01).slice(2, 6);

  const memberDaily = DAILY.map(d => ({
    d: d.d,
    cost: d.cost * (m.id === "vk" ? 0.88 : 0.12),
    reqs: Math.round(d.reqs * (m.id === "vk" ? 0.89 : 0.11)),
  }));

  return (
    <div data-screen-label="06b Member Detail" style={{ padding:"20px 28px 40px", maxWidth:1380, margin:"0 auto", display:"flex", flexDirection:"column", gap:18 }}>
      {/* Breadcrumb */}
      <div style={{ display:"flex", alignItems:"center", gap:8, fontSize:12.5, color:"var(--fg-2)" }}>
        <button onClick={()=>setScreen("members")} style={{ background:"none", border:"none", color:"var(--fg-2)", padding:0, cursor:"pointer", fontSize:12.5, display:"inline-flex", alignItems:"center", gap:5 }}>
          <Icon name="chevLeft" size={12}/> Members
        </button>
        <span style={{ color:"var(--fg-3)" }}>/</span>
        <span style={{ color:"var(--fg-0)", fontWeight:500 }}>{m.name}</span>
      </div>

      {/* Header */}
      <header className="card" style={{ padding:0, overflow:"hidden", position:"relative" }}>
        <div style={{ position:"absolute", inset:0, background:`linear-gradient(135deg, ${m.color}10 0%, transparent 55%)`, pointerEvents:"none" }}/>
        <div style={{ padding:"22px 26px 18px", display:"flex", justifyContent:"space-between", alignItems:"flex-start", gap:24, position:"relative" }}>
          <div style={{ display:"flex", gap:18, alignItems:"flex-start" }}>
            <Avatar seed={m.id} name={m.name} size={64}/>
            <div>
              <div style={{ display:"flex", alignItems:"center", gap:10 }}>
                <h1 style={{ margin:0, fontSize:24, fontWeight:600, letterSpacing:-0.4 }}>{m.name}</h1>
                <RoleBadge role={m.role}/>
                <span style={{ display:"inline-flex", alignItems:"center", gap:5, fontSize:11.5, color:"var(--pos)" }}>
                  <span style={{ width:6, height:6, borderRadius:"50%", background:"var(--pos)" }}/>Active
                </span>
              </div>
              <div style={{ display:"flex", gap:14, marginTop:6, fontSize:12.5, color:"var(--fg-2)" }}>
                <a href={`mailto:${m.email}`} className="mono" style={{ color:"var(--fg-1)", textDecoration:"none" }}>{m.email}</a>
                <span style={{ color:"var(--fg-3)" }}>·</span>
                <span>Member since <span className="mono">{m.since}</span></span>
                <span style={{ color:"var(--fg-3)" }}>·</span>
                <span>Last active <span className="mono">{m.lastActive}</span></span>
              </div>
              <div style={{ display:"flex", gap:8, marginTop:12 }}>
                {m.twoFA && <span className="badge badge--pos" style={{ fontSize:10 }}><Icon name="check" size={10}/> 2FA enabled</span>}
                {!m.twoFA && <span className="badge badge--warn" style={{ fontSize:10 }}><Icon name="alert" size={10}/> 2FA missing</span>}
                {m.sso ? <span className="badge badge--accent" style={{ fontSize:10 }}>SSO</span> : null}
                <span className="badge badge--ghost" style={{ fontSize:10 }}>API tokens · 0</span>
              </div>
            </div>
          </div>
          <div style={{ display:"flex", flexDirection:"column", gap:10, alignItems:"flex-end" }}>
            <div style={{ display:"flex", gap:8 }}>
              <button style={btnSecondary()}><Icon name="cog" size={13}/> Edit role</button>
              <button style={btnSecondary()}><Icon name="alert" size={13}/> Suspend</button>
              <button style={btnPrimary()}><Icon name="download" size={13}/> Export profile</button>
            </div>
          </div>
        </div>

        {/* KPI strip */}
        <div style={{ display:"grid", gridTemplateColumns:"repeat(5, 1fr)", borderTop:"1px solid var(--line-1)", background:"rgba(20,16,8,0.012)" }}>
          <MStat label="Spend (MTD)"   value={<Money value={m.spend} size="sm"/>}   sub={`${(m.spend/PERIOD.totalGBP*100).toFixed(1)}% of workspace`}/>
          <MStat label="Requests"      value={m.requests.toLocaleString()}          sub={`${Math.round(m.requests/PERIOD.daysElapsed)} per day`} border/>
          <MStat label="Projects"      value={memberProjects.length}                sub="contributed to" border/>
          <MStat label="Primary model" value="Opus 4.7"                              sub="92% of requests" border icon="cube"/>
          <MStat label="Avg cost / req"value={fmtGBP(m.spend / Math.max(1,m.requests), 6)} sub="blended" border/>
        </div>
      </header>

      {/* Tabs */}
      <div style={{ display:"flex", alignItems:"center", borderBottom:"1px solid var(--line-1)", marginTop:-4 }}>
        {[
          { id:"overview",   label:"Overview" },
          { id:"projects",   label:"Projects", count: memberProjects.length },
          { id:"activity",   label:"Activity" },
          { id:"access",     label:"Access & permissions" },
        ].map(t => {
          const active = tab === t.id;
          return (
            <button key={t.id} onClick={()=>setTab(t.id)} style={{
              appearance:"none", background:"transparent", border:"none",
              padding:"10px 14px",
              fontSize:13, fontWeight: active?500:400,
              color: active?"var(--fg-0)":"var(--fg-2)",
              borderBottom: active?"2px solid var(--accent)":"2px solid transparent",
              marginBottom:-1, cursor:"pointer",
              display:"inline-flex", alignItems:"center", gap:8,
            }}>
              {t.label}
              {t.count != null && <span className="mono" style={{ fontSize:10.5, color:"var(--fg-3)" }}>{t.count}</span>}
            </button>
          );
        })}
      </div>

      {tab === "overview" && (
        <div style={{ display:"grid", gridTemplateColumns:"minmax(0, 1fr) 320px", gap:18 }}>
          <div style={{ display:"flex", flexDirection:"column", gap:18 }}>
            <MemberSpendChart daily={memberDaily} color={m.color}/>
            <MemberProjectsTable projects={memberProjects} memberShare={m.id==="vk"?0.88:0.12}/>
            <MemberRecentRequests memberId={m.id}/>
          </div>
          <aside style={{ display:"flex", flexDirection:"column", gap:14 }}>
            <ModelUsageCard memberId={m.id}/>
            <PermissionScopeCard m={m}/>
            <SecurityCard m={m}/>
            <DangerZoneMember/>
          </aside>
        </div>
      )}

      {tab === "projects" && (
        <MemberProjectsTable projects={memberProjects} memberShare={m.id==="vk"?0.88:0.12} expanded/>
      )}

      {tab === "activity" && <MemberActivityTab memberId={m.id}/>}
      {tab === "access" && <AccessTab m={m}/>}
    </div>
  );
}

function MStat({ label, value, sub, border, icon }){
  return (
    <div style={{ padding:"14px 18px", borderLeft: border ? "1px solid var(--line-1)" : "none", display:"flex", flexDirection:"column", gap:5 }}>
      <span style={{ display:"inline-flex", alignItems:"center", gap:7, fontSize:10.5, letterSpacing:0.08, textTransform:"uppercase", color:"var(--fg-3)", fontWeight:600 }}>
        {icon && <Icon name={icon} size={12} stroke="var(--fg-3)"/>}
        {label}
      </span>
      <span className="mono" style={{ fontSize:17, fontWeight:600, color:"var(--fg-0)", letterSpacing:-0.2 }}>{value}</span>
      <span style={{ fontSize:10.5, color:"var(--fg-2)" }}>{sub}</span>
    </div>
  );
}

// Member spend chart — area with requests bar
function MemberSpendChart({ daily, color }){
  const ref = useRef(null);
  const w = useWidth(ref);
  const h = 200;
  const padL = 48, padR = 44, padT = 14, padB = 30;
  const innerW = Math.max(100, w - padL - padR);
  const innerH = h - padT - padB;
  const n = daily.length;
  const maxC = Math.max(...daily.map(d=>d.cost), 0.01)*1.18;
  const maxR = Math.max(...daily.map(d=>d.reqs), 1)*1.18;
  const x = i => (i/(n-1))*innerW;
  const yC = v => innerH - (v/maxC)*innerH;
  const yR = v => innerH - (v/maxR)*innerH;
  const pts = daily.map((d,i)=>`${x(i)},${yC(d.cost)}`).join(" ");
  const areaPath = `M0,${innerH} L${pts.split(" ").join(" L")} L${innerW},${innerH} Z`;
  const linePath = `M${pts}`;
  const barW = (innerW/n)*0.3;

  const yTicks = [0, 0.25, 0.5, 0.75, 1].map(t => ({ v:t*maxC, y:yC(t*maxC) }));

  return (
    <section className="card" style={{ padding:"20px 22px" }}>
      <SectionHeader
        title="Their spend over time"
        subtitle="Cost area · request bars · last 11 days"
        action={
          <div style={{ display:"flex", gap:14 }}>
            <span style={{ display:"inline-flex", alignItems:"center", gap:6, fontSize:11.5, color:"var(--fg-2)" }}><span style={{ width:10, height:3, borderRadius:2, background:color }}/>Cost</span>
            <span style={{ display:"inline-flex", alignItems:"center", gap:6, fontSize:11.5, color:"var(--fg-2)" }}><span style={{ width:6, height:10, borderRadius:1, background:"var(--bg-4)" }}/>Requests</span>
          </div>
        }
      />
      <div ref={ref} style={{ position:"relative", width:"100%", height:h }}>
        <svg width={w} height={h}>
          <defs>
            <linearGradient id={`grad-${color.replace(/[#(),. ]/g,'')}`} x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%" stopColor={color} stopOpacity="0.30"/>
              <stop offset="100%" stopColor={color} stopOpacity="0.02"/>
            </linearGradient>
          </defs>
          {yTicks.map((t,i) => (
            <g key={i}>
              <line x1={padL} x2={padL+innerW} y1={padT+t.y} y2={padT+t.y} stroke="var(--line-1)" strokeDasharray={i===0?"":"2 4"}/>
              <text x={padL-10} y={padT+t.y+3} textAnchor="end" fontSize="10" fontFamily="var(--font-mono)" fill="var(--fg-3)">£{t.v.toFixed(t.v<1?2:0)}</text>
            </g>
          ))}
          <g transform={`translate(${padL},${padT})`}>
            {daily.map((d,i) => {
              const bh = innerH - yR(d.reqs);
              return <rect key={i} x={x(i)-barW/2} y={yR(d.reqs)} width={barW} height={bh} rx="1.5" fill="var(--bg-4)" opacity="0.85"/>;
            })}
            <path d={areaPath} fill={`url(#grad-${color.replace(/[#(),. ]/g,'')})`}/>
            <path d={linePath} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            {daily.map((d,i) => <circle key={i} cx={x(i)} cy={yC(d.cost)} r="2.5" fill={color} stroke="#fff" strokeWidth="1.5"/>)}
          </g>
          {daily.map((d,i) => (i===0 || i===n-1 || i%2===0) && (
            <text key={i} x={padL+x(i)} y={h-10} textAnchor="middle" fontSize="10" fontFamily="var(--font-mono)" fill="var(--fg-3)">{d.d} May</text>
          ))}
        </svg>
      </div>
    </section>
  );
}

function MemberProjectsTable({ projects, memberShare, expanded }){
  return (
    <section className="card" style={{ padding:0, overflow:"hidden" }}>
      <div style={{ padding:"16px 22px", borderBottom:"1px solid var(--line-1)", display:"flex", justifyContent:"space-between", alignItems:"center" }}>
        <div>
          <h2 style={{ margin:0, fontSize:14, fontWeight:600 }}>Projects contributed to</h2>
          <div style={{ fontSize:11.5, color:"var(--fg-2)", marginTop:3 }}>Cost & requests attributed to this member</div>
        </div>
        {!expanded && <button style={btnGhost()}>View all <Icon name="arrow" size={11}/></button>}
      </div>
      <table className="tbl">
        <thead>
          <tr>
            <th style={{ paddingLeft:22 }}>Project</th>
            <th className="right">Their spend</th>
            <th className="right">Requests</th>
            <th>Share of project</th>
            <th style={{ paddingRight:22 }}>Last active</th>
          </tr>
        </thead>
        <tbody>
          {projects.map(p => {
            const memberSpend = p.spend * memberShare;
            const memberReqs = Math.round(p.requests * memberShare);
            return (
              <tr key={p.slug} className="clickable">
                <td style={{ paddingLeft:22 }}>
                  <div style={{ display:"flex", flexDirection:"column", gap:1 }}>
                    <span style={{ color:"var(--fg-0)", fontWeight:500 }}>{p.name}</span>
                    <span className="mono" style={{ fontSize:11, color:"var(--fg-3)" }}>/{p.slug}</span>
                  </div>
                </td>
                <td className="right"><Money value={memberSpend} size="sm"/></td>
                <td className="right mono" style={{ color:"var(--fg-1)" }}>{memberReqs.toLocaleString()}</td>
                <td>
                  <div style={{ display:"flex", alignItems:"center", gap:8, maxWidth:200 }}>
                    <div className="bar-track" style={{ flex:1, height:5 }}>
                      <div className="bar-fill" style={{ width:(memberShare*100)+"%", height:"100%" }}/>
                    </div>
                    <span className="mono" style={{ fontSize:11, color:"var(--fg-2)", minWidth:38, textAlign:"right" }}>{(memberShare*100).toFixed(0)}%</span>
                  </div>
                </td>
                <td className="mono" style={{ color:"var(--fg-2)", fontSize:12, paddingRight:22 }}>{p.lastActive}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </section>
  );
}

function MemberRecentRequests({ memberId }){
  const rows = ACTIVITY.slice(0, 6).map(r => ({ ...r, by: memberId === "vk" ? "Alex" : "Sarah" }));
  return (
    <section className="card" style={{ padding:0, overflow:"hidden" }}>
      <div style={{ padding:"16px 22px", borderBottom:"1px solid var(--line-1)", display:"flex", justifyContent:"space-between" }}>
        <div>
          <h2 style={{ margin:0, fontSize:14, fontWeight:600 }}>Recent requests</h2>
          <div style={{ fontSize:11.5, color:"var(--fg-2)", marginTop:3 }}>Latest LLM calls attributed to them</div>
        </div>
        <button style={btnGhost()}>View all <Icon name="arrow" size={11}/></button>
      </div>
      <table className="tbl">
        <thead>
          <tr>
            <th style={{ paddingLeft:22 }}>Time</th>
            <th>Project</th>
            <th>Model</th>
            <th className="right">Tokens</th>
            <th className="right">Cost</th>
            <th style={{ paddingRight:22 }}>Status</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r,i) => (
            <tr key={i} className="clickable">
              <td style={{ paddingLeft:22 }} className="mono">{r.ts}</td>
              <td className="mono" style={{ fontSize:12, color:"var(--fg-1)" }}>{r.project}</td>
              <td><ModelBadge model={r.model}/></td>
              <td className="right mono" style={{ fontSize:12, color:"var(--fg-1)" }}>{fmtTokens(r.inT + r.outT)}</td>
              <td className="right"><Money value={r.cost * USD_TO_GBP} size="sm"/></td>
              <td style={{ paddingRight:22 }}>
                {r.status === "error"
                  ? <span className="badge badge--neg" style={{ fontSize:10 }}>error</span>
                  : <span style={{ display:"inline-flex", alignItems:"center", gap:5, fontSize:11.5, color:"var(--pos)" }}><span style={{ width:5, height:5, borderRadius:"50%", background:"var(--pos)" }}/>ok</span>}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </section>
  );
}

function ModelUsageCard({ memberId }){
  const mix = memberId === "vk"
    ? [
        { model:"claude-opus-4-7",   share:0.96, reqs:5740 },
        { model:"claude-sonnet-4-6", share:0.03, reqs:172 },
        { model:"claude-haiku-4-5",  share:0.01, reqs:68 },
      ]
    : [
        { model:"claude-sonnet-4-6", share:0.62, reqs:468 },
        { model:"claude-haiku-4-5",  share:0.34, reqs:257 },
        { model:"gemini-3-flash",    share:0.04, reqs:30 },
      ];
  return (
    <div className="card" style={{ padding:"16px 18px" }}>
      <h3 style={{ margin:"0 0 12px", fontSize:12.5, fontWeight:600 }}>Their model mix</h3>
      <div style={{ display:"flex", height:10, borderRadius:99, overflow:"hidden", background:"var(--bg-3)", marginBottom:12 }}>
        {mix.map(m => {
          const meta = MODELS[m.model];
          return <div key={m.model} style={{ width:Math.max(1, m.share*100)+"%", background:PROVIDERS[meta.provider].color, opacity:0.78+m.share*0.22 }}/>;
        })}
      </div>
      <div style={{ display:"flex", flexDirection:"column", gap:8 }}>
        {mix.map(m => {
          const meta = MODELS[m.model];
          return (
            <div key={m.model} style={{ display:"flex", justifyContent:"space-between", alignItems:"baseline", fontSize:12 }}>
              <span style={{ display:"inline-flex", alignItems:"center", gap:6 }}>
                <span style={{ width:6, height:6, borderRadius:2, background:PROVIDERS[meta.provider].color }}/>
                <span className="mono" style={{ color:"var(--fg-1)" }}>{meta.short}</span>
              </span>
              <span style={{ display:"inline-flex", gap:8 }}>
                <span className="mono" style={{ color:"var(--fg-3)", fontSize:11 }}>{m.reqs.toLocaleString()} req</span>
                <span className="mono" style={{ color:"var(--fg-0)", minWidth:36, textAlign:"right" }}>{(m.share*100).toFixed(m.share<0.01?2:0)}%</span>
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function PermissionScopeCard({ m }){
  const r = ROLE_DEFS[m.role];
  return (
    <div className="card" style={{ padding:"16px 18px" }}>
      <h3 style={{ margin:"0 0 10px", fontSize:12.5, fontWeight:600 }}>Permission scope</h3>
      <div style={{ display:"flex", flexDirection:"column", gap:9 }}>
        <div style={{ display:"flex", justifyContent:"space-between", fontSize:12 }}>
          <span style={{ color:"var(--fg-2)" }}>Role</span>
          <RoleBadge role={m.role}/>
        </div>
        <div style={{ display:"flex", justifyContent:"space-between", fontSize:12 }}>
          <span style={{ color:"var(--fg-2)" }}>Scope</span>
          <span style={{ color:"var(--fg-0)" }}>{m.scope}</span>
        </div>
        <div style={{ display:"flex", justifyContent:"space-between", fontSize:12 }}>
          <span style={{ color:"var(--fg-2)" }}>Cost centre</span>
          <span style={{ color:m.id==="vk"?"var(--fg-0)":"var(--warn)" }}>{m.id==="vk"?"Internal ops":"Unassigned"}</span>
        </div>
      </div>
      <button style={{ ...btnGhost(), width:"100%", justifyContent:"center", marginTop:12 }}>Manage access <Icon name="arrow" size={11}/></button>
    </div>
  );
}

function SecurityCard({ m }){
  return (
    <div className="card" style={{ padding:"16px 18px" }}>
      <h3 style={{ margin:"0 0 10px", fontSize:12.5, fontWeight:600 }}>Security</h3>
      <div style={{ display:"flex", flexDirection:"column", gap:9 }}>
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", fontSize:12 }}>
          <span style={{ color:"var(--fg-2)" }}>Two-factor</span>
          {m.twoFA ? <span className="badge badge--pos" style={{ fontSize:10 }}>Enabled</span> : <span className="badge badge--warn" style={{ fontSize:10 }}>Required</span>}
        </div>
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", fontSize:12 }}>
          <span style={{ color:"var(--fg-2)" }}>SSO</span>
          <span style={{ color:"var(--fg-3)" }}>—</span>
        </div>
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", fontSize:12 }}>
          <span style={{ color:"var(--fg-2)" }}>Active sessions</span>
          <span className="mono" style={{ color:"var(--fg-0)" }}>2</span>
        </div>
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", fontSize:12 }}>
          <span style={{ color:"var(--fg-2)" }}>API tokens</span>
          <span className="mono" style={{ color:"var(--fg-3)" }}>0</span>
        </div>
      </div>
    </div>
  );
}

function DangerZoneMember(){
  return (
    <div style={{ padding:"12px 14px", border:"1px dashed rgba(201,58,58,0.3)", borderRadius:10, background:"transparent" }}>
      <div style={{ fontSize:11, color:"var(--neg)", marginBottom:8, letterSpacing:0.04, textTransform:"uppercase", fontWeight:600 }}>Danger zone</div>
      <div style={{ display:"flex", gap:8, flexWrap:"wrap" }}>
        <button style={{ ...btnGhost(), color:"var(--warn)", borderColor:"rgba(185,113,13,0.3)" }}>Suspend account</button>
        <button style={{ ...btnGhost(), color:"var(--neg)", borderColor:"rgba(201,58,58,0.3)" }}>Remove from workspace</button>
      </div>
    </div>
  );
}

function MemberActivityTab({ memberId }){
  const events = [
    { ts:"15 May 14:32", action:"report.generate",   scope:"workspace",         detail:"April 2026 Monthly summary · PDF" },
    { ts:"15 May 13:58", action:"project.update",    scope:"contract-ai",      detail:"set primary model to Opus 4.7" },
    { ts:"14 May 11:08", action:"project.create",    scope:"Marketing Copilot", detail:"created new project" },
    { ts:"13 May 09:21", action:"optimisation.apply",scope:"contract-ai",      detail:"swap 70% of Opus → Sonnet · saved £12.40 / mo" },
    { ts:"12 May 17:44", action:"member.invite",     scope:"workspace",         detail:"invited finance@meridianlegal.co.uk as Viewer" },
    { ts:"11 May 16:02", action:"settings.update",   scope:"workspace",         detail:"changed default currency to GBP" },
  ];
  return (
    <section className="card" style={{ padding:0, overflow:"hidden" }}>
      <table className="tbl">
        <thead>
          <tr>
            <th style={{ paddingLeft:22 }}>Time</th>
            <th>Action</th>
            <th>Scope</th>
            <th style={{ paddingRight:22 }}>Detail</th>
          </tr>
        </thead>
        <tbody>
          {events.map((e,i) => (
            <tr key={i}>
              <td className="mono" style={{ paddingLeft:22, fontSize:11.5, color:"var(--fg-2)" }}>{e.ts}</td>
              <td><span className="mono" style={{ fontSize:11.5, color:"var(--fg-1)", padding:"1px 7px", background:"var(--bg-3)", borderRadius:5 }}>{e.action}</span></td>
              <td className="mono" style={{ fontSize:12, color:"var(--fg-1)" }}>{e.scope}</td>
              <td style={{ fontSize:12, color:"var(--fg-2)", paddingRight:22 }}>{e.detail}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </section>
  );
}

function AccessTab({ m }){
  return (
    <div style={{ display:"grid", gridTemplateColumns:"1.5fr 1fr", gap:18 }}>
      <section className="card" style={{ padding:"20px 22px" }}>
        <SectionHeader title="Project access" subtitle="Specific projects this member can view or edit"/>
        <table className="tbl">
          <thead>
            <tr>
              <th>Project</th>
              <th>Permission</th>
              <th>Granted by</th>
              <th>Since</th>
            </tr>
          </thead>
          <tbody>
            {PROJECTS.slice(0, 5).map(p => (
              <tr key={p.slug}>
                <td>
                  <div style={{ display:"flex", flexDirection:"column" }}>
                    <span style={{ color:"var(--fg-0)", fontWeight:500 }}>{p.name}</span>
                    <span className="mono" style={{ fontSize:11, color:"var(--fg-3)" }}>/{p.slug}</span>
                  </div>
                </td>
                <td><RoleBadge role={m.role === "Owner" ? "Owner" : "Editor"}/></td>
                <td style={{ fontSize:12, color:"var(--fg-2)" }}>{m.role === "Owner" ? "—" : "Alex"}</td>
                <td className="mono" style={{ fontSize:12, color:"var(--fg-2)" }}>{m.since}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </section>

      <section className="card" style={{ padding:"20px 22px" }}>
        <SectionHeader title="API tokens" subtitle="Access tokens"/>
        <div style={{ padding:"30px 0", textAlign:"center", color:"var(--fg-2)", fontSize:13 }}>
          <Icon name="cog" size={28} stroke="var(--fg-3)"/>
          <div style={{ marginTop:10 }}>No API tokens issued</div>
          <button style={{ ...btnSecondary(), marginTop:14 }}><Icon name="plus" size={13}/> Generate token</button>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { Members, MemberDetail });
