// role-system.jsx — "System" backend admin area (officer-level). Accounts &
// roles, access codes issued on sale, company configuration (persisted), and
// the data model / integration health for a technical buyer's "deeper dive".

function RoleSystem() {
  const [tab, setTab] = useState('accounts');
  return (
    <>
      <PageHeader
        eyebrow="SYSTEM · BACKEND ADMIN"
        title="System administration"
        subtitle="Identity directory, access codes, company configuration, and the data model behind every app."
        right={<Pill tone="dark"><IconSettings size={12} /> Officer access</Pill>}
      />
      <div style={{ padding: '14px 32px 0', borderBottom: '1px solid var(--line)', background: 'var(--panel)', display: 'flex', gap: 4 }}>
        {[
          { id: 'accounts', label: 'Accounts & roles' },
          { id: 'codes', label: 'Access codes' },
          { id: 'company', label: 'Company config' },
          { id: 'server', label: 'Server & identity' },
          { id: 'data', label: 'Data & integrations' },
        ].map(t => {
          const on = tab === t.id;
          return (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              padding: '10px 14px', background: 'transparent', border: 'none',
              borderBottom: on ? '2px solid var(--accent)' : '2px solid transparent', marginBottom: -1,
              color: on ? 'var(--text)' : 'var(--muted)', fontWeight: on ? 600 : 500, fontSize: 13.5,
            }}>{t.label}</button>
          );
        })}
      </div>
      <PageBody>
        {tab === 'accounts' && <AccountsTab />}
        {tab === 'codes' && <AccessCodesTab />}
        {tab === 'company' && <CompanyConfigTab />}
        {tab === 'server' && <ServerIdentityTab />}
        {tab === 'data' && <DataModelTab />}
      </PageBody>
    </>
  );
}

// ── Accounts ─────────────────────────────────────────────────
function AccountsTab() {
  const { toast } = useAdmin();
  const [accounts, setAccounts] = useState(() => {
    const saved = dbLoad().accounts;
    return saved || ACCOUNTS;
  });
  const persist = (next) => { setAccounts(next); dbSave({ accounts: next }); };
  const toggleStatus = (id) => {
    persist(accounts.map(a => a.id === id ? { ...a, status: a.status === 'active' ? 'suspended' : 'active' } : a));
    toast('Account status updated · saved', 'success');
  };

  const roleTone = { officer: 'dark', ops: 'accent', safety: 'info', dispatch: 'indigo', accounting: 'good', employee: 'neutral' };
  const appPill = { console: 'Console', tablet: 'Tablet', portal: 'Portal' };

  const cols = [
    { key: 'name', label: 'User', render: (r) => (
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 30, height: 30, borderRadius: 15, background: 'var(--panel-3)', display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700 }}>{A_initials(r.name)}</div>
        <div><div style={{ fontWeight: 600 }}>{r.name}</div><div style={{ fontSize: 11, color: 'var(--muted)' }}>{r.email}</div></div>
      </div>
    ) },
    { key: 'role', label: 'Role', render: (r) => <Pill tone={roleTone[r.role]}>{r.role}</Pill> },
    { key: 'apps', label: 'Apps', render: (r) => <div style={{ display: 'flex', gap: 4 }}>{r.apps.map(a => <Pill key={a} tone="neutral">{appPill[a]}</Pill>)}</div> },
    { key: 'mfa', label: 'MFA', render: (r) => r.mfa ? <Pill tone="good"><IconCheck size={10} /> On</Pill> : <Pill tone="warn">Off</Pill> },
    { key: 'lastLogin', label: 'Last login', mono: true, render: (r) => r.lastLogin.replace('T', ' ') },
    { key: 'status', label: 'Status', render: (r) => (
      <button onClick={() => toggleStatus(r.id)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>
        {r.status === 'active' ? <Pill tone="good"><StatusDot tone="good" size={6} /> Active</Pill> : <Pill tone="bad">Suspended</Pill>}
      </button>
    ) },
  ];

  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 20 }}>
        <KPI label="Total accounts" value={accounts.length} icon={<IconUsersBig size={16} />} />
        <KPI label="Active" value={accounts.filter(a => a.status === 'active').length} tone="good" icon={<IconCheck size={16} />} />
        <KPI label="MFA enabled" value={`${Math.round(accounts.filter(a => a.mfa).length / accounts.length * 100)}%`} tone="info" icon={<IconShield size={16} />} />
        <KPI label="Suspended" value={accounts.filter(a => a.status === 'suspended').length} tone={accounts.some(a => a.status === 'suspended') ? 'bad' : 'neutral'} icon={<IconAlert size={16} />} />
      </div>
      <AdminSection title="Identity directory"
        action={<><span style={{ fontSize: 12, color: 'var(--muted)' }}>Shared across Console · Tablet · Portal</span><Button variant="primary" size="sm" icon={<IconPlus size={12} />} onClick={() => toast('Invite user — enter email & role', 'info')}>Invite user</Button></>}>
        <DataTable columns={cols} rows={accounts} />
      </AdminSection>
    </>
  );
}

// ── Access codes ─────────────────────────────────────────────
function AccessCodesTab() {
  const { toast } = useAdmin();
  return (
    <>
      <div style={{ background: 'var(--info-soft)', border: '1px solid rgba(29,111,184,0.25)', borderRadius: 10, padding: '11px 16px', marginBottom: 18, fontSize: 13, color: 'var(--info)' }}>
        Access codes are issued to a client on sale. Each role gets a code; share it with the staff who need that view. Codes can be rotated at any time.
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
        {ROLES.map(r => (
          <div key={r.id} style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 42, height: 42, borderRadius: 10, background: r.accent, color: '#fff', display: 'grid', placeItems: 'center', fontWeight: 700, fontFamily: 'var(--font-mono)', fontSize: 12 }}>{r.short}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 700, fontSize: 14 }}>{r.label}</div>
              <div className="mono" style={{ fontSize: 13, color: 'var(--accent-deep)', fontWeight: 600, letterSpacing: 0.5 }}>{ACCESS_CODES[r.id]}</div>
            </div>
            <Button variant="secondary" size="sm" icon={<IconRefresh size={12} />} onClick={() => toast(`${r.label} access code rotated`, 'success')}>Rotate</Button>
          </div>
        ))}
        <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 42, height: 42, borderRadius: 10, background: '#0F172A', color: '#fff', display: 'grid', placeItems: 'center', fontWeight: 700, fontFamily: 'var(--font-mono)', fontSize: 11 }}>SYS</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 14 }}>System / Officer master</div>
            <div className="mono" style={{ fontSize: 13, color: 'var(--accent-deep)', fontWeight: 600 }}>SYS-2026-0001</div>
          </div>
          <Pill tone="bad">Restricted</Pill>
        </div>
      </div>
    </>
  );
}

// ── Company config (persisted) ───────────────────────────────
function CompanyConfigTab() {
  const { toast } = useAdmin();
  const [cfg, setCfg] = useState(() => ({ ...COMPANY_CONFIG, ...(dbLoad().company || {}) }));
  const set = (k, v) => setCfg(c => ({ ...c, [k]: v }));
  const setAddon = (id, v) => setCfg(c => ({ ...c, addons: { ...(c.addons || {}), [id]: v } }));
  const save = () => { dbSave({ company: cfg }); toast('Company configuration saved', 'success'); };

  const row = (label, k, opts) => (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '11px 0', borderTop: '1px solid var(--line)' }}>
      <span style={{ fontSize: 13.5, color: 'var(--text-2)' }}>{label}</span>
      {opts ? (
        <select value={cfg[k]} onChange={e => set(k, e.target.value)} style={{ padding: '6px 10px', border: '1px solid var(--line-strong)', borderRadius: 8, fontSize: 13, background: 'var(--panel)' }}>
          {opts.map(o => <option key={o} value={o}>{o}</option>)}
        </select>
      ) : (
        <input value={cfg[k]} onChange={e => set(k, e.target.value)} style={{ padding: '6px 10px', border: '1px solid var(--line-strong)', borderRadius: 8, fontSize: 13, background: 'var(--panel)', textAlign: 'right', width: 280, fontFamily: 'var(--font-mono)' }} />
      )}
    </div>
  );

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, maxWidth: 1100 }}>
      <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: '4px 18px 18px' }}>
        <div className="eyebrow" style={{ padding: '14px 0 4px' }}>LEGAL ENTITY</div>
        {row('Legal name', 'legalName')}
        {row('EIN', 'ein')}
        {row('RRB BA number', 'rrbBaNumber')}
        {row('Address', 'address')}
        {row('Fiscal year', 'fiscalYear', ['Calendar (Jan–Dec)', 'Jul–Jun', 'Oct–Sep'])}
      </div>
      <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: '4px 18px 18px' }}>
        <div className="eyebrow" style={{ padding: '14px 0 4px' }}>PAYROLL DEFAULTS</div>
        {row('Pay frequency', 'payFrequency', ['Weekly', 'Bi-weekly', 'Semi-monthly', 'Monthly'])}
        {row('OT threshold (hrs/day)', 'otThreshold')}
        {row('OT multiplier', 'otMultiplier')}
        {row('Mileage rate ($/mi)', 'mileageRate')}
        {row('Per-diem rate ($/day)', 'perDiemRate')}
        {row('Tax policy', 'taxPolicy', ['home', 'work', 'hybrid'])}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '11px 0', borderTop: '1px solid var(--line)' }}>
          <div>
            <div style={{ fontSize: 13.5, color: 'var(--text-2)' }}>Railroad Retirement (RRTA)</div>
            <div style={{ fontSize: 11.5, color: 'var(--muted)', maxWidth: 320, lineHeight: 1.4 }}>Most flagging companies are under FICA, not RRB. Only enable if you actually pay into Railroad Retirement.</div>
          </div>
          <button onClick={() => set('rrbEnabled', !cfg.rrbEnabled)} style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'transparent', border: 'none', cursor: 'pointer' }}>
            <span style={{ width: 42, height: 24, borderRadius: 12, background: cfg.rrbEnabled ? 'var(--good)' : 'var(--line-strong)', position: 'relative', transition: 'background 160ms' }}>
              <span style={{ position: 'absolute', top: 3, left: cfg.rrbEnabled ? 21 : 3, width: 18, height: 18, borderRadius: 9, background: '#fff', transition: 'left 160ms' }} />
            </span>
            <span style={{ fontSize: 12.5, fontWeight: 600, color: cfg.rrbEnabled ? 'var(--good)' : 'var(--muted)' }}>{cfg.rrbEnabled ? 'Enrolled' : 'FICA only'}</span>
          </button>
        </div>
        <div style={{ marginTop: 14 }}>
          <Button variant="primary" icon={<IconCheck size={14} />} onClick={save} style={{ width: '100%' }}>Save configuration</Button>
          <div style={{ fontSize: 11, color: 'var(--muted)', textAlign: 'center', marginTop: 8 }}>Persists across refresh · would write to the API in production.</div>
        </div>
      </div>

      {/* Add-on modules — purchasable, off by default */}
      <div style={{ gridColumn: '1 / -1', background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: '4px 18px 18px' }}>
        <div className="eyebrow" style={{ padding: '14px 0 4px' }}>ADD-ON MODULES · SOLD SEPARATELY</div>
        <div style={{ fontSize: 12.5, color: 'var(--muted)', marginBottom: 12, lineHeight: 1.5 }}>
          Optional modules enabled per-contract at purchase. Off by default — these are upsells beyond the base platform.
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          {ADDON_MODULES.map(m => {
            const on = !!(cfg.addons && cfg.addons[m.id]);
            return (
              <div key={m.id} style={{ background: on ? 'var(--good-soft)' : 'var(--panel-2)', border: `1px solid ${on ? 'var(--good)' : 'var(--line)'}`, borderRadius: 12, padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <span style={{ fontWeight: 700, fontSize: 14 }}>{m.name}</span>
                  <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: 'var(--accent-deep)' }}>{m.priceNote}</span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--muted)', lineHeight: 1.5, flex: 1 }}>{m.desc}</div>
                <div style={{ fontSize: 11, color: 'var(--muted-2)', fontStyle: 'italic' }}>{m.sells}</div>
                <button onClick={() => setAddon(m.id, !on)} style={{
                  marginTop: 4, padding: '8px 12px', borderRadius: 8, border: 'none', cursor: 'pointer',
                  background: on ? 'var(--good)' : 'var(--text)', color: '#fff', fontWeight: 600, fontSize: 12.5,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                }}>
                  {on ? <><IconCheck size={13} /> Enabled · click to disable</> : 'Enable module'}
                </button>
              </div>
            );
          })}
        </div>
        <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 10 }}>
          <Button variant="primary" icon={<IconCheck size={14} />} onClick={save}>Save add-ons</Button>
          <a href="../client/index.html" target="_blank" style={{ fontSize: 12.5, color: 'var(--accent-deep)', fontWeight: 600, textDecoration: 'none' }}>Open Client Portal →</a>
        </div>
      </div>
    </div>
  );
}

// ── Data model + integration health ──────────────────────────
function DataModelTab() {
  const { integrations } = useAdmin();
  return (
    <>
      <AdminSection title="Data model" >
        <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: -6, marginBottom: 12 }}>Every entity the platform stores and where it originates — the spine that connects the field tablet, console, and employee portal.</div>
        <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, overflow: 'hidden' }}>
          {DATA_MODEL.map((e, i) => (
            <div key={e.entity} style={{ display: 'grid', gridTemplateColumns: '160px 70px 1fr 200px', gap: 14, padding: '11px 16px', borderTop: i === 0 ? 'none' : '1px solid var(--line)', alignItems: 'center' }}>
              <div style={{ fontWeight: 700, fontSize: 13.5, fontFamily: 'var(--font-mono)' }}>{e.entity}</div>
              <div className="mono" style={{ fontSize: 13, color: 'var(--accent)' }}>{e.count}</div>
              <div className="mono" style={{ fontSize: 11.5, color: 'var(--muted)' }}>{e.fields}</div>
              <div><Pill tone="neutral">{e.source}</Pill></div>
            </div>
          ))}
        </div>
      </AdminSection>
      <AdminSection title="Integration health">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          {integrations.filter(i => i.status === 'connected').map(i => (
            <div key={i.id} style={{ background: 'var(--panel)', border: '1px solid var(--good)', borderRadius: 12, padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
              <StatusDot tone="good" size={8} pulse />
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, fontSize: 13.5 }}>{i.name}</div>
                <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{i.format} · synced {typeof i.lastSync === 'string' && i.lastSync.includes('T') ? i.lastSync.slice(5, 16).replace('T', ' ') : i.lastSync}</div>
              </div>
              <Pill tone="good">healthy</Pill>
            </div>
          ))}
        </div>
      </AdminSection>
    </>
  );
}

// ── Server & identity status panel ───────────────────────────
function ServerIdentityTab() {
  const { toast } = useAdmin();
  const [, force] = useState(0);
  const health = RFP.server.health();
  const cfg = RFP.idp.config();
  const log = RFP.server.requestLog();
  const db = RFP.db.get();
  const sessions = db.sessions || [];

  const ping = () => { RFP.server.api('GET', '/v1/health', null, {}); toast('Health check 200 OK', 'success'); force(x => x + 1); };
  const reseed = () => { RFP.db.reseed(); toast('Identity directory reseeded', 'info'); force(x => x + 1); };

  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 20 }}>
        <KPI label="Server" value="200" sub="OK" tone="good" icon={<IconCheck size={16} />} footer={`v${health.data.version}`} />
        <KPI label="Identity provider" value="OIDC" sub="HS256" tone="info" icon={<IconShield size={16} />} footer="auth.railflagspro.com" />
        <KPI label="Accounts" value={db.users.length} sub="in directory" icon={<IconUsersBig size={16} />} />
        <KPI label="Active sessions" value={sessions.length} sub="tokens issued" tone="accent" icon={<IconSettings size={16} />} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
        <AdminSection title="Identity provider"
          action={<Button variant="secondary" size="sm" onClick={reseed}>Reseed directory</Button>}>
          <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: 16 }}>
            {[['Issuer', cfg.issuer], ['Token endpoint', cfg.token_endpoint], ['Userinfo', cfg.userinfo_endpoint], ['JWKS', cfg.jwks_uri], ['Signing alg', cfg.id_token_signing_alg_values_supported.join(', ')]].map(([k, v]) => (
              <div key={k} style={{ marginBottom: 10 }}>
                <div style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 600 }}>{k}</div>
                <div className="mono" style={{ fontSize: 11.5, wordBreak: 'break-all' }}>{v}</div>
              </div>
            ))}
            <div style={{ paddingTop: 10, borderTop: '1px solid var(--line)', display: 'flex', flexWrap: 'wrap', gap: 5 }}>
              {cfg.grant_types_supported.map(g => <Pill key={g} tone="neutral">{g}</Pill>)}
            </div>
          </div>
          <div style={{ marginTop: 12, background: 'var(--good-soft)', border: '1px solid var(--good)', borderRadius: 10, padding: '11px 14px', fontSize: 12.5, color: 'var(--good)' }}>
            <b>Tokens are signed JWTs</b> (header.payload.signature). Passwords are salted-hashed; the directory, sessions, and request log persist server-side.
          </div>
        </AdminSection>

        <AdminSection title={`API request log (${log.length})`}
          action={<Button variant="secondary" size="sm" icon={<IconCheck size={12} />} onClick={ping}>Ping /health</Button>}>
          <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, overflow: 'hidden', maxHeight: 420, overflowY: 'auto' }}>
            {log.length === 0 && <div style={{ padding: 24, textAlign: 'center', color: 'var(--muted)', fontSize: 13 }}>No requests logged yet.</div>}
            {log.map((r, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 14px', borderTop: i === 0 ? 'none' : '1px solid var(--line)' }}>
                <span style={{ minWidth: 50 }}><Pill tone={{ GET: 'info', POST: 'good', PATCH: 'warn', DELETE: 'bad' }[r.method] || 'neutral'}>{r.method}</Pill></span>
                <span className="mono" style={{ flex: 1, fontSize: 11.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.path}</span>
                <span className="mono" style={{ fontSize: 11, fontWeight: 700, color: r.status < 300 ? 'var(--good)' : r.status < 500 ? 'var(--warn)' : 'var(--bad)' }}>{r.status}</span>
                <span className="mono" style={{ fontSize: 10.5, color: 'var(--muted-2)' }}>{r.ms}ms</span>
              </div>
            ))}
          </div>
        </AdminSection>
      </div>
    </>
  );
}

Object.assign(window, { RoleSystem, ServerIdentityTab });