// Team & Access — admin view for managing users + showroom allocation (leadership only)
function Admin({ users, showrooms, accessMatrix, onSetAccess, onUpdateUser, onInviteUser, onDeleteUser, onResendInvite, currentUser }) {
  const [editingId, setEditingId] = React.useState(null);
  const [inviteOpen, setInviteOpen] = React.useState(false);
  const [search, setSearch] = React.useState('');
  const [roleFilter, setRoleFilter] = React.useState('all');
  const [statusFilter, setStatusFilter] = React.useState('all');

  let rows = users;
  if (search) {
    const q = search.toLowerCase();
    rows = rows.filter(u => u.name.toLowerCase().includes(q) || u.email.toLowerCase().includes(q));
  }
  if (roleFilter !== 'all') rows = rows.filter(u => u.role === roleFilter);
  if (statusFilter !== 'all') rows = rows.filter(u => u.status === statusFilter);

  const counts = {
    total: users.length,
    leadership: users.filter(u => u.role === 'leadership').length,
    salesperson: users.filter(u => u.role === 'sales_designer').length,
    invited: users.filter(u => u.status === 'invited').length,
  };

  return (
    <div>
      {/* Info card explaining the model */}
      <div className="card" style={{ marginBottom: 16, padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 14, background: 'var(--info-soft)', border: '1px solid oklch(0.85 0.04 240)' }}>
        <div style={{
          width: 32, height: 32, borderRadius: 16,
          background: 'var(--info)',
          color: 'white',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>
          <Icon name="alert" size={16} color="white"/>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'oklch(0.3 0.1 240)', marginBottom: 2 }}>
            How access works
          </div>
          <div style={{ fontSize: 12, color: 'oklch(0.35 0.08 240)' }}>
            Each team member signs in with their email. Their <strong>role</strong> and <strong>assigned showrooms</strong> are set here — sales designers only see deals from their assigned showroom(s); leadership sees everything. Changes take effect the next time the user refreshes.
          </div>
        </div>
      </div>

      <div className="grid-kpis" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
        <Kpi label="Total users" value={counts.total} foot={`${counts.leadership} leadership · ${counts.salesperson} reps`} deltaPct={0}/>
        <Kpi label="Active" value={users.filter(u => u.status === 'active').length} foot="signed in within 30 days" deltaPct={0.05}/>
        <Kpi label="Pending invites" value={counts.invited} foot="awaiting first sign-in" deltaPct={0} alert={counts.invited > 0}/>
        <Kpi label="Showrooms covered" value={showrooms.length} foot="all 4 staffed" deltaPct={0}/>
      </div>

      {accessMatrix && (
        <div className="card" style={{ marginBottom: 16, padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 10, background: 'var(--surface-2)', border: '1px solid var(--border)' }}>
          <Icon name="lock" size={14} color="var(--ink-3)"/>
          <span style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>Section access by role has moved to <strong>Admin → Settings → Access &amp; Roles</strong>.</span>
        </div>
      )}

      <div className="card">
        <div className="card-hd">
          <div>
            <div className="card-title">Team & access</div>
            <div className="card-sub">Manage who can sign in and which showrooms each person can see</div>
          </div>
          <button className="btn primary" onClick={() => setInviteOpen(true)}>
            <Icon name="plus" size={12}/> Invite team member
          </button>
        </div>

        <div className="filters-bar" style={{ padding: '10px 18px', borderTop: 0 }}>
          <div className="topbar-search" style={{ marginLeft: 0 }}>
            <span className="search-icon"><Icon name="search" size={12}/></span>
            <input
              placeholder="Search by name or email…"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              style={{ width: 220 }}
            />
          </div>
          <select className="sel" value={roleFilter} onChange={(e) => setRoleFilter(e.target.value)}>
            <option value="all">All roles</option>
            <option value="leadership">Leadership</option>
            <option value="salesperson">Sales Designers</option>
          </select>
          <select className="sel" value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)}>
            <option value="all">All statuses</option>
            <option value="active">Active</option>
            <option value="invited">Invited</option>
            <option value="disabled">Disabled</option>
          </select>
          {(search || roleFilter !== 'all' || statusFilter !== 'all') && (
            <button
              className="filter-chip"
              onClick={() => { setSearch(''); setRoleFilter('all'); setStatusFilter('all'); }}
              style={{ marginLeft: 4 }}
            >
              <Icon name="close" size={11}/> Clear filters
            </button>
          )}
        </div>

        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>User</th>
                <th>Email · login</th>
                <th>Role</th>
                <th>Showroom access</th>
                <th>Status</th>
                <th>Last sign-in</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {rows.map(u => (
                <tr key={u.id} onClick={() => setEditingId(u.id)}>
                  <td>
                    <div className="customer-cell">
                      <span className="avatar sm" style={u.avatarColor ? { background: u.avatarColor } : null}>
                        {u.name.split(' ').map(s => s[0]).slice(0, 2).join('')}
                      </span>
                      <div className="customer-meta">
                        <div className="customer-name">{u.name}</div>
                        <div className="customer-sub">{u.title}</div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <div className="mono" style={{ fontSize: 11.5, color: 'var(--ink-2)' }}>{u.email}</div>
                  </td>
                  <td>
                    <span className={`role-pill ${u.role}`} style={{ marginLeft: 0 }}>
                      {u.role === 'admin' ? 'Admin'
                        : u.role === 'leadership' ? 'Leadership'
                        : u.role === 'manager' ? 'Manager'
                        : 'Sales Designer'}
                    </span>
                  </td>
                  <td>
                    {(u.role === 'admin' || u.role === 'leadership') ? (
                      <span className="pill" style={{ background: 'var(--accent-soft)', color: 'var(--accent-ink)' }}>
                        <span className="dot" style={{ background: 'var(--accent)' }}></span>
                        All showrooms
                      </span>
                    ) : (
                      ((u.role === 'manager' ? u.manages : u.works) || []).map(sid => {
                        const s = showrooms.find(x => x.id === sid);
                        return s ? (
                          <span key={sid} className="pill" style={{ marginRight: 4 }}>
                            <span className={`ss-tab-dot ${sid}`}></span>
                            {s.name}
                          </span>
                        ) : null;
                      })
                    )}
                  </td>
                  <td>
                    <span className={`status-pill ${u.status}`}>
                      <span className="dot"></span>
                      {u.status === 'active' ? 'Active' : u.status === 'invited' ? 'Invited' : 'Disabled'}
                    </span>
                  </td>
                  <td style={{ fontSize: 12, color: 'var(--ink-3)' }}>
                    {u.lastLogin || <em style={{ fontStyle: 'normal', color: 'var(--ink-4)' }}>— never —</em>}
                  </td>
                  <td>
                    <div style={{ display: 'flex', gap: 4 }}>
                      <button
                        className="btn icon sm"
                        title={u.status === 'invited' ? 'Resend invite' : 'Send password reset link'}
                        onClick={(e) => { e.stopPropagation(); onResendInvite(u); }}
                      >
                        <Icon name="mail" size={13}/>
                      </button>
                      <button className="btn icon sm" onClick={(e) => { e.stopPropagation(); setEditingId(u.id); }}>
                        <Icon name="edit" size={13}/>
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
              {rows.length === 0 && (
                <tr><td colSpan="7" className="empty">No team members match the current filters.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {editingId && (
        <UserEditPanel
          user={users.find(u => u.id === editingId)}
          showrooms={showrooms}
          currentUser={currentUser}
          onClose={() => setEditingId(null)}
          onSave={(patch) => { onUpdateUser(editingId, patch); }}
          onDelete={() => { onDeleteUser(editingId); setEditingId(null); }}
          onResendInvite={() => onResendInvite(users.find(u => u.id === editingId))}
        />
      )}
      {inviteOpen && (
        <InviteModal
          showrooms={showrooms}
          onClose={() => setInviteOpen(false)}
          onInvite={(user) => { onInviteUser(user); setInviteOpen(false); }}
        />
      )}
    </div>
  );
}

function UserEditPanel({ user, showrooms, currentUser, onClose, onSave, onDelete, onResendInvite }) {
  const [draft, setDraft] = React.useState({ ...user });
  const isSelf = user.id === currentUser.id;

  const toggleShowroom = (sid) => {
    const works = (draft && draft.works) || [];
    const next = works.includes(sid) ? works.filter(x => x !== sid) : [...works, sid];
    if (next.length === 0) return; // must have at least one
    let home = (draft && draft.home) || null;
    if (!next.includes(home)) home = next[0];
    setDraft({ ...(draft || {}), works: next, home });
  };

  const save = () => {
    onSave(draft);
    onClose();
  };

  return (
    <div>
      <div className="detail-overlay" onClick={onClose}/>
      <div className="detail-panel">
        <div className="detail-hd">
          <div className="detail-row1">
            <span className="detail-id mono">{user.email}</span>
            <button className="detail-close" onClick={onClose}><Icon name="close" size={16}/></button>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span className="avatar lg" style={user.avatarColor ? { background: user.avatarColor } : null}>
              {user.name.split(' ').map(s => s[0]).slice(0, 2).join('')}
            </span>
            <div>
              <div className="detail-customer">{user.name}</div>
              <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>{user.title}</div>
            </div>
            <span className={`status-pill ${user.status}`} style={{ marginLeft: 'auto' }}>
              <span className="dot"></span>
              {user.status === 'active' ? 'Active' : user.status === 'invited' ? 'Invited' : 'Disabled'}
            </span>
          </div>
        </div>

        <div className="detail-body">
          <div className="detail-section">
            <h4>Login & identity</h4>
            <div className="detail-grid">
              <div className="detail-field">
                <span className="lbl">Full name</span>
                <input
                  value={draft.name}
                  onChange={(e) => setDraft({ ...draft, name: e.target.value })}
                />
              </div>
              <div className="detail-field">
                <span className="lbl">Job title</span>
                <input
                  value={draft.title || ''}
                  onChange={(e) => setDraft({ ...draft, title: e.target.value })}
                />
              </div>
              <div className="detail-field" style={{ gridColumn: '1 / -1' }}>
                <span className="lbl">Email address (login)</span>
                <input
                  value={draft.email}
                  onChange={(e) => setDraft({ ...draft, email: e.target.value })}
                  className="mono"
                />
                <button
                  type="button"
                  onClick={() => onResendInvite && onResendInvite()}
                  style={{
                    marginTop: 8,
                    alignSelf: 'flex-start',
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: 6,
                    padding: '5px 10px',
                    fontSize: 11.5,
                    border: '1px solid var(--border)',
                    background: 'var(--surface)',
                    borderRadius: 4,
                    cursor: 'pointer',
                    color: 'var(--ink-2)',
                  }}
                >
                  <Icon name="mail" size={11}/>
                  {user.status === 'invited' ? 'Resend invite link' : 'Send password reset link'}
                </button>
              </div>
              <div className="detail-field">
                <span className="lbl">Account created</span>
                <div className="val">{draft.createdDate}</div>
              </div>
              <div className="detail-field">
                <span className="lbl">Last sign-in</span>
                <div className="val">{draft.lastLogin || '— never —'}</div>
              </div>
            </div>
          </div>

          <div className="detail-section">
            <h4>Role</h4>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              <button
                className={`role-card ${draft.role === 'admin' ? 'on' : ''}`}
                onClick={() => setDraft({ ...draft, role: 'admin' })}
                disabled={isSelf && draft.role === 'admin'}
              >
                <div style={{ fontWeight: 600, marginBottom: 3 }}>Admin</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>All access · manages settings</div>
              </button>
              <button
                className={`role-card ${draft.role === 'leadership' ? 'on' : ''}`}
                onClick={() => setDraft({ ...draft, role: 'leadership' })}
              >
                <div style={{ fontWeight: 600, marginBottom: 3 }}>Leadership</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>All showrooms · no settings changes</div>
              </button>
              <button
                className={`role-card ${draft.role === 'manager' ? 'on' : ''}`}
                onClick={() => setDraft({ ...draft, role: 'manager', manages: draft.manages || [] })}
              >
                <div style={{ fontWeight: 600, marginBottom: 3 }}>Showroom Manager</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>Full access to allocated showrooms</div>
              </button>
              <button
                className={`role-card ${draft.role === 'sales_designer' ? 'on' : ''}`}
                onClick={() => setDraft({ ...draft, role: 'sales_designer' })}
              >
                <div style={{ fontWeight: 600, marginBottom: 3 }}>Sales Designer</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>Own contacts &amp; quotes only</div>
              </button>
            </div>
            {isSelf && draft.role === 'admin' && (
              <div style={{ marginTop: 8, fontSize: 11.5, color: 'var(--warn)' }}>
                <Icon name="alert" size={11}/> You can't downgrade your own admin role.
              </div>
            )}
          </div>

          {draft.role === 'manager' && (
            <div className="detail-section">
              <h4>Manages ({(draft.manages || []).length} of {showrooms.length} showrooms)</h4>
              <div className="showroom-grid">
                {showrooms.map(s => {
                  const checked = (draft.manages || []).includes(s.id);
                  return (
                    <div
                      key={s.id}
                      className={`sh-pick ${checked ? 'on' : ''}`}
                      onClick={() => {
                        const m = draft.manages || [];
                        const next = checked ? m.filter(x => x !== s.id) : [...m, s.id];
                        setDraft({ ...draft, manages: next });
                      }}
                    >
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span className={`checkbox ${checked ? 'on' : ''}`}>
                          {checked && <Icon name="check" size={10} color="white"/>}
                        </span>
                        <span className={`ss-tab-dot ${s.id}`}></span>
                        <span style={{ fontWeight: 500 }}>{s.name}</span>
                        <span style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{s.state}</span>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {draft.role === 'sales_designer' && (
            <div className="detail-section">
              <h4>Showroom access ({(draft.works || []).length} assigned)</h4>
              <div className="showroom-grid">
                {showrooms.map(s => {
                  const checked = (draft.works || []).includes(s.id);
                  const isHome = draft.home === s.id;
                  return (
                    <div
                      key={s.id}
                      className={`sh-pick ${checked ? 'on' : ''}`}
                      onClick={() => toggleShowroom(s.id)}
                    >
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span className={`checkbox ${checked ? 'on' : ''}`}>
                          {checked && <Icon name="check" size={10} color="white"/>}
                        </span>
                        <span className={`ss-tab-dot ${s.id}`}></span>
                        <span style={{ fontWeight: 500 }}>{s.name}</span>
                        <span style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{s.state}</span>
                      </div>
                      {checked && (
                        <button
                          className={`home-btn ${isHome ? 'on' : ''}`}
                          onClick={(e) => { e.stopPropagation(); setDraft({ ...draft, home: s.id }); }}
                          title="Set as home showroom"
                        >
                          <Icon name="home" size={11}/>
                          {isHome ? 'Home' : 'Set as home'}
                        </button>
                      )}
                    </div>
                  );
                })}
              </div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 8 }}>
                The home showroom is the one selected by default when this user signs in. Sales Designers must have at least one showroom assigned.
              </div>
            </div>
          )}

          <div className="detail-section">
            <h4>Account status</h4>
            <div className="detail-grid">
              <button
                className={`btn ${draft.status === 'active' ? 'primary' : ''}`}
                onClick={() => setDraft({ ...draft, status: 'active' })}
                disabled={isSelf}
              >
                <Icon name="check" size={12}/> Active
              </button>
              <button
                className={`btn ${draft.status === 'disabled' ? '' : ''}`}
                onClick={() => setDraft({ ...draft, status: 'disabled' })}
                disabled={isSelf}
                style={draft.status === 'disabled' ? { background: 'var(--lost)', color: 'white', borderColor: 'var(--lost)' } : null}
              >
                Disable account
              </button>
            </div>
            {isSelf && (
              <div style={{ marginTop: 8, fontSize: 11.5, color: 'var(--warn)' }}>
                <Icon name="alert" size={11}/> You can't disable your own account.
              </div>
            )}
          </div>
        </div>

        <div style={{ padding: '14px 22px', borderTop: '1px solid var(--border)', display: 'flex', gap: 8, background: 'var(--surface-2)' }}>
          <button className="btn" onClick={onClose}>Cancel</button>
          {!isSelf && (
            <button
              className="btn"
              onClick={() => { if (confirm('Remove this user? They will lose access immediately.')) onDelete(); }}
              style={{ color: 'var(--lost)', borderColor: 'var(--lost-soft)' }}
            >
              Remove user
            </button>
          )}
          <button className="btn primary" style={{ marginLeft: 'auto' }} onClick={save}>
            Save changes
          </button>
        </div>
      </div>
    </div>
  );
}

function InviteModal({ showrooms, onClose, onInvite }) {
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [role, setRole] = React.useState('sales_designer');
  const [works, setWorks] = React.useState([]);
  const [manages, setManages] = React.useState([]);
  const [home, setHome] = React.useState(null);

  const toggleShowroom = (sid) => {
    setWorks(prev => {
      const next = prev.includes(sid) ? prev.filter(x => x !== sid) : [...prev, sid];
      if (!next.includes(home)) setHome(next[0] || null);
      return next;
    });
    if (!home) setHome(sid);
  };

  const valid = name.trim() && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) &&
    (role === 'admin' || role === 'leadership' || (role === 'manager' ? manages.length > 0 : works.length > 0));

  const send = () => {
    if (!valid) return;
    const allIds = showrooms.map(s => s.id);
    onInvite({
      name: name.trim(),
      email: email.trim().toLowerCase(),
      role,
      works: (role === 'admin' || role === 'leadership') ? allIds : (role === 'manager' ? manages : works),
      manages: role === 'manager' ? manages : undefined,
      home: (role === 'admin' || role === 'leadership') ? null : (home || works[0] || manages[0] || null),
      title: role === 'admin' ? 'Administrator' : role === 'leadership' ? 'Sales Manager' : role === 'manager' ? 'Showroom Manager' : 'Sales Consultant',
      status: 'invited',
      lastLogin: null,
      createdDate: new Date().toISOString().slice(0, 10),
    });
  };

  return (
    <div>
      <div className="detail-overlay" onClick={onClose}/>
      <div className="invite-modal">
        <div style={{ padding: '18px 22px 14px', borderBottom: '1px solid var(--border)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.02em' }}>Invite team member</div>
            <button className="detail-close" style={{ marginLeft: 'auto' }} onClick={onClose}>
              <Icon name="close" size={16}/>
            </button>
          </div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4 }}>
            They'll receive an email with a sign-in link. Access is enforced from this user record.
          </div>
        </div>

        <div style={{ padding: '18px 22px', maxHeight: '60vh', overflowY: 'auto' }}>
          <div className="detail-section">
            <h4>Identity</h4>
            <div className="detail-grid">
              <div className="detail-field">
                <span className="lbl">Full name</span>
                <input value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Mia Patel" autoFocus/>
              </div>
              <div className="detail-field">
                <span className="lbl">Email address</span>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="mia.patel@kitchensubuild.com.au"
                  className="mono"
                />
              </div>
            </div>
          </div>

          <div className="detail-section">
            <h4>Role</h4>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              <button className={`role-card ${role === 'admin' ? 'on' : ''}`} onClick={() => setRole('admin')}>
                <div style={{ fontWeight: 600, marginBottom: 3 }}>Admin</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>Full access · manages settings &amp; users</div>
              </button>
              <button className={`role-card ${role === 'leadership' ? 'on' : ''}`} onClick={() => setRole('leadership')}>
                <div style={{ fontWeight: 600, marginBottom: 3 }}>Leadership</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>All showrooms · analytics only</div>
              </button>
              <button className={`role-card ${role === 'manager' ? 'on' : ''}`} onClick={() => setRole('manager')}>
                <div style={{ fontWeight: 600, marginBottom: 3 }}>Showroom Manager</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>Full access to assigned showrooms</div>
              </button>
              <button className={`role-card ${role === 'sales_designer' ? 'on' : ''}`} onClick={() => setRole('sales_designer')}>
                <div style={{ fontWeight: 600, marginBottom: 3 }}>Sales Designer</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>Own contacts &amp; quotes only</div>
              </button>
            </div>
          </div>

          {(role === 'sales_designer' || role === 'manager') && (
            <div className="detail-section">
              <h4>
                {role === 'manager' ? 'Manages' : 'Showroom access'}
                {(role === 'manager' ? manages : works).length > 0 && ` (${(role === 'manager' ? manages : works).length} selected)`}
              </h4>
              <div className="showroom-grid">
                {showrooms.map(s => {
                  const list = role === 'manager' ? manages : works;
                  const setList = role === 'manager'
                    ? (fn) => setManages(fn)
                    : (fn) => { setWorks(fn); };
                  const checked = list.includes(s.id);
                  return (
                    <div
                      key={s.id}
                      className={`sh-pick ${checked ? 'on' : ''}`}
                      onClick={() => {
                        if (role === 'manager') {
                          setManages(prev => prev.includes(s.id) ? prev.filter(x => x !== s.id) : [...prev, s.id]);
                        } else {
                          toggleShowroom(s.id);
                        }
                      }}
                    >
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span className={`checkbox ${checked ? 'on' : ''}`}>
                          {checked && <Icon name="check" size={10} color="white"/>}
                        </span>
                        <span className={`ss-tab-dot ${s.id}`}></span>
                        <span style={{ fontWeight: 500 }}>{s.name}</span>
                        <span style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{s.state}</span>
                      </div>
                      {role === 'sales_designer' && checked && works.length > 1 && (
                        <button
                          className={`home-btn ${home === s.id ? 'on' : ''}`}
                          onClick={(e) => { e.stopPropagation(); setHome(s.id); }}
                        >
                          <Icon name="home" size={11}/>
                          {home === s.id ? 'Home' : 'Set as home'}
                        </button>
                      )}
                    </div>
                  );
                })}
              </div>
              {(role === 'manager' ? manages : works).length === 0 && (
                <div style={{ fontSize: 11.5, color: 'var(--warn)', marginTop: 6 }}>
                  <Icon name="alert" size={11}/> Select at least one showroom.
                </div>
              )}
            </div>
          )}
        </div>

        <div style={{ padding: '14px 22px', borderTop: '1px solid var(--border)', background: 'var(--surface-2)', display: 'flex', gap: 8 }}>
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!valid} onClick={send} style={!valid ? { opacity: 0.5, cursor: 'not-allowed' } : { marginLeft: 'auto' }}>
            <Icon name="mail" size={12}/> Send invite
          </button>
        </div>
      </div>
    </div>
  );
}

// Role × Section access matrix — admin-editable authorisation control
function AccessMatrix({ accessMatrix, onSetAccess, currentUser }) {
  const SECTIONS = window.ACCESS_SECTIONS || [];
  const ROLES = window.ACCESS_ROLES || [];
  const LOCKED = window.ACCESS_ADMIN_LOCKED || [];
  const isAdmin = currentUser.role === 'admin' || currentUser.superAdmin;
  const groups = [...new Set(SECTIONS.map(s => s.group))];

  return (
    <div className="card" style={{ marginBottom: 16 }}>
      <div className="card-hd">
        <div>
          <div className="card-title">Section access by role</div>
          <div className="card-sub">Authorise which areas each role can open · enforced across the app{isAdmin ? '' : ' · only an Admin can change this'}</div>
        </div>
        <span className="pill" style={{ background: 'var(--accent-soft)', color: 'var(--accent-ink)' }}><Icon name="lock" size={11}/> Access control</span>
      </div>
      <div className="tbl-wrap">
        <table className="tbl">
          <thead>
            <tr>
              <th style={{ minWidth: 200 }}>Section</th>
              {ROLES.map(r => (
                <th key={r.id} className="num-col" style={{ textAlign: 'center', minWidth: 120 }}>
                  <div style={{ fontWeight: 600 }}>{r.label}</div>
                  <div style={{ fontSize: 9.5, color: 'var(--ink-4)', textTransform: 'none', letterSpacing: 0, fontWeight: 400 }}>{r.desc}</div>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {groups.map(g => (
              <React.Fragment key={g}>
                <tr style={{ background: 'var(--surface-2)' }}>
                  <td colSpan={ROLES.length + 1} style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--ink-3)', fontWeight: 600 }}>{g}</td>
                </tr>
                {SECTIONS.filter(s => s.group === g).map(s => (
                  <tr key={s.id} style={{ cursor: 'default' }}>
                    <td style={{ fontWeight: 500 }}>{s.label}</td>
                    {ROLES.map(r => {
                      const on = !!(accessMatrix[r.id] && accessMatrix[r.id][s.id]);
                      const locked = r.id === 'admin' || (LOCKED.includes(s.id)); // admin always on; floor sections never editable for others
                      const editable = isAdmin && !locked;
                      return (
                        <td key={r.id} className="num-col" style={{ textAlign: 'center' }}>
                          <button
                            onClick={() => editable && onSetAccess(r.id, s.id, !on)}
                            title={locked ? (r.id === 'admin' ? 'Admin always has full access' : 'Restricted to Admin only') : (on ? 'Allowed — click to revoke' : 'Blocked — click to allow')}
                            disabled={!editable}
                            style={{
                              width: 26, height: 26, borderRadius: 6, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                              border: '1px solid ' + (on ? 'var(--won)' : 'var(--border)'),
                              background: on ? 'var(--won-soft)' : 'var(--surface)',
                              color: on ? 'oklch(0.4 0.1 155)' : 'var(--ink-4)',
                              cursor: editable ? 'pointer' : 'not-allowed', opacity: locked && !on ? 0.45 : 1,
                            }}
                          >
                            <Icon name={on ? 'check' : 'close'} size={13}/>
                          </button>
                        </td>
                      );
                    })}
                  </tr>
                ))}
              </React.Fragment>
            ))}
          </tbody>
        </table>
      </div>
      <div style={{ padding: '10px 18px', borderTop: '1px solid var(--border)', fontSize: 11, color: 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 6 }}>
        <Icon name="alert" size={12}/> Admin keeps full access. Team &amp; Access, Workspace, Manage Showrooms and Data Import are locked to Admin for security. Changes apply immediately to the sidebar and block direct navigation.
      </div>
    </div>
  );
}

window.Admin = Admin;
window.AccessMatrix = AccessMatrix;