// Team dashboard — manage recruiting teammates (allowlist).

function TeamManagement({ useLive, adminEmail }) {
  const [teammates, setTeammates] = React.useState([]);
  const [loading, setLoading] = React.useState(!!useLive);
  const [email, setEmail] = React.useState('');
  const [role, setRole] = React.useState('recruiter');
  const [adding, setAdding] = React.useState(false);
  const [error, setError] = React.useState('');
  const [notice, setNotice] = React.useState('');

  const load = React.useCallback(async () => {
    if (!useLive) {
      setTeammates([
        { email: 'hr@wewire.com', role: 'admin', created_at: new Date().toISOString() },
        { email: 'recruiting@wewire.com', role: 'recruiter', created_at: new Date().toISOString() },
      ]);
      setLoading(false);
      return;
    }
    try {
      const rows = await WWAdmin.fetchTeammates();
      setTeammates(rows);
    } catch (err) {
      setError(err.message || 'Could not load team.');
    } finally {
      setLoading(false);
    }
  }, [useLive]);

  React.useEffect(() => { load(); }, [load]);

  const handleAdd = async (e) => {
    e?.preventDefault();
    setError('');
    setNotice('');
    if (!useLive) {
      setError('Connect Supabase to add teammates.');
      return;
    }
    setAdding(true);
    try {
      await WWAdmin.addTeammate(email, role);
      setEmail('');
      setNotice(`${email.trim()} added. They can now sign up on the login page with this email.`);
      await load();
    } catch (err) {
      setError(err.message || 'Could not add teammate.');
    } finally {
      setAdding(false);
    }
  };

  const handleRemove = async (row) => {
    if (row.email.toLowerCase() === (adminEmail || '').toLowerCase()) {
      setError('You cannot remove your own account.');
      return;
    }
    if (!confirm(`Remove ${row.email} from the team? They will lose dashboard access.`)) return;
    setError('');
    setNotice('');
    try {
      await WWAdmin.removeTeammate(row.email);
      setNotice(`${row.email} removed.`);
      await load();
    } catch (err) {
      setError(err.message || 'Could not remove teammate.');
    }
  };

  return (
    <div style={{ padding: '30px 36px 48px' }}>
      <Eyebrow>People</Eyebrow>
      <h1 style={{ fontFamily: DISP, fontWeight: 600, fontSize: 34, letterSpacing: '-0.02em', margin: '8px 0 6px' }}>Team</h1>
      <p style={{ fontSize: 15, color: T.muted, lineHeight: 1.55, maxWidth: 560, marginBottom: 24 }}>
        Add work emails here before teammates sign up. New members use the dashboard sign-up page with the email you add.
      </p>

      {error && (
        <Card pad={14} style={{ marginBottom: 16, background: T.redSoft, border: 'none' }}>
          <div style={{ fontSize: 13, color: T.red, lineHeight: 1.45 }}>{error}</div>
        </Card>
      )}
      {notice && (
        <Card pad={14} style={{ marginBottom: 16, background: T.greenSoft, border: 'none' }}>
          <div style={{ fontSize: 13, color: T.green, lineHeight: 1.45 }}>{notice}</div>
        </Card>
      )}

      <Card pad={22} style={{ marginBottom: 20 }}>
        <Eyebrow style={{ marginBottom: 14 }}>Add teammate</Eyebrow>
        <form onSubmit={handleAdd} style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'flex-end' }}>
          <label style={{ flex: '1 1 220px' }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: T.muted, marginBottom: 7 }}>Work email</div>
            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required placeholder="colleague@wewire.com"
              style={{ width: '100%', height: 44, borderRadius: 12, border: `1px solid ${T.lineStrong}`, padding: '0 14px',
                fontFamily: FONT, fontSize: 15, boxSizing: 'border-box' }} />
          </label>
          <label style={{ flex: '0 0 160px' }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: T.muted, marginBottom: 7 }}>Role</div>
            <select value={role} onChange={(e) => setRole(e.target.value)}
              style={{ width: '100%', height: 44, borderRadius: 12, border: `1px solid ${T.lineStrong}`, padding: '0 12px',
                fontFamily: FONT, fontSize: 15, background: T.white }}>
              <option value="recruiter">Recruiter</option>
              <option value="admin">Admin</option>
            </select>
          </label>
          <Btn variant="primary" type="submit" icon="user" disabled={adding || !email.trim()}>
            {adding ? 'Adding…' : 'Add to team'}
          </Btn>
        </form>
      </Card>

      <Card pad={0} style={{ overflow: 'hidden' }}>
        <div style={{ padding: '18px 22px', borderBottom: `1px solid ${T.line}`, display: 'flex', justifyContent: 'space-between' }}>
          <Eyebrow>Allowlist ({teammates.length})</Eyebrow>
          {loading && <span style={{ fontSize: 13, color: T.muted }}>Loading…</span>}
        </div>
        {teammates.length === 0 && !loading ? (
          <div style={{ padding: 32, textAlign: 'center', color: T.muted, fontSize: 14 }}>No teammates yet.</div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ borderBottom: `1px solid ${T.line}`, background: T.panel }}>
                <th style={{ textAlign: 'left', padding: '12px 22px', fontSize: 12, color: T.muted }}>Email</th>
                <th style={{ textAlign: 'left', padding: '12px 16px', fontSize: 12, color: T.muted }}>Role</th>
                <th style={{ textAlign: 'left', padding: '12px 16px', fontSize: 12, color: T.muted }}>Added</th>
                <th style={{ width: 100 }} />
              </tr>
            </thead>
            <tbody>
              {teammates.map((row) => (
                <tr key={row.email} style={{ borderBottom: `1px solid ${T.line}` }}>
                  <td style={{ padding: '14px 22px', fontSize: 14.5, fontWeight: 600 }}>{row.email}</td>
                  <td style={{ padding: '14px 16px' }}>
                    <Badge status={row.role === 'admin' ? 'advancing' : 'in_review'} size="sm" />
                    <span style={{ marginLeft: 8, fontSize: 13, color: T.muted, textTransform: 'capitalize' }}>{row.role}</span>
                  </td>
                  <td style={{ padding: '14px 16px', fontSize: 13, color: T.muted }}>
                    {row.created_at ? new Date(row.created_at).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }) : '—'}
                  </td>
                  <td style={{ padding: '14px 16px', textAlign: 'right' }}>
                    <Btn variant="ghost" size="sm" onClick={() => handleRemove(row)}
                      disabled={row.email.toLowerCase() === (adminEmail || '').toLowerCase()}>
                      Remove
                    </Btn>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </Card>
    </div>
  );
}

Object.assign(window, { TeamManagement });
