// Users.jsx — Admin User Management
function UsersPage() {
  const [search, setSearch] = React.useState('');
  const [catFilter, setCatFilter] = React.useState('All');
  const [showAdd, setShowAdd] = React.useState(false);

  const filtered = USERS.filter(u =>
    (catFilter === 'All' || userCategory(u) === catFilter) &&
    (u.name.toLowerCase().includes(search.toLowerCase()) || u.email.toLowerCase().includes(search.toLowerCase()))
  );

  // Group filtered users into the tidy categories, preserving category order.
  const grouped = USER_CATEGORIES
    .map(cat => ({ cat, rows: filtered.filter(u => userCategory(u) === cat) }))
    .filter(g => g.rows.length > 0);

  const roleColor = {
    Admin: '#7C3AED', Operation: '#2563EB', Operator: '#F59E0B',
    Rigger: '#0891B2', Mechanic: '#DC2626', Finance: '#059669', Management: '#0B1F3A',
  };
  const catColor = {
    'Super Admin': '#7C3AED', 'Management': '#0B1F3A', 'Account and Finance': '#059669',
    'Dispatch': '#0EA5E9', 'Mechanic': '#DC2626',
    'Operator': '#F59E0B', 'Rigger': '#0891B2',
  };
  const statusBadge = (s) => s === 'On Job' ? 'orange' : s === 'Standby' ? 'gray' : 'green';

  return (
    <div className="content">
      <div className="card">
        <div className="card__head" style={{justifyContent: 'space-between'}}>
          <div>
            <div className="card__title">Team Members</div>
            <div style={{fontSize: 13, color: 'var(--color-grey-500)', marginTop: 2}}>{USERS.length} staff across {USER_CATEGORIES.length} categories</div>
          </div>
          <button className="btn btn--primary" onClick={() => setShowAdd(true)}>
            <Plus size={16}/> Add User
          </button>
        </div>

        <div style={{display: 'flex', gap: 12, marginBottom: 16, flexWrap: 'wrap'}}>
          <div style={{position: 'relative', flex: '1 1 280px', minWidth: 240}}>
            <Search size={16} style={{position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)'}}/>
            <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search by name or email..." style={{paddingLeft: 38, width: '100%'}}/>
          </div>
          <select value={catFilter} onChange={(e) => setCatFilter(e.target.value)} style={{minWidth: 180}}>
            <option>All</option>
            {USER_CATEGORIES.map(c => <option key={c}>{c}</option>)}
          </select>
        </div>

        <div style={{border: '1px solid var(--border-default)', borderRadius: 8, overflow: 'hidden'}}>
          <table style={{width: '100%', borderCollapse: 'collapse', fontSize: 13}}>
            <thead style={{background: 'var(--color-grey-50)', textAlign: 'left'}}>
              <tr>
                <th style={{padding: '10px 14px', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--color-grey-500)'}}>Name</th>
                <th style={{padding: '10px 14px', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--color-grey-500)'}}>Role</th>
                <th style={{padding: '10px 14px', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--color-grey-500)'}}>Email</th>
                <th style={{padding: '10px 14px', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--color-grey-500)'}}>Phone</th>
                <th style={{padding: '10px 14px', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--color-grey-500)'}}>Status</th>
                <th style={{padding: '10px 14px', fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--color-grey-500)'}}>Last Active</th>
                <th style={{padding: '10px 14px'}}></th>
              </tr>
            </thead>
            <tbody>
              {grouped.map(g => (
                <React.Fragment key={g.cat}>
                  <tr>
                    <td colSpan={7} style={{padding: '10px 14px', background: 'var(--color-navy)'}}>
                      <div style={{display: 'flex', alignItems: 'center', gap: 8}}>
                        <span style={{width: 8, height: 8, borderRadius: '50%', background: catColor[g.cat] || 'white'}}/>
                        <span style={{fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'white'}}>{g.cat}</span>
                        <span style={{fontSize: 11, fontWeight: 700, color: 'rgba(255,255,255,0.55)'}}>· {g.rows.length}</span>
                      </div>
                    </td>
                  </tr>
                  {g.rows.map(u => {
                    const initials = u.name === 'N/A' ? '—' : u.name.replace(/\(.*?\)/g, '').trim().split(/\s+/).map(p => p[0]).slice(0, 2).join('');
                    return (
                      <tr key={u.id} style={{borderTop: '1px solid var(--border-default)'}}>
                        <td style={{padding: '12px 14px'}}>
                          <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
                            <div style={{width: 32, height: 32, borderRadius: '50%', background: u.status === 'Standby' ? 'var(--color-grey-300)' : 'var(--color-navy)', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700}}>{initials}</div>
                            <span style={{fontWeight: 600, color: 'var(--color-navy)'}}>{u.name}</span>
                          </div>
                        </td>
                        <td style={{padding: '12px 14px'}}>
                          <span style={{display: 'inline-block', padding: '3px 8px', borderRadius: 4, fontSize: 11, fontWeight: 700, color: 'white', background: roleColor[u.role]}}>{u.role}</span>
                        </td>
                        <td style={{padding: '12px 14px', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--color-grey-700)'}}>{u.email}</td>
                        <td style={{padding: '12px 14px', color: 'var(--color-grey-700)'}}>{u.phone}</td>
                        <td style={{padding: '12px 14px'}}>
                          <span className={"badge badge--" + statusBadge(u.status)}>{u.status}</span>
                        </td>
                        <td style={{padding: '12px 14px', color: 'var(--color-grey-500)', fontSize: 12}}>{u.last}</td>
                        <td style={{padding: '12px 14px', textAlign: 'right'}}>
                          <button className="btn btn--ghost btn--sm" onClick={() => window.askAdminPassword('Edit user · ' + u.name, () => {})}><Edit size={14}/></button>
                        </td>
                      </tr>
                    );
                  })}
                </React.Fragment>
              ))}
              {grouped.length === 0 ? (
                <tr><td colSpan={7} style={{padding: '32px 14px', textAlign: 'center', color: 'var(--color-grey-500)'}}>No team members match your search.</td></tr>
              ) : null}
            </tbody>
          </table>
        </div>
      </div>

      {showAdd ? (
        <div className="install-modal" onClick={() => setShowAdd(false)}>
          <div className="install-modal__card" onClick={(e) => e.stopPropagation()} style={{maxWidth: 520}}>
            <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20}}>
              <div style={{fontWeight: 700, fontSize: 18, color: 'var(--color-navy)'}}>Add User</div>
              <button className="install-banner__close" onClick={() => setShowAdd(false)}><X size={18}/></button>
            </div>
            <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 12}}>
              <div className="field"><label>Full name</label><input placeholder="e.g. Lim Wei Ming"/></div>
              <div className="field"><label>Role</label><select>{ROLES.map(r => <option key={r}>{r}</option>)}</select></div>
              <div className="field" style={{gridColumn: '1 / -1'}}><label>Email</label><input type="email" placeholder="user@powleecrane.com"/></div>
              <div className="field"><label>Phone</label><input placeholder="+60 ..."/></div>
              <div className="field"><label>Initial password</label><input type="password" placeholder="Auto-generated · sent to email"/></div>
            </div>
            <div style={{padding: 12, background: 'var(--color-grey-50)', borderRadius: 8, fontSize: 12, color: 'var(--color-grey-700)', marginBottom: 16}}>
              The new user receives a password-setup link by email. Their permissions are determined by the role you select — see <strong>Role Permissions</strong> for the full matrix.
            </div>
            <div style={{display: 'flex', gap: 8, justifyContent: 'flex-end'}}>
              <button className="btn btn--ghost" onClick={() => setShowAdd(false)}>Cancel</button>
              <button className="btn btn--primary" onClick={() => setShowAdd(false)}><Plus size={14}/> Create User</button>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}

Object.assign(window, { UsersPage });
