/* Admin → Users & access. */
const { useState: useStateAU } = React;

function AdminUsers({ users }) {
  const [section, setSection] = useStateAU('users');
  const sections = [
    { id: 'users',  icon: 'users',     label: 'Users' },
    { id: 'roles',  icon: 'shield',    label: 'Roles & RBAC' },
    { id: 'teams',  icon: 'building',  label: 'Teams' },
    { id: '2fa',    icon: 'key-round', label: '2FA policy' },
    { id: 'log',    icon: 'history',   label: 'Audit log' },
  ];

  return (
    <React.Fragment>
      <div className="mn-page-h">
        <div className="mn-page-title">
          <h1 className="title-1">Users & access</h1>
          <span className="mn-page-count">{users.length} users · acme.monolit.app</span>
        </div>
        <div className="mn-page-actions">
          <Button variant="ghost" size="md" icon="download">Export</Button>
          <Button variant="primary" size="md" icon="user-plus">Invite user</Button>
        </div>
      </div>

      <div className="mn-admin-grid">
        <aside className="mn-admin-side">
          {sections.map((s) => (
            <button key={s.id} type="button"
                    className={'mn-admin-side-item' + (section === s.id ? ' mn-admin-side-item--active' : '')}
                    onClick={() => setSection(s.id)}>
              <Icon name={s.icon} size="sm" />
              <span>{s.label}</span>
            </button>
          ))}
        </aside>

        <div>
          {section === 'users' && <UsersTable users={users} />}
          {section === 'roles' && <RolesMatrix />}
          {section === 'teams' && <TeamsView />}
          {section === '2fa' && <TwoFaPolicy users={users} />}
          {section === 'log' && <AuditTab activity={window.MonolitData.activity} />}
        </div>
      </div>
    </React.Fragment>
  );
}

function UsersTable({ users }) {
  return (
    <div style={{ background: 'var(--bg-1)', border: '1px solid var(--border-1)', borderRadius: 'var(--radi-md)', overflow: 'hidden auto', maxWidth: '100%' }}>
      <div className="mn-toolbar" style={{ padding: 12, borderBottom: '1px solid var(--border-1)' }}>
        <div style={{ width: 280 }}>
          <Input fullWidth icon="search" placeholder="Search users…" />
        </div>
        <Button variant="ghost" size="md" icon="filter">All roles</Button>
        <Button variant="ghost" size="md" icon="filter">All teams</Button>
        <div className="mn-toolbar-spacer" />
        <Button variant="ghost" size="md" icon="user-x">Disabled (1)</Button>
      </div>
      <div style={{ overflowX: 'auto' }}>
      <table className="mn-table">
        <thead>
          <tr>
            <th style={{ width: 36 }}><input type="checkbox" className="mn-checkbox" /></th>
            <th>User</th>
            <th>Role</th>
            <th>Team</th>
            <th>2FA</th>
            <th>Status</th>
            <th>Last seen</th>
            <th style={{ width: 36 }}></th>
          </tr>
        </thead>
        <tbody>
          {users.map((u) => {
            const color = ['teal', 'blue', 'orange', 'slate', 'green'][u.id.charCodeAt(1) % 5];
            const initials = u.name.split(' ').map(p => p[0]).slice(0, 2).join('');
            const av = { initials, color };
            return (
              <tr key={u.id}>
                <td><input type="checkbox" className="mn-checkbox" /></td>
                <td>
                  <div className="mn-cell-name">
                    <Avatar user={av} size={26} />
                    <div className="mn-cell-name-text">
                      <strong>{u.name}</strong>
                      <span>{u.email}</span>
                    </div>
                  </div>
                </td>
                <td><RoleBadge role={u.role} /></td>
                <td><span style={{ font: 'var(--font-weight-medium) 13px/16px var(--font-sans)' }}>{u.team}</span></td>
                <td>
                  {u.twofa
                    ? <span className="mn-chip mn-chip--md mn-chip--st-qual"><Icon name="shield-check" size="xs" stroke="2"/>Enabled</span>
                    : <span className="mn-chip mn-chip--md mn-chip--problem"><Icon name="shield-off" size="xs" stroke="2"/>Off</span>}
                </td>
                <td>
                  {u.status === 'active'  ? <span className="mn-chip mn-chip--md mn-chip--st-qual">Active</span> :
                   u.status === 'invited' ? <span className="mn-chip mn-chip--md mn-chip--st-new">Invited</span> :
                                            <span className="mn-chip mn-chip--md mn-chip--st-arc">Disabled</span>}
                </td>
                <td><span className="mn-mono" style={{ fontSize: 12, color: 'var(--text-3)' }}>{u.lastSeen}</span></td>
                <td><IconButton icon="more-horizontal" size="sm" title="Row actions" /></td>
              </tr>
            );
          })}
        </tbody>
      </table>
      </div>
    </div>
  );
}

function RoleBadge({ role }) {
  const map = {
    'Admin':            { tone: 'st-qual',  icon: 'shield' },
    'Operations Admin': { tone: 'st-conv',  icon: 'shield-half' },
    'Manager':          { tone: 'st-ip',    icon: 'users' },
    'Sales Rep':        { tone: 'st-new',   icon: 'user' },
    'Viewer':           { tone: 'st-disq',  icon: 'eye' },
  };
  const m = map[role] || map['Sales Rep'];
  return <span className={`mn-chip mn-chip--md mn-chip--${m.tone}`}><Icon name={m.icon} size="xs" stroke="2"/>{role}</span>;
}

function RolesMatrix() {
  const rows = [
    { lbl: 'View leads (all tenant)',           A: 'y', O: 'y', M: 'team', R: 'own',   V: 'y' },
    { lbl: 'Edit lead status',                  A: 'y', O: 'y', M: 'y',    R: 'y',     V: 'n' },
    { lbl: 'Assign / reassign owner',           A: 'y', O: 'y', M: 'y',    R: 'n',     V: 'n' },
    { lbl: 'Unassign owner (destructive)',      A: 'y', O: 'y', M: 'n',    R: 'n',     V: 'n' },
    { lbl: 'Convert lead → client + deal',      A: 'y', O: 'y', M: 'y',    R: 'qual',  V: 'n' },
    { lbl: 'Archive lead',                      A: 'y', O: 'y', M: 'y',    R: 'n',     V: 'n' },
    { lbl: 'Permanent delete',                  A: 'y', O: 'n', M: 'n',    R: 'n',     V: 'n' },
    { lbl: 'Bulk actions (≥1 lead)',            A: 'y', O: 'y', M: 'y',    R: 'n',     V: 'n' },
    { lbl: 'Manage users & roles',              A: 'y', O: 'n', M: 'n',    R: 'n',     V: 'n' },
  ];
  const Cell = ({ v }) => {
    if (v === 'y')    return <Icon name="check"    size="sm" color="success" stroke="2" />;
    if (v === 'n')    return <Icon name="minus"    size="sm" color="text-3"  stroke="2" />;
    if (v === 'team') return <span className="mn-chip mn-chip--tag">team only</span>;
    if (v === 'own')  return <span className="mn-chip mn-chip--tag">own only</span>;
    if (v === 'qual') return <span className="mn-chip mn-chip--tag">if qualified</span>;
    return v;
  };
  return (
    <Card title="Roles & RBAC matrix" eyebrow="Five MVP roles · server-enforced" padding="md">
      <table className="mn-table" style={{ borderTop: '1px solid var(--border-1)' }}>
        <thead>
          <tr>
            <th>Capability</th>
            <th style={{ width: 110, textAlign: 'center' }}>Admin</th>
            <th style={{ width: 130, textAlign: 'center' }}>Ops Admin</th>
            <th style={{ width: 110, textAlign: 'center' }}>Manager</th>
            <th style={{ width: 110, textAlign: 'center' }}>Sales Rep</th>
            <th style={{ width: 110, textAlign: 'center' }}>Viewer</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r) => (
            <tr key={r.lbl}>
              <td style={{ font: 'var(--font-weight-medium) 13px/18px var(--font-sans)' }}>{r.lbl}</td>
              {['A','O','M','R','V'].map(k => <td key={k} style={{ textAlign: 'center' }}><Cell v={r[k]} /></td>)}
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

function TeamsView() {
  const teams = [
    { name: 'Trading EU',  manager: 'Daniyar K.', members: 4, leads: 38 },
    { name: 'Real Estate', manager: 'Pavel Sych', members: 3, leads: 24 },
    { name: 'Insurance',   manager: 'Tetiana B.', members: 2, leads: 9 },
  ];
  return (
    <Card title="Teams" eyebrow="Named Team entities · used by Manager scope" padding="md"
          action={<Button variant="primary" size="sm" icon="plus">New team</Button>}>
      <table className="mn-table">
        <thead><tr><th>Team</th><th>Manager</th><th>Members</th><th>Leads owned</th><th></th></tr></thead>
        <tbody>
          {teams.map((t) => (
            <tr key={t.name}>
              <td style={{ font: 'var(--font-weight-strong) 13px/18px var(--font-sans)' }}>{t.name}</td>
              <td>{t.manager}</td>
              <td>{t.members}</td>
              <td><span className="mn-mono" style={{ fontSize: 13 }}>{t.leads}</span></td>
              <td style={{ textAlign: 'right' }}><IconButton icon="more-horizontal" size="sm" /></td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}

function TwoFaPolicy({ users }) {
  const enabled = users.filter(u => u.twofa).length;
  const total = users.length;
  return (
    <Card title="2FA policy" eyebrow={`${enabled}/${total} users enrolled`} padding="md">
      <div className="mn-stack-lg">
        <div className="mn-row" style={{ justifyContent: 'space-between' }}>
          <div>
            <div style={{ font: 'var(--font-weight-strong) 14px/20px var(--font-sans)' }}>Require 2FA for all users</div>
            <div style={{ font: 'var(--font-weight-medium) 12px/16px var(--font-sans)', color: 'var(--text-3)' }}>Users without 2FA will be prompted at next login.</div>
          </div>
          <Toggle on />
        </div>
        <div className="mn-row" style={{ justifyContent: 'space-between' }}>
          <div>
            <div style={{ font: 'var(--font-weight-strong) 14px/20px var(--font-sans)' }}>Require 2FA for Admin / Ops Admin</div>
            <div style={{ font: 'var(--font-weight-medium) 12px/16px var(--font-sans)', color: 'var(--text-3)' }}>Always enforced. Cannot be disabled.</div>
          </div>
          <Toggle on locked />
        </div>
        <div className="mn-row" style={{ justifyContent: 'space-between' }}>
          <div>
            <div style={{ font: 'var(--font-weight-strong) 14px/20px var(--font-sans)' }}>Allow SMS as a 2FA method</div>
            <div style={{ font: 'var(--font-weight-medium) 12px/16px var(--font-sans)', color: 'var(--text-3)' }}>Recommended: TOTP only.</div>
          </div>
          <Toggle on={false} />
        </div>
      </div>
    </Card>
  );
}

function Toggle({ on, locked }) {
  return (
    <span style={{
      width: 36, height: 20, borderRadius: 9999,
      background: on ? 'var(--primary-main)' : 'var(--bg-3)',
      position: 'relative', cursor: locked ? 'not-allowed' : 'pointer',
      opacity: locked ? 0.7 : 1, transition: 'background 100ms',
    }}>
      <span style={{
        position: 'absolute', top: 2, left: on ? 18 : 2,
        width: 16, height: 16, borderRadius: 9999, background: '#fff',
        transition: 'left 100ms',
      }} />
    </span>
  );
}

Object.assign(window, { AdminUsers });
