// Users — unified directory: Admin, Staff, Suppliers, Customers (filterable)

const UsersPage = ({ openSupplier }) => {
  const { ME_ADMIN, STAFF, SUPPLIERS, CUSTOMERS, SAIF_COMPANIES } = window.SaifData;
  const [filter, setFilter] = React.useState('all');
  const [query, setQuery] = React.useState('');

  const coById = (id) => SAIF_COMPANIES.find(c => c.id === id);

  const adminRows = [ME_ADMIN].map(u => ({
    id: u.id, type: 'admin', name: u.name, initials: u.initials, tone: u.tone,
    title: u.role, org: coById(u.company)?.name, orgColor: coById(u.company)?.color,
    email: 'hessa@saifalkhyeli.ae', status: 'active',
  }));

  const staffRows = STAFF.map(u => ({
    id: u.id, type: 'staff', name: u.name, initials: u.initials, tone: u.tone,
    title: u.role, org: coById(u.company)?.name, orgColor: coById(u.company)?.color,
    email: `${u.name.split(' ')[0].toLowerCase()}@saifalkhyeli.ae`, status: 'active',
  }));

  const supplierRows = SUPPLIERS.map(s => ({
    id: s.id, type: 'supplier', name: s.contact, initials: null, tone: s.tone,
    title: 'Primary contact · ' + s.industry, org: s.name, orgColor: null,
    email: s.email, status: s.status,
    _supplierObj: s,
  }));

  const customerRows = CUSTOMERS.map(c => ({
    id: c.id, type: 'customer', name: c.contact, initials: null, tone: c.tone,
    title: 'Primary contact · ' + c.industry, org: c.name, orgColor: null,
    email: c.email, status: c.status,
  }));

  const all = [...adminRows, ...staffRows, ...supplierRows, ...customerRows];
  const counts = {
    all: all.length,
    admin: adminRows.length,
    staff: staffRows.length,
    supplier: supplierRows.length,
    customer: customerRows.length,
  };

  const q = query.trim().toLowerCase();
  const filtered = all.filter(u => {
    if (filter !== 'all' && u.type !== filter) return false;
    if (!q) return true;
    return (u.name || '').toLowerCase().includes(q)
        || (u.org || '').toLowerCase().includes(q)
        || (u.email || '').toLowerCase().includes(q);
  });

  const typeMeta = {
    admin:    { label: 'Admin',    badge: 'accent' },
    staff:    { label: 'Staff',    badge: 'blue'   },
    supplier: { label: 'Supplier', badge: 'amber'  },
    customer: { label: 'Customer', badge: 'green'  },
  };

  const statusBadgeKind = (s) => s === 'active' || s === 'approved' ? 'green' : s === 'pending' ? 'amber' : s === 'rejected' ? 'red' : 'grey';

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Users</h1>
          <p className="page-subtitle">Everyone in the portal — internal staff, admins, suppliers, and customers.</p>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="download" size={14}/> Export</button>
          <button className="btn btn-primary"><Icon name="plus" size={14}/> Add user</button>
        </div>
      </div>

      <div className="tabs" style={{ marginBottom: 14 }}>
        {[
          { id: 'all',      label: 'All' },
          { id: 'admin',    label: 'Admin' },
          { id: 'staff',    label: 'Staff' },
          { id: 'supplier', label: 'Suppliers' },
          { id: 'customer', label: 'Customers' },
        ].map(t => (
          <button key={t.id} className="tab" data-active={filter === t.id} onClick={() => setFilter(t.id)}>
            {t.label} <span className="tab-count">{counts[t.id]}</span>
          </button>
        ))}
      </div>

      <div style={{ marginBottom: 14, position: 'relative', maxWidth: 360 }}>
        <input
          className="form-control"
          placeholder="Search by name, organization, or email…"
          value={query}
          onChange={e => setQuery(e.target.value)}
          style={{ paddingLeft: 32 }}
        />
        <span style={{ position: 'absolute', left: 10, top: 9, color: 'var(--text-mute)' }}>
          <Icon name="search" size={13}/>
        </span>
      </div>

      <div className="card">
        <table className="tbl users-tbl">
          <thead>
            <tr>
              <th>Name</th>
              <th>Type</th>
              <th>Title / Role</th>
              <th>Organization</th>
              <th>Email</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(u => {
              const meta = typeMeta[u.type];
              const clickable = u.type === 'supplier';
              return (
                <tr
                  key={`${u.type}-${u.id}`}
                  onClick={clickable ? () => openSupplier(u.id) : undefined}
                  style={{ cursor: clickable ? 'pointer' : 'default' }}
                >
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <Avatar name={u.name} initials={u.initials} size="sm" tone={u.tone}/>
                      <span style={{ fontWeight: 600, color: 'var(--ink)' }}>{u.name}</span>
                    </div>
                  </td>
                  <td><Badge kind={meta.badge}>{meta.label}</Badge></td>
                  <td className="text-sm" style={{ color: 'var(--text)' }}>{u.title}</td>
                  <td>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12 }}>
                      {u.orgColor && <span className="company-dot" style={{ background: u.orgColor, width: 7, height: 7, borderRadius: '50%' }}></span>}
                      {u.org}
                    </span>
                  </td>
                  <td className="text-mono text-xs text-mute">{u.email}</td>
                  <td><Badge kind={statusBadgeKind(u.status)}>{u.status}</Badge></td>
                </tr>
              );
            })}
            {filtered.length === 0 && (
              <tr><td colSpan="6" style={{ padding: 36, textAlign: 'center', color: 'var(--text-mute)' }}>No users match this filter.</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};

Object.assign(window, { UsersPage });
