// AdminViews — AdminOnboarding, AdminAllTickets
// Exports: AdminOnboarding, AdminAllTickets

// ── Progress Bar ─────────────────────────────────────────────────────────────
function ProgressBar({ value, color = '#1A5090' }) {
  return (
    <div style={{ height: 6, background: '#F1F5F9', borderRadius: 99, overflow: 'hidden' }}>
      <div style={{
        height: '100%', width: `${value}%`, background: color,
        borderRadius: 99, transition: 'width 0.6s cubic-bezier(.4,0,.2,1)',
      }} />
    </div>
  );
}

// ── Onboarding Management ────────────────────────────────────────────────────
function AdminOnboarding({ onNewTicket }) {
  const { onboardingEmployees } = window.MOCK;
  const [selected, setSelected] = React.useState(null);
  const [employees, setEmployees] = React.useState(onboardingEmployees);

  function toggleStep(empId, stepIdx) {
    setEmployees(emps => emps.map(e => {
      if (e.id !== empId) return e;
      const steps = e.steps.map((s, i) => i === stepIdx ? { ...s, done: !s.done } : s);
      const progress = Math.round((steps.filter(s => s.done).length / steps.length) * 100);
      return { ...e, steps, progress };
    }));
  }

  const emp = selected ? employees.find(e => e.id === selected) : null;

  const progressColor = (pct) => pct >= 80 ? '#10B981' : pct >= 40 ? '#F59E0B' : '#D96228';

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 22 }}>
        <Btn icon="userplus" variant="primary" onClick={() => onNewTicket && onNewTicket('onboarding_issues')}>Raise Onboarding Concern</Btn>
      </div>

      {/* Summary cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginBottom: 22 }}>
        {[
          { label: 'Active Onboardings', value: employees.length, icon: 'users', color: '#1A5090', bg: '#E8EFF8' },
          { label: 'Starting This Week',  value: employees.filter(e => e.startDate.includes('May 21') || e.startDate.includes('May 26')).length, icon: 'clock', color: '#F59E0B', bg: '#FFFBEB' },
          { label: 'Fully Complete',      value: employees.filter(e => e.progress === 100).length, icon: 'check', color: '#10B981', bg: '#ECFDF5' },
        ].map(c => (
          <div key={c.label} style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', padding: '18px 20px', display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: c.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <IC name={c.icon} size={18} color={c.color} />
            </div>
            <div>
              <div style={{ fontSize: 26, fontWeight: 800, color: '#0F172A', lineHeight: 1 }}>{c.value}</div>
              <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 4 }}>{c.label}</div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: selected ? '1fr 340px' : '1fr', gap: 18, alignItems: 'start' }}>
        {/* Employee cards grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 14 }}>
          {employees.map(emp => {
            const isSelected = selected === emp.id;
            const pColor = progressColor(emp.progress);
            return (
              <div key={emp.id} onClick={() => setSelected(isSelected ? null : emp.id)} style={{
                background: '#fff', borderRadius: 12,
                border: `1.5px solid ${isSelected ? '#1A5090' : '#E2E8F0'}`,
                padding: '20px', cursor: 'pointer', transition: 'all 0.15s',
                boxShadow: isSelected ? '0 0 0 3px rgba(26,80,144,0.12)' : '0 1px 4px rgba(0,0,0,0.04)',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
                  <Avatar name={emp.name} initials={emp.name.split(' ').map(n => n[0]).join('')} size={40} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 14, color: '#0F172A', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{emp.name}</div>
                    <div style={{ fontSize: 12, color: '#64748B' }}>{emp.role}</div>
                  </div>
                  <div style={{
                    fontSize: 13, fontWeight: 800, color: pColor,
                    background: pColor + '18', padding: '4px 10px', borderRadius: 20,
                  }}>{emp.progress}%</div>
                </div>
                <ProgressBar value={emp.progress} color={pColor} />
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10 }}>
                  <span style={{ fontSize: 11, color: '#94A3B8' }}>
                    {emp.steps.filter(s => s.done).length}/{emp.steps.length} steps
                  </span>
                  <span style={{ fontSize: 11, color: '#94A3B8' }}>Starts {emp.startDate}</span>
                </div>
                <div style={{ marginTop: 10, fontSize: 11, color: '#64748B' }}>
                  Dept: <strong>{emp.department}</strong> · Mgr: <strong>{emp.manager.split(' ')[0]}</strong>
                </div>
              </div>
            );
          })}
        </div>

        {/* Checklist panel */}
        {emp && (
          <div style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', overflow: 'hidden', position: 'sticky', top: 0 }}>
            <div style={{ background: '#0F2540', padding: '18px 22px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <div style={{ color: '#fff', fontWeight: 800, fontSize: 15 }}>{emp.name}</div>
                <div style={{ color: 'rgba(255,255,255,0.5)', fontSize: 12, marginTop: 2 }}>{emp.role} · {emp.department}</div>
              </div>
              <button onClick={() => setSelected(null)} style={{
                background: 'rgba(255,255,255,0.1)', border: 'none', borderRadius: 8,
                padding: 7, cursor: 'pointer', color: '#fff', display: 'flex',
              }}>
                <IC name="x" size={14} color="#fff" />
              </button>
            </div>
            <div style={{ padding: '16px 20px', borderBottom: '1px solid #F1F5F9' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                <span style={{ fontSize: 12, fontWeight: 700, color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.07em' }}>Checklist Progress</span>
                <span style={{ fontSize: 13, fontWeight: 800, color: progressColor(emp.progress) }}>{emp.progress}%</span>
              </div>
              <ProgressBar value={emp.progress} color={progressColor(emp.progress)} />
            </div>
            <div style={{ padding: '10px 20px' }}>
              {emp.steps.map((step, i) => (
                <div key={i} onClick={() => toggleStep(emp.id, i)} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '12px 0', borderBottom: i < emp.steps.length - 1 ? '1px solid #F8FAFC' : 'none',
                  cursor: 'pointer', transition: 'opacity 0.1s',
                }}>
                  <div style={{
                    width: 22, height: 22, borderRadius: 6, flexShrink: 0,
                    background: step.done ? '#1A5090' : '#F1F5F9',
                    border: step.done ? 'none' : '2px solid #E2E8F0',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    transition: 'all 0.15s',
                  }}>
                    {step.done && <IC name="check" size={12} color="#fff" strokeWidth={2.5} />}
                  </div>
                  <span style={{
                    fontSize: 13.5, color: step.done ? '#94A3B8' : '#1E293B',
                    fontWeight: step.done ? 400 : 600,
                    textDecoration: step.done ? 'line-through' : 'none',
                    transition: 'all 0.15s',
                  }}>{step.label}</span>
                </div>
              ))}
            </div>
            <div style={{ padding: '14px 20px', borderTop: '1.5px solid #F1F5F9' }}>
              <Btn variant="primary" size="sm" style={{ width: '100%', justifyContent: 'center' }}
                onClick={() => onNewTicket && onNewTicket('onboarding_issues')}>
                Raise Issue Concern
              </Btn>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Admin All Tickets ────────────────────────────────────────────────────────
function AdminAllTickets({ tickets, onTicketClick, onNewTicket }) {
  const { categories } = window.MOCK;
  const [search, setSearch]     = React.useState('');
  const [filterCat, setFilterCat]     = React.useState('All');
  const [filterStatus, setFilterStatus] = React.useState('All');
  const [filterPri, setFilterPri]     = React.useState('All');

  const filtered = tickets.filter(t => {
    const q = search.toLowerCase();
    const matchSearch = !q || t.title.toLowerCase().includes(q) || t.id.toLowerCase().includes(q) || t.submittedBy.name.toLowerCase().includes(q);
    const matchCat    = filterCat    === 'All' || t.categoryId === filterCat;
    const matchStatus = filterStatus === 'All' || t.status     === filterStatus;
    const matchPri    = filterPri    === 'All' || t.priority   === filterPri;
    return matchSearch && matchCat && matchStatus && matchPri;
  });

  const totalOpen = tickets.filter(t => t.status === 'Open').length;
  const totalIP   = tickets.filter(t => t.status === 'In Progress').length;

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 22 }}>
        <div style={{ fontSize: 13, color: '#94A3B8' }}>
          {totalOpen} open · {totalIP} in progress · {tickets.length} total
        </div>
        <Btn icon="plus" variant="primary" onClick={onNewTicket}>New Concern</Btn>
      </div>

      {/* Filters */}
      <div style={{ display: 'flex', gap: 10, marginBottom: 18, flexWrap: 'wrap' }}>
        <div style={{ flex: 1, minWidth: 200, position: 'relative' }}>
          <IC name="search" size={15} color="#94A3B8" style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
          <input value={search} onChange={e => setSearch(e.target.value)}
            placeholder="Search by title, ID, or person..."
            style={{
              width: '100%', padding: '10px 14px 10px 36px', borderRadius: 8,
              border: '1.5px solid #E2E8F0', fontSize: 13, fontFamily: 'inherit',
              color: '#1E293B', background: '#fff', boxSizing: 'border-box', outline: 'none',
            }} />
        </div>
        {[
          { value: filterCat,    setter: setFilterCat,    opts: [['All', 'All Categories'], ...categories.filter(c => !c.adminOnly).map(c => [c.id, c.label])] },
          { value: filterStatus, setter: setFilterStatus, opts: [['All','All Statuses'],['Open','Open'],['In Progress','In Progress'],['Resolved','Resolved'],['Closed','Closed']] },
          { value: filterPri,    setter: setFilterPri,    opts: [['All','All Priorities'],['Urgent','Urgent'],['High','High'],['Medium','Medium'],['Low','Low']] },
        ].map((f, i) => (
          <select key={i} value={f.value} onChange={e => f.setter(e.target.value)} style={{
            padding: '10px 14px', borderRadius: 8, border: '1.5px solid #E2E8F0',
            fontSize: 13, fontFamily: 'inherit', color: '#374151', background: '#fff', cursor: 'pointer',
          }}>
            {f.opts.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
          </select>
        ))}
      </div>

      {/* Table */}
      <div style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', overflow: 'hidden' }}>
        <div style={{
          display: 'grid', gridTemplateColumns: '70px 1fr 110px 36px 58px 95px 70px',
          gap: 10, padding: '10px 20px', background: '#F8FAFC', borderBottom: '1.5px solid #E2E8F0',
        }}>
          {['ID', 'Title', 'Category', 'By', 'Priority', 'Status', 'Updated'].map(h => (
            <span key={h} style={{ fontSize: 10, fontWeight: 700, color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.06em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{h}</span>
          ))}
        </div>
        {filtered.length === 0 ? (
          <div style={{ padding: '48px', textAlign: 'center', color: '#94A3B8' }}>
            <IC name="inbox" size={36} color="#CBD5E1" style={{ display: 'block', margin: '0 auto 12px' }} />
            <div style={{ fontWeight: 600, color: '#CBD5E1' }}>No concerns match your filters</div>
          </div>
        ) : filtered.map((t, i) => {
          const cat = categories.find(c => c.id === t.categoryId);
          return (
            <div key={t.id} onClick={() => onTicketClick(t)}
              onMouseEnter={e => e.currentTarget.style.background = '#FAFBFF'}
              onMouseLeave={e => e.currentTarget.style.background = '#fff'}
              style={{
                display: 'grid', gridTemplateColumns: '70px 1fr 110px 36px 58px 95px 70px',
                alignItems: 'center', gap: 10, padding: '11px 20px',
                background: '#fff', cursor: 'pointer', borderBottom: i < filtered.length - 1 ? '1px solid #F1F5F9' : 'none',
                transition: 'background 0.1s',
              }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: '#94A3B8', fontFamily: 'monospace' }}>{t.id}</span>
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, color: '#1E293B', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.title}</div>
              </div>
              <span style={{ fontSize: 12, fontWeight: 600, color: cat?.color, background: cat?.bg, padding: '3px 9px', borderRadius: 20, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{cat?.label}</span>
              <div title={t.submittedBy.name}>
                <Avatar name={t.submittedBy.name} initials={t.submittedBy.initials} size={24} />
              </div>
              <div style={{ display: 'flex', alignItems: 'center' }}><PriorityBadge priority={t.priority} /></div>
              <div style={{ display: 'flex', alignItems: 'center' }}><StatusBadge status={t.status} /></div>
              <span style={{ fontSize: 11, color: '#64748B' }}>{t.updatedAt}</span>
            </div>
          );
        })}
      </div>
      <div style={{ marginTop: 12, fontSize: 12, color: '#94A3B8', textAlign: 'right' }}>
        Showing {filtered.length} of {tickets.length} concerns
      </div>
    </div>
  );
}

// ── Category Access Tab ───────────────────────────────────────────────────────
function CategoryAccessTab() {
  const DEPARTMENTS = ['HR', 'Finance', 'IT', 'Marketing', 'Operations', 'Management'];
  const { categories } = window.MOCK;
  const managedCats = categories.filter(c => !c.adminOnly);

  const [accessMap, setAccessMap] = React.useState({});
  const [saving, setSaving]       = React.useState(null);
  const [flash, setFlash]         = React.useState(null);
  const [loading, setLoading]     = React.useState(true);

  function authH() { return { Authorization: 'Bearer ' + (localStorage.getItem('syn_token') || '') }; }

  React.useEffect(() => {
    fetch('/api/category-access/all', { headers: authH() })
      .then(r => r.ok ? r.json() : {})
      .then(data => { setAccessMap(data); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  async function toggleDept(catId, dept) {
    const current = accessMap[catId] || [];
    const updated = current.includes(dept)
      ? current.filter(d => d !== dept)
      : [...current, dept];

    setAccessMap(m => ({ ...m, [catId]: updated }));
    setSaving(catId + dept);
    try {
      const res = await fetch(`/api/category-access/${catId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', ...authH() },
        body: JSON.stringify({ departments: updated }),
      });
      if (!res.ok) throw new Error('Failed');
      setFlash({ type: 'success', text: 'Access updated.' });
    } catch (e) {
      setFlash({ type: 'error', text: 'Failed to save.' });
      setAccessMap(m => ({ ...m, [catId]: current }));
    } finally {
      setSaving(null);
      setTimeout(() => setFlash(null), 3000);
    }
  }

  if (loading) return <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8' }}>Loading…</div>;

  return (
    <div>
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: '#0F172A' }}>Category Access Control</div>
        <div style={{ fontSize: 13, color: '#64748B', marginTop: 4 }}>
          Check which departments can view <strong>all</strong> concerns in each category. Users always see their own concerns regardless.
        </div>
      </div>

      {flash && (
        <div style={{
          padding: '10px 16px', borderRadius: 8, marginBottom: 16, fontSize: 13, fontWeight: 600,
          background: flash.type === 'success' ? '#ECFDF5' : '#FEF2F2',
          color:      flash.type === 'success' ? '#065F46' : '#B91C1C',
          border:     `1.5px solid ${flash.type === 'success' ? '#A7F3D0' : '#FECACA'}`,
        }}>{flash.text}</div>
      )}

      <div style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', overflow: 'hidden' }}>
        {/* Header row */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: `200px ${DEPARTMENTS.map(() => '1fr').join(' ')}`,
          gap: 8, padding: '10px 20px',
          background: '#F8FAFC', borderBottom: '1.5px solid #E2E8F0',
        }}>
          <span style={{ fontSize: 10, fontWeight: 700, color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Category</span>
          {DEPARTMENTS.map(d => (
            <span key={d} style={{ fontSize: 10, fontWeight: 700, color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.06em', textAlign: 'center' }}>{d}</span>
          ))}
        </div>

        {managedCats.map((cat, i) => {
          const depts = accessMap[cat.id] || [];
          return (
            <div key={cat.id} style={{
              display: 'grid',
              gridTemplateColumns: `200px ${DEPARTMENTS.map(() => '1fr').join(' ')}`,
              gap: 8, padding: '14px 20px', alignItems: 'center',
              borderBottom: i < managedCats.length - 1 ? '1px solid #F1F5F9' : 'none',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: cat.color, flexShrink: 0 }} />
                <span style={{ fontSize: 13, fontWeight: 600, color: '#1E293B' }}>{cat.label}</span>
              </div>
              {DEPARTMENTS.map(dept => {
                const checked = depts.includes(dept);
                const isSaving = saving === cat.id + dept;
                return (
                  <div key={dept} style={{ display: 'flex', justifyContent: 'center' }}>
                    <button
                      type="button"
                      onClick={() => toggleDept(cat.id, dept)}
                      disabled={isSaving}
                      style={{
                        width: 22, height: 22, borderRadius: 6, flexShrink: 0,
                        background: checked ? BRAND_NAVY : '#F1F5F9',
                        border: checked ? 'none' : '2px solid #E2E8F0',
                        cursor: isSaving ? 'wait' : 'pointer',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        transition: 'all 0.15s',
                      }}>
                      {checked && <IC name="check" size={12} color="#fff" strokeWidth={2.5} />}
                    </button>
                  </div>
                );
              })}
            </div>
          );
        })}
      </div>

      <div style={{ marginTop: 14, fontSize: 12, color: '#94A3B8' }}>
        Changes take effect immediately. Admin always has access to all categories.
      </div>
    </div>
  );
}

// ── Admin User Management ─────────────────────────────────────────────────────
function AdminUsers() {
  const [tab, setTab]           = React.useState('onboard');
  const [users, setUsers]       = React.useState([]);
  const [loading, setLoading]   = React.useState(true);
  const [apiError, setApiError] = React.useState(null);
  const [search, setSearch]     = React.useState('');

  const DEPARTMENTS = ['HR', 'Finance', 'IT', 'Marketing', 'Operations', 'Management'];
  const [form, setForm]           = React.useState({ name: '', email: '', department: '', role: 'user' });
  const [formError, setFormError] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);
  const [flash, setFlash]         = React.useState(null);
  const [confirmUser, setConfirmUser]   = React.useState(null);
  const [deleteUser, setDeleteUser]     = React.useState(null);
  const [promoteTarget, setPromoteTarget] = React.useState('');
  const [promoting, setPromoting]         = React.useState(false);

  function authH() { return { Authorization: 'Bearer ' + (localStorage.getItem('syn_token') || '') }; }

  async function fetchUsers() {
    setLoading(true); setApiError(null);
    try {
      const res = await fetch('/api/users', { headers: authH() });
      if (!res.ok) throw new Error('Status ' + res.status);
      setUsers(await res.json());
    } catch (e) { setApiError(e.message); }
    finally { setLoading(false); }
  }
  React.useEffect(() => { fetchUsers(); }, []);

  function showFlash(type, text) { setFlash({ type, text }); setTimeout(() => setFlash(null), 6000); }

  function isValidEmail(email) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim()); }

  function fmtDate(val) {
    if (!val) return '—';
    try { return new Date(val).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }); }
    catch { return val; }
  }

  async function handleAdd(e) {
    e.preventDefault();
    setFormError(null);
    const name  = form.name.trim();
    const email = form.email.trim().toLowerCase();
    if (!name)  { setFormError('Full name is required.'); return; }
    if (!isValidEmail(email)) { setFormError('Please enter a valid email address.'); return; }
    if (users.some(u => u.email.toLowerCase() === email)) { setFormError('This Gmail address is already registered.'); return; }
    setSubmitting(true);
    try {
      const res  = await fetch('/api/users/onboard', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...authH() },
        body: JSON.stringify({ name, email, role: 'user', department: '' }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to add member');
      showFlash('success', `${name} added successfully! Temporary password: ${data.tempPassword}`);
      setForm({ name: '', email: '', department: '', role: 'user' });
      fetchUsers();
    } catch (e) { setFormError(e.message); }
    finally { setSubmitting(false); }
  }

  async function doDelete(user) {
    setDeleteUser(null);
    try {
      const res = await fetch(`/api/users/${user.id}`, { method: 'DELETE', headers: authH() });
      if (!res.ok) throw new Error((await res.json()).error || 'Failed');
      showFlash('success', `${user.name} has been permanently deleted.`);
      fetchUsers();
    } catch (e) { showFlash('error', e.message); }
  }

  async function doResetPassword(user) {
    if (!window.confirm(`Reset password for ${user.name}? A new temporary password will be sent to ${user.email}.`)) return;
    try {
      const res  = await fetch(`/api/users/${user.id}/reset-password`, { method: 'POST', headers: authH() });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed');
      showFlash('success', `Password reset for ${user.name}. Temp password: ${data.tempPassword} — email sent.`);
    } catch (e) { showFlash('error', e.message); }
  }

  async function doOffboard(user) {
    setConfirmUser(null);
    try {
      const res = await fetch(`/api/users/${user.id}/offboard`, { method: 'PUT', headers: authH() });
      if (!res.ok) throw new Error((await res.json()).error || 'Failed');
      showFlash('success', `${user.name}'s access has been removed.`);
      fetchUsers();
    } catch (e) { showFlash('error', e.message); }
  }

  async function doReactivate(user) {
    try {
      const res = await fetch(`/api/users/${user.id}/reactivate`, { method: 'PUT', headers: authH() });
      if (!res.ok) throw new Error('Failed');
      showFlash('success', `${user.name} has been reactivated.`);
      fetchUsers();
    } catch (e) { showFlash('error', e.message); }
  }

  async function handleChangeRole(userId, newRole, name) {
    try {
      const res = await fetch(`/api/users/${userId}/change-role`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', ...authH() },
        body: JSON.stringify({ role: newRole }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to update role');
      showFlash('success', data.message || `${name}'s role updated to ${newRole}.`);
      fetchUsers();
    } catch (e) { showFlash('error', e.message); }
  }

  async function handlePromote() {
    if (!promoteTarget) return;
    const target = users.find(u => String(u.id) === String(promoteTarget));
    if (!target) return;
    setPromoting(true);
    await handleChangeRole(promoteTarget, 'admin', target.name);
    setPromoteTarget('');
    setPromoting(false);
  }

  const activeUsers  = users.filter(u => u.status === 'active');
  const removedUsers = users.filter(u => u.status !== 'active');

  function filtered(list) {
    if (!search.trim()) return list;
    const q = search.toLowerCase();
    return list.filter(u => u.name.toLowerCase().includes(q) || u.email.toLowerCase().includes(q));
  }

  // ── Shared styles ──
  const INPUT = {
    width: '100%', padding: '10px 14px', borderRadius: 8, border: '1.5px solid #E2E8F0',
    fontSize: 14, fontFamily: 'inherit', color: '#1E293B', background: '#FAFBFF',
    outline: 'none', boxSizing: 'border-box', transition: 'border-color 0.15s',
  };
  const LABEL = {
    display: 'block', fontSize: 11, fontWeight: 700, color: '#374151',
    textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6,
  };
  function TH({ cols, headers }) {
    return (
      <div style={{ display: 'grid', gridTemplateColumns: cols, gap: 12, padding: '10px 20px', background: '#F8FAFC', borderBottom: '1.5px solid #E2E8F0' }}>
        {headers.map(h => <span key={h} style={{ fontSize: 10, fontWeight: 700, color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{h}</span>)}
      </div>
    );
  }

  const TABS = [
    { id: 'onboard',     label: 'Onboard New Member', dot: '#10B981' },
    { id: 'offboard',    label: 'Offboard Members',   dot: '#EF4444' },
    { id: 'coordinator', label: 'Coordinator',        dot: '#0EA5E9' },
    { id: 'access',      label: 'Category Access',    dot: '#8B5CF6' },
  ];

  // ── Offboard table (reused in offboard + members tabs) ──
  function MemberRow({ u, idx, showStatus, onOffboard, onReactivate, onResetPassword, onDelete }) {
    const isActive = u.status === 'active';
    const cols     = showStatus
      ? '40px 1fr 200px 120px 90px 200px'
      : '40px 1fr 200px 130px 200px';
    return (
      <div style={{
        display: 'grid', gridTemplateColumns: cols, alignItems: 'center', gap: 12,
        padding: '13px 20px', opacity: isActive ? 1 : 0.6,
      }}>
        <span style={{ fontSize: 12, fontWeight: 600, color: '#CBD5E1' }}>{idx + 1}</span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
          <Avatar name={u.name} size={30} />
          <span style={{ fontSize: 13, fontWeight: 600, color: '#1E293B', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', textDecoration: isActive ? 'none' : 'line-through' }}>{u.name}</span>
        </div>
        <span style={{ fontSize: 12, color: '#64748B', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{u.email}</span>
        <span style={{ fontSize: 12, color: '#64748B' }}>{fmtDate(u.created_at)}</span>
        {showStatus && (
          <span style={{
            fontSize: 12, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 5,
            color: isActive ? '#065F46' : '#B91C1C', background: isActive ? '#ECFDF5' : '#FEF2F2',
            padding: '3px 10px', borderRadius: 20, whiteSpace: 'nowrap', width: 'fit-content',
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: isActive ? '#10B981' : '#EF4444', display: 'inline-block' }} />
            {isActive ? 'Active' : 'Removed'}
          </span>
        )}
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {isActive && u.role === 'admin' && <span style={{ fontSize: 11, color: '#CBD5E1', fontStyle: 'italic' }}>Protected</span>}
          {isActive && u.role !== 'admin' && (
            <>
              <button onClick={() => onResetPassword(u)} style={{
                padding: '6px 12px', borderRadius: 7, border: '1.5px solid #E2E8F0', background: '#fff',
                color: '#1A5090', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer',
                display: 'inline-flex', alignItems: 'center', gap: 4,
              }}>
                <IC name="lock" size={11} color="#1A5090" /> Reset Pwd
              </button>
              <button onClick={() => onOffboard(u)} style={{
                padding: '6px 12px', borderRadius: 7, border: 'none', background: '#FEF2F2', color: '#EF4444',
                fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 4,
              }}>
                <IC name="x" size={11} color="#EF4444" strokeWidth={2.5} /> Remove
              </button>
            </>
          )}
          {!isActive && (
            <button onClick={() => onReactivate(u)} style={{
              padding: '6px 12px', borderRadius: 7, border: '1.5px solid #E2E8F0', background: '#fff',
              color: '#64748B', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer',
            }}>Reactivate</button>
          )}
          {u.role !== 'admin' && (
            <button onClick={() => onDelete(u)} style={{
              padding: '6px 12px', borderRadius: 7, border: 'none', background: '#FEF2F2',
              color: '#7F1D1D', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 4,
            }}>
              <IC name="userminus" size={11} color="#7F1D1D" /> Delete
            </button>
          )}
        </div>
      </div>
    );
  }

  function SectionTable({ label, dot, list, showStatus, emptyMsg }) {
    const rows = filtered(list);
    const cols = showStatus ? '40px 1fr 200px 120px 90px 200px' : '40px 1fr 200px 130px 200px';
    const hdrs = showStatus
      ? ['#', 'Name', 'Email', 'Date Added', 'Status', 'Actions']
      : ['#', 'Name', 'Email', 'Date Added', 'Actions'];
    return (
      <div style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', overflow: 'hidden', marginBottom: 24 }}>
        <div style={{ padding: '14px 20px', borderBottom: '1.5px solid #E2E8F0', background: '#F8FAFC', display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: dot, display: 'inline-block' }} />
          <span style={{ fontSize: 13, fontWeight: 700, color: '#0F172A' }}>{label}</span>
          <span style={{ fontSize: 12, color: '#94A3B8', marginLeft: 2 }}>({rows.length})</span>
        </div>
        <TH cols={cols} headers={hdrs} />
        {rows.length === 0
          ? <div style={{ padding: '40px', textAlign: 'center', color: '#94A3B8', fontSize: 14, fontWeight: 600 }}>{emptyMsg}</div>
          : rows.map((u, i) => (
            <div key={u.id} style={{ borderBottom: i < rows.length - 1 ? '1px solid #F1F5F9' : 'none' }}>
              <MemberRow u={u} idx={i} showStatus={showStatus} onOffboard={setConfirmUser} onReactivate={doReactivate} onResetPassword={doResetPassword} onDelete={setDeleteUser} />
            </div>
          ))
        }
      </div>
    );
  }

  return (
    <div>
      {/* ── Confirm Delete Modal ── */}
      {deleteUser && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(15,37,64,0.6)', zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
          <div style={{ background: '#fff', borderRadius: 16, width: '100%', maxWidth: 440, boxShadow: '0 32px 80px rgba(0,0,0,0.2)', overflow: 'hidden' }}>
            <div style={{ background: '#7F1D1D', padding: '22px 28px', display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 44, height: 44, borderRadius: '50%', background: 'rgba(255,255,255,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <IC name="userminus" size={22} color="#fff" />
              </div>
              <div style={{ fontSize: 17, fontWeight: 800, color: '#fff' }}>Permanently Delete User</div>
            </div>
            <div style={{ padding: '24px 28px' }}>
              <p style={{ margin: '0 0 14px', fontSize: 14, color: '#374151', lineHeight: 1.65 }}>
                Are you sure you want to permanently delete <strong>{deleteUser.name}</strong>?
              </p>
              <p style={{ margin: '0 0 6px', fontSize: 13, color: '#64748B' }}>{deleteUser.email}</p>
              <div style={{ margin: '18px 0 24px', background: '#FEF2F2', border: '1.5px solid #FECACA', borderRadius: 8, padding: '12px 14px', fontSize: 13, color: '#B91C1C', fontWeight: 600, lineHeight: 1.6 }}>
                ⚠️ This action is <u>irreversible</u>. The user and all their data will be permanently removed.
              </div>
              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                <Btn variant="ghost" onClick={() => setDeleteUser(null)}>Cancel</Btn>
                <button onClick={() => doDelete(deleteUser)} style={{
                  padding: '9px 20px', borderRadius: 8, border: 'none', background: '#7F1D1D', color: '#fff',
                  fontFamily: 'inherit', fontSize: 14, fontWeight: 700, cursor: 'pointer',
                }}>Yes, Delete Permanently</button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ── Confirm Remove Modal ── */}
      {confirmUser && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(15,37,64,0.6)', zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
          <div style={{ background: '#fff', borderRadius: 16, width: '100%', maxWidth: 440, boxShadow: '0 32px 80px rgba(0,0,0,0.2)', overflow: 'hidden' }}>
            <div style={{ background: '#FEF2F2', padding: '22px 28px', borderBottom: '1.5px solid #FECACA', display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 44, height: 44, borderRadius: '50%', background: '#FEE2E2', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <IC name="x" size={22} color="#EF4444" strokeWidth={2.5} />
              </div>
              <div style={{ fontSize: 17, fontWeight: 800, color: '#7F1D1D' }}>Confirm Removal</div>
            </div>
            <div style={{ padding: '24px 28px' }}>
              <p style={{ margin: '0 0 14px', fontSize: 14, color: '#374151', lineHeight: 1.65 }}>
                Are you sure you want to remove <strong>{confirmUser.name}</strong>'s access?
              </p>
              <p style={{ margin: '0 0 6px', fontSize: 13, color: '#64748B' }}>{confirmUser.email}</p>
              <div style={{ margin: '18px 0 24px', background: '#FEF2F2', border: '1.5px solid #FECACA', borderRadius: 8, padding: '10px 14px', fontSize: 13, color: '#B91C1C', fontWeight: 600 }}>
                This will immediately revoke their platform access.
              </div>
              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                <Btn variant="ghost" onClick={() => setConfirmUser(null)}>Cancel</Btn>
                <button onClick={() => doOffboard(confirmUser)} style={{
                  padding: '9px 20px', borderRadius: 8, border: 'none', background: '#EF4444', color: '#fff',
                  fontFamily: 'inherit', fontSize: 14, fontWeight: 700, cursor: 'pointer',
                }}>Yes, Remove Access</button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ── Stats ── */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14, marginBottom: 24 }}>
        {[
          { label: 'Active Members',   value: activeUsers.length,  icon: 'users',    bg: '#ECFDF5', ic: '#10B981' },
          { label: 'Removed Members',  value: removedUsers.length, icon: 'userplus', bg: '#FEF2F2', ic: '#EF4444' },
        ].map(c => (
          <div key={c.label} style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', padding: '20px 24px', display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{ width: 48, height: 48, borderRadius: 12, background: c.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <IC name={c.icon} size={22} color={c.ic} />
            </div>
            <div>
              <div style={{ fontSize: 32, fontWeight: 800, color: '#0F172A', lineHeight: 1 }}>{loading ? '—' : c.value}</div>
              <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 5, fontWeight: 600 }}>{c.label}</div>
            </div>
          </div>
        ))}
      </div>

      {/* ── Flash ── */}
      {flash && (
        <div style={{
          padding: '12px 18px', borderRadius: 10, marginBottom: 20, fontSize: 13, fontWeight: 600,
          display: 'flex', alignItems: 'flex-start', gap: 10,
          background: flash.type === 'success' ? '#ECFDF5' : '#FEF2F2',
          color:      flash.type === 'success' ? '#065F46' : '#B91C1C',
          border:     `1.5px solid ${flash.type === 'success' ? '#A7F3D0' : '#FECACA'}`,
        }}>
          <IC name={flash.type === 'success' ? 'check' : 'x'} size={16} color={flash.type === 'success' ? '#10B981' : '#EF4444'} strokeWidth={2.5} />
          <span style={{ flex: 1 }}>{flash.text}</span>
          <button onClick={() => setFlash(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, opacity: 0.5 }}>
            <IC name="x" size={14} color="currentColor" />
          </button>
        </div>
      )}

      {/* ── API error ── */}
      {apiError && (
        <div style={{ background: '#FFF7ED', border: '1.5px solid #FED7AA', borderRadius: 10, padding: '14px 20px', marginBottom: 20, color: '#92400E', fontSize: 13 }}>
          <strong>Backend not reachable:</strong> {apiError} — run <code>docker compose up -d</code> and refresh.
        </div>
      )}

      {/* ── Tabs ── */}
      <div style={{ display: 'flex', gap: 4, marginBottom: 24, background: '#F1F5F9', borderRadius: 12, padding: 4, width: 'fit-content', flexWrap: 'wrap' }}>
        {TABS.map(t => (
          <button key={t.id} onClick={() => { setTab(t.id); setSearch(''); setFormError(null); }} style={{
            padding: '9px 20px', borderRadius: 8, border: 'none', cursor: 'pointer',
            fontFamily: 'inherit', fontSize: 13, fontWeight: 700,
            background: tab === t.id ? '#fff' : 'transparent',
            color:      tab === t.id ? t.dot  : '#64748B',
            boxShadow:  tab === t.id ? '0 1px 6px rgba(0,0,0,0.1)' : 'none',
            transition: 'all 0.15s', display: 'flex', alignItems: 'center', gap: 7,
          }}>
            <span style={{ width: 7, height: 7, borderRadius: '50%', background: tab === t.id ? t.dot : '#CBD5E1', display: 'inline-block', transition: 'background 0.15s' }} />
            {t.label}
          </button>
        ))}
      </div>

      {/* ─────────────────────────────────────────────────────────────────────
          TAB: ONBOARD
      ───────────────────────────────────────────────────────────────────── */}
      {tab === 'onboard' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,560px) 1fr', gap: 24, alignItems: 'start' }}>
          {/* Form card */}
          <div style={{ background: '#fff', borderRadius: 14, border: '1.5px solid #E2E8F0', overflow: 'hidden' }}>
            <div style={{ background: 'linear-gradient(135deg, #0F2540 0%, #1A5090 100%)', padding: '22px 28px' }}>
              <div style={{ color: '#fff', fontWeight: 800, fontSize: 16 }}>Add New Member</div>
              <div style={{ color: 'rgba(255,255,255,0.5)', fontSize: 12, marginTop: 3 }}>Grant platform access to a new team member</div>
            </div>
            <form onSubmit={handleAdd} style={{ padding: '28px' }}>
              {formError && (
                <div style={{ background: '#FEF2F2', border: '1.5px solid #FECACA', borderRadius: 8, padding: '10px 14px', marginBottom: 20, fontSize: 13, color: '#B91C1C', fontWeight: 600, display: 'flex', gap: 8, alignItems: 'flex-start' }}>
                  <IC name="x" size={14} color="#EF4444" strokeWidth={2.5} style={{ marginTop: 1, flexShrink: 0 }} />
                  {formError}
                </div>
              )}
              <div style={{ marginBottom: 18 }}>
                <label style={LABEL}>Full Name <span style={{ color: '#D96228' }}>*</span></label>
                <input style={INPUT} placeholder="e.g. Priya Sharma" value={form.name}
                  onChange={e => { setForm(f => ({ ...f, name: e.target.value })); setFormError(null); }} />
              </div>
              <div style={{ marginBottom: 18 }}>
                <label style={LABEL}>Email Address <span style={{ color: '#D96228' }}>*</span></label>
                <input style={INPUT} type="email" placeholder="name@zentiti.com" value={form.email}
                  onChange={e => { setForm(f => ({ ...f, email: e.target.value })); setFormError(null); }} />
              </div>
              <button type="submit" disabled={submitting} style={{
                width: '100%', padding: '12px 20px', borderRadius: 9, border: 'none',
                background: submitting ? '#9CA3AF' : '#10B981', color: '#fff',
                fontFamily: 'inherit', fontSize: 14, fontWeight: 700, cursor: submitting ? 'not-allowed' : 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, transition: 'background 0.15s',
              }}>
                <IC name="userplus" size={16} color="#fff" />
                {submitting ? 'Adding…' : 'Add Member'}
              </button>
            </form>
          </div>

          {/* Hint card */}
          <div style={{ background: '#F8FAFC', borderRadius: 14, border: '1.5px solid #E2E8F0', padding: '24px 26px' }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#0F172A', marginBottom: 14 }}>What happens next?</div>
            {[
              { icon: 'check', color: '#10B981', bg: '#ECFDF5', text: 'Member is granted platform access immediately.' },
              { icon: 'send',  color: '#1A5090', bg: '#E8EFF8', text: 'A welcome email with login credentials is sent to their Gmail.' },
              { icon: 'users', color: '#D96228', bg: '#FEF0EB', text: 'They appear in the Active Members list right away.' },
            ].map((s, i) => (
              <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', marginBottom: i < 2 ? 14 : 0 }}>
                <div style={{ width: 32, height: 32, borderRadius: 8, background: s.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <IC name={s.icon} size={15} color={s.color} />
                </div>
                <p style={{ margin: '5px 0 0', fontSize: 13, color: '#475569', lineHeight: 1.5 }}>{s.text}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ─────────────────────────────────────────────────────────────────────
          TAB: OFFBOARD
      ───────────────────────────────────────────────────────────────────── */}
      {tab === 'offboard' && (
        <div>
          <div style={{ position: 'relative', marginBottom: 18, maxWidth: 400 }}>
            <IC name="search" size={15} color="#94A3B8" style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
            <input value={search} onChange={e => setSearch(e.target.value)}
              placeholder="Search by name or Gmail…"
              style={{ ...INPUT, paddingLeft: 38 }} />
          </div>
          {loading
            ? <div style={{ textAlign: 'center', padding: 60, color: '#94A3B8' }}>Loading members…</div>
            : <>
                <SectionTable
                  label="Active Members" dot="#10B981" list={activeUsers} showStatus={false}
                  emptyMsg={search ? 'No active members match your search.' : 'No active members.'}
                />
                {removedUsers.length > 0 && (
                  <SectionTable
                    label="Removed Members" dot="#EF4444" list={removedUsers} showStatus={false}
                    emptyMsg="No removed members match your search."
                  />
                )}
              </>
          }
        </div>
      )}

      {/* ─────────────────────────────────────────────────────────────────────
          TAB: COORDINATOR
      ───────────────────────────────────────────────────────────────────── */}
      {tab === 'coordinator' && (
        <CoordinatorTab users={users} loading={loading} onRefresh={fetchUsers} authH={authH} showFlash={showFlash} />
      )}

      {/* ─────────────────────────────────────────────────────────────────────
          TAB: CATEGORY ACCESS
      ───────────────────────────────────────────────────────────────────── */}
      {tab === 'access' && <CategoryAccessTab />}

      {/* Admin Users tab removed — now a top-level page: Admin Management */}
      {tab === '__removed_admins__' && (
        <div>
          {/* Current admins */}
          <div style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', overflow: 'hidden', marginBottom: 24 }}>
            <div style={{ padding: '14px 20px', background: '#FFFBEB', borderBottom: '1.5px solid #FDE68A', display: 'flex', alignItems: 'center', gap: 8 }}>
              <IC name="users" size={15} color="#D97706" />
              <span style={{ fontWeight: 700, color: '#0F172A', fontSize: 13 }}>Current Admins</span>
              <span style={{ fontSize: 12, color: '#94A3B8', marginLeft: 2 }}>
                ({users.filter(u => u.role === 'admin' && u.status === 'active').length})
              </span>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '40px 1fr 220px 130px 160px', gap: 12, padding: '10px 20px', background: '#F8FAFC', borderBottom: '1.5px solid #E2E8F0' }}>
              {['#', 'Name', 'Email', 'Added', 'Actions'].map(h => (
                <span key={h} style={{ fontSize: 10, fontWeight: 700, color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{h}</span>
              ))}
            </div>
            {loading ? (
              <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8' }}>Loading…</div>
            ) : (() => {
              const admins = users.filter(u => u.role === 'admin' && u.status === 'active');
              if (!admins.length) return <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8', fontSize: 14 }}>No admins found.</div>;
              return admins.map((u, i) => {
                const isCurrentUser = String(u.id) === String(window._synUser?.id) || u.email === window._synUser?.email;
                const isLastAdmin   = admins.length === 1;
                return (
                  <div key={u.id} style={{ display: 'grid', gridTemplateColumns: '40px 1fr 220px 130px 160px', gap: 12, padding: '13px 20px', borderBottom: i < admins.length - 1 ? '1px solid #F1F5F9' : 'none', alignItems: 'center' }}>
                    <span style={{ fontSize: 12, fontWeight: 600, color: '#CBD5E1' }}>{i + 1}</span>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                      <Avatar name={u.name} size={30} />
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 600, color: '#1E293B', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                          {u.name}
                          {isCurrentUser && <span style={{ fontSize: 10, color: '#D97706', fontWeight: 700, marginLeft: 7, background: '#FFFBEB', padding: '2px 7px', borderRadius: 20 }}>You</span>}
                        </div>
                        <div style={{ fontSize: 11, color: '#D97706', fontWeight: 600, marginTop: 1, display: 'flex', alignItems: 'center', gap: 4 }}>
                          <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#D97706', display: 'inline-block' }} /> Admin
                        </div>
                      </div>
                    </div>
                    <span style={{ fontSize: 12, color: '#64748B', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{u.email}</span>
                    <span style={{ fontSize: 12, color: '#64748B' }}>{fmtDate(u.created_at)}</span>
                    <div>
                      {isCurrentUser ? (
                        <span style={{ fontSize: 11, color: '#CBD5E1', fontStyle: 'italic' }}>That's you</span>
                      ) : isLastAdmin ? (
                        <span style={{ fontSize: 11, color: '#CBD5E1', fontStyle: 'italic' }}>Last admin</span>
                      ) : (
                        <button onClick={() => handleChangeRole(u.id, 'user', u.name)} style={{
                          padding: '6px 12px', borderRadius: 7, border: 'none', background: '#FEF3C7',
                          color: '#D97706', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer',
                          display: 'inline-flex', alignItems: 'center', gap: 4,
                        }}>
                          <IC name="userminus" size={11} color="#D97706" /> Revoke Admin
                        </button>
                      )}
                    </div>
                  </div>
                );
              });
            })()}
          </div>

          {/* Promote existing user */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 20, alignItems: 'start' }}>
            <div style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', overflow: 'hidden' }}>
              <div style={{ padding: '16px 20px', background: '#F8FAFC', borderBottom: '1.5px solid #E2E8F0' }}>
                <div style={{ fontWeight: 700, color: '#0F172A', fontSize: 14 }}>Promote Existing User to Admin</div>
                <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 2 }}>Select an active user to grant them full admin access</div>
              </div>
              <div style={{ padding: '24px 24px 28px' }}>
                <label style={LABEL}>Select User</label>
                <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                  <select style={{ ...INPUT, flex: 1 }} value={promoteTarget} onChange={e => setPromoteTarget(e.target.value)}>
                    <option value="">Choose an active user…</option>
                    {users.filter(u => u.role !== 'admin' && u.status === 'active').map(u => (
                      <option key={u.id} value={u.id}>{u.name} — {u.email}</option>
                    ))}
                  </select>
                  <button onClick={handlePromote} disabled={!promoteTarget || promoting} style={{
                    padding: '10px 20px', borderRadius: 8, border: 'none', whiteSpace: 'nowrap',
                    background: !promoteTarget || promoting ? '#E2E8F0' : '#D97706',
                    color: !promoteTarget || promoting ? '#94A3B8' : '#fff',
                    fontFamily: 'inherit', fontSize: 14, fontWeight: 700,
                    cursor: !promoteTarget || promoting ? 'not-allowed' : 'pointer',
                    display: 'flex', alignItems: 'center', gap: 8, transition: 'all 0.15s',
                  }}>
                    <IC name="userplus" size={15} color="currentColor" />
                    {promoting ? 'Promoting…' : 'Make Admin'}
                  </button>
                </div>
                <div style={{ marginTop: 16, background: '#FFFBEB', border: '1.5px solid #FDE68A', borderRadius: 8, padding: '10px 14px', fontSize: 12, color: '#92400E', display: 'flex', gap: 8, alignItems: 'flex-start' }}>
                  <IC name="alert" size={14} color="#D97706" style={{ flexShrink: 0, marginTop: 1 }} />
                  <span>Admins have full access to all tickets, users, and settings. Only promote trusted team members.</span>
                </div>
              </div>
            </div>
            <div style={{ background: '#F8FAFC', borderRadius: 12, border: '1.5px solid #E2E8F0', padding: '20px 22px' }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: '#0F172A', marginBottom: 12 }}>Admin Access Includes</div>
              {[
                { icon: 'ticket',  color: '#1A5090', bg: '#E8EFF8', text: 'View, manage, and delete all tickets' },
                { icon: 'users',   color: '#10B981', bg: '#ECFDF5', text: 'Add, remove, and manage all users' },
                { icon: 'chart',   color: '#8B5CF6', bg: '#F5F3FF', text: 'Full dashboard and analytics access' },
                { icon: 'settings',color: '#D97706', bg: '#FFFBEB', text: 'Department and category settings' },
              ].map((s, i) => (
                <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: i < 3 ? 10 : 0 }}>
                  <div style={{ width: 28, height: 28, borderRadius: 7, background: s.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <IC name={s.icon} size={13} color={s.color} />
                  </div>
                  <span style={{ fontSize: 12, color: '#475569' }}>{s.text}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

    </div>
  );
}

// ── Department Management ─────────────────────────────────────────────────────
function AdminTeams() {
  // Admin sections — HR covers both onboarding_issues + payroll + hr teams under one section.
  // Marketing sub-teams (Asura/Laura/Deepthi/Wade) are grouped under Marketing.
  const ADMIN_SECTIONS = [
    { id: 'technical_support', label: 'IT Support',       color: '#60A5FA', bg: '#EFF6FF', categoryIds: ['technical_support'] },
    { id: 'marketing',         label: 'Marketing',        color: '#A78BFA', bg: '#F5F3FF', categoryIds: ['marketing'] },
    { id: 'hr',                label: 'HR',               color: '#34D399', bg: '#ECFDF5', categoryIds: ['hr', 'onboarding_issues', 'payroll'] },
    { id: 'training_issues',   label: 'Training Issues',  color: '#FBBF24', bg: '#FEF3C7', categoryIds: ['training_issues'] },
    { id: 'others',            label: 'People Related Issues', color: '#94A3B8', bg: '#F1F5F9', categoryIds: ['others'] },
  ];

  const [teams, setTeams]               = React.useState([]);
  const [users, setUsers]               = React.useState([]);
  const [loading, setLoading]           = React.useState(true);
  const [flash, setFlash]               = React.useState(null);
  const [expandedDepts, setExpandedDepts] = React.useState(new Set());
  const [expandedTeams, setExpandedTeams] = React.useState(new Set());
  const [addingTeamFor, setAddingTeamFor]   = React.useState(null); // category_id
  const [addingMemberFor, setAddingMemberFor] = React.useState(null); // team id
  const [newTeam, setNewTeam]           = React.useState({ name: '', description: '' });
  const [newMember, setNewMember]       = React.useState({ name: '', email: '' });
  const [saving, setSaving]             = React.useState(false);

  function authH() { return { Authorization: 'Bearer ' + (localStorage.getItem('syn_token') || '') }; }
  function showFlash(type, text) { setFlash({ type, text }); setTimeout(() => setFlash(null), 4000); }

  async function fetchTeams() {
    try {
      const res = await fetch('/api/teams', { headers: authH() });
      const data = await res.json();
      setTeams(data);
    } catch (e) { showFlash('error', 'Failed to load teams'); }
    finally { setLoading(false); }
  }

  async function fetchUsers() {
    try {
      const res = await fetch('/api/users', { headers: authH() });
      if (res.ok) setUsers(await res.json());
    } catch (e) {}
  }

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

  function toggleDept(catId) {
    setExpandedDepts(prev => {
      const next = new Set(prev);
      if (next.has(catId)) next.delete(catId); else next.add(catId);
      return next;
    });
  }

  function toggleTeam(teamId) {
    setExpandedTeams(prev => {
      const next = new Set(prev);
      if (next.has(teamId)) next.delete(teamId); else next.add(teamId);
      return next;
    });
  }

  async function createTeam(e, catId) {
    e.preventDefault();
    if (!newTeam.name.trim()) return;
    setSaving(true);
    try {
      const res = await fetch('/api/teams', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...authH() },
        body: JSON.stringify({ name: newTeam.name, category_id: catId, description: newTeam.description }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed');
      setTeams(t => [...t, data]);
      setExpandedTeams(prev => new Set([...prev, data.id]));
      setNewTeam({ name: '', description: '' });
      setAddingTeamFor(null);
      showFlash('success', `Team "${data.name}" created.`);
    } catch (e) { showFlash('error', e.message); }
    finally { setSaving(false); }
  }

  async function deleteTeam(team) {
    if (!window.confirm(`Delete team "${team.name}" and all its members?`)) return;
    try {
      await fetch(`/api/teams/${team.id}`, { method: 'DELETE', headers: authH() });
      setTeams(t => t.filter(x => x.id !== team.id));
      showFlash('success', `Team "${team.name}" deleted.`);
    } catch (e) { showFlash('error', 'Failed to delete'); }
  }

  async function addMember(e, team) {
    e.preventDefault();
    if (!newMember.name.trim() || !newMember.email.trim()) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/teams/${team.id}/members`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...authH() },
        body: JSON.stringify(newMember),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed');
      setTeams(ts => ts.map(t => t.id === team.id ? { ...t, members: [...(t.members || []), data] } : t));
      setNewMember({ name: '', email: '' });
      setAddingMemberFor(null);
      showFlash('success', `${data.name} added to ${team.name}.`);
    } catch (e) { showFlash('error', e.message); }
    finally { setSaving(false); }
  }

  async function removeMember(team, memberId, memberName) {
    try {
      await fetch(`/api/teams/${team.id}/members/${memberId}`, { method: 'DELETE', headers: authH() });
      setTeams(ts => ts.map(t => t.id === team.id ? { ...t, members: t.members.filter(m => m.id !== memberId) } : t));
      showFlash('success', `${memberName} removed.`);
    } catch (e) { showFlash('error', 'Failed to remove'); }
  }

  const INPUT = {
    padding: '8px 12px', borderRadius: 8, border: '1.5px solid #E2E8F0',
    fontSize: 13, fontFamily: 'inherit', color: '#1E293B', background: '#FAFBFF',
    outline: 'none', boxSizing: 'border-box',
  };

  if (loading) return <div style={{ padding: 40, textAlign: 'center', color: '#94A3B8' }}>Loading…</div>;

  return (
    <div>
      {flash && (
        <div style={{
          padding: '10px 16px', borderRadius: 8, marginBottom: 16, fontSize: 13, fontWeight: 600,
          background: flash.type === 'success' ? '#ECFDF5' : '#FEF2F2',
          color:      flash.type === 'success' ? '#065F46' : '#B91C1C',
          border:     `1.5px solid ${flash.type === 'success' ? '#A7F3D0' : '#FECACA'}`,
        }}>{flash.text}</div>
      )}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {ADMIN_SECTIONS.map(cat => {
          const catTeams = teams.filter(t => cat.categoryIds.includes(t.category_id));
          const isDeptOpen = expandedDepts.has(cat.id);
          const privilegedCount = cat.id === 'others'
            ? users.filter(u => (u.role === 'admin' || u.role === 'coordinator') && u.status === 'active').length
            : 0;
          const totalMembers = catTeams.reduce((s, t) => s + (t.members || []).length, 0) + privilegedCount;

          return (
            <div key={cat.id} style={{ background: '#fff', borderRadius: 14, border: '1.5px solid #E2E8F0', overflow: 'hidden' }}>

              {/* ── Department header ── */}
              <div onClick={() => toggleDept(cat.id)} style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '14px 20px', cursor: 'pointer', userSelect: 'none',
                background: isDeptOpen ? cat.bg : '#fff',
                borderBottom: isDeptOpen ? `1.5px solid ${cat.color}30` : 'none',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span style={{ width: 13, height: 13, borderRadius: 4, background: cat.color, flexShrink: 0 }} />
                  <span style={{ fontWeight: 700, fontSize: 15, color: '#1E293B' }}>{cat.label}</span>
                  <span style={{ fontSize: 12, color: '#94A3B8' }}>
                    {catTeams.length} team{catTeams.length !== 1 ? 's' : ''} · {totalMembers} member{totalMembers !== 1 ? 's' : ''}
                  </span>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <button onClick={e => {
                    e.stopPropagation();
                    if (!isDeptOpen) toggleDept(cat.id);
                    setAddingTeamFor(addingTeamFor === cat.id ? null : cat.id);
                    setNewTeam({ name: '', description: '' });
                  }} style={{
                    background: cat.color, color: '#fff', border: 'none', borderRadius: 7,
                    padding: '5px 13px', fontSize: 12, fontWeight: 700, cursor: 'pointer',
                    fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 5,
                  }}>
                    <IC name="plus" size={12} color="#fff" strokeWidth={2.5} /> Add Team
                  </button>
                  <IC name={isDeptOpen ? 'chevron_d' : 'chevron_r'} size={16} color="#94A3B8" />
                </div>
              </div>

              {/* ── Department body ── */}
              {isDeptOpen && (
                <div style={{ padding: '14px 18px', display: 'flex', flexDirection: 'column', gap: 10 }}>

                  {/* Add team form */}
                  {addingTeamFor === cat.id && (
                    <form onSubmit={e => createTeam(e, cat.id)} style={{
                      background: cat.bg, border: `1.5px dashed ${cat.color}`, borderRadius: 10, padding: '14px 16px',
                    }}>
                      <div style={{ fontSize: 11, fontWeight: 700, color: cat.color, marginBottom: 10, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                        New Team — {cat.label}
                      </div>
                      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                        <input style={{ ...INPUT, flex: '1 1 160px' }} placeholder="Team name *" value={newTeam.name}
                          onChange={e => setNewTeam(f => ({ ...f, name: e.target.value }))} required autoFocus />
                        <input style={{ ...INPUT, flex: '2 1 220px' }} placeholder="Description (optional)" value={newTeam.description}
                          onChange={e => setNewTeam(f => ({ ...f, description: e.target.value }))} />
                        <button type="submit" disabled={saving} style={{
                          background: cat.color, color: '#fff', border: 'none', borderRadius: 8,
                          padding: '8px 18px', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
                        }}>{saving ? 'Creating…' : 'Create'}</button>
                        <button type="button" onClick={() => setAddingTeamFor(null)} style={{
                          background: '#F1F5F9', color: '#64748B', border: 'none', borderRadius: 8,
                          padding: '8px 14px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
                        }}>Cancel</button>
                      </div>
                    </form>
                  )}

                  {/* Empty state */}
                  {catTeams.length === 0 && addingTeamFor !== cat.id && (
                    <div style={{ textAlign: 'center', padding: '24px', color: '#CBD5E1', fontSize: 13 }}>
                      No teams yet — click "Add Team" to create one for {cat.label}.
                    </div>
                  )}

                  {/* ── Admins & Coordinators — auto-included for People Related Issues ── */}
                  {cat.id === 'others' && (() => {
                    const privileged = users.filter(u =>
                      (u.role === 'admin' || u.role === 'coordinator') && u.status === 'active'
                    );
                    if (privileged.length === 0) return null;
                    return (
                      <div style={{ border: '1.5px solid #FDE68A', borderRadius: 10, overflow: 'hidden' }}>
                        <div style={{
                          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                          padding: '11px 16px', background: '#FFFBEB',
                          borderBottom: '1.5px solid #FDE68A',
                        }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <IC name="lock" size={15} color="#D97706" strokeWidth={2} />
                            <span style={{ fontWeight: 700, fontSize: 13, color: '#1E293B' }}>Admins &amp; Coordinators</span>
                            <span style={{
                              fontSize: 11, background: '#FEF9C3', color: '#D97706',
                              borderRadius: 99, padding: '2px 9px', fontWeight: 600,
                            }}>
                              {privileged.length} member{privileged.length !== 1 ? 's' : ''}
                            </span>
                          </div>
                          <span style={{ fontSize: 11, color: '#92400E', fontStyle: 'italic' }}>Auto-included</span>
                        </div>
                        {privileged.map((u, i) => (
                          <div key={u.id} style={{
                            display: 'flex', alignItems: 'center', gap: 12, padding: '10px 16px',
                            borderBottom: i < privileged.length - 1 ? '1px solid #FEF9C3' : 'none',
                            background: '#fff',
                          }}>
                            <Avatar name={u.name} size={32} color={u.role === 'admin' ? '#D97706' : '#0EA5E9'} />
                            <div style={{ flex: 1, minWidth: 0 }}>
                              <div style={{ fontSize: 13, fontWeight: 700, color: '#1E293B' }}>{u.name}</div>
                              <div style={{ fontSize: 11, color: '#94A3B8' }}>{u.email}</div>
                            </div>
                            <span style={{
                              fontSize: 11, fontWeight: 700,
                              color: u.role === 'admin' ? '#D97706' : '#0EA5E9',
                              background: u.role === 'admin' ? '#FFFBEB' : '#F0F9FF',
                              border: `1px solid ${u.role === 'admin' ? '#FDE68A' : '#BAE6FD'}`,
                              padding: '3px 10px', borderRadius: 20, textTransform: 'capitalize',
                            }}>{u.role}</span>
                          </div>
                        ))}
                      </div>
                    );
                  })()}

                  {/* Team cards */}
                  {catTeams.map(team => {
                    const isTeamOpen = expandedTeams.has(team.id);
                    const isAddingMember = addingMemberFor === team.id;
                    const memberCount = (team.members || []).length;

                    return (
                      <div key={team.id} style={{ border: '1.5px solid #E2E8F0', borderRadius: 10, overflow: 'hidden' }}>

                        {/* Team row */}
                        <div onClick={() => toggleTeam(team.id)} style={{
                          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                          padding: '11px 16px', cursor: 'pointer', userSelect: 'none',
                          background: isTeamOpen ? '#F8FAFF' : '#fff',
                          borderBottom: isTeamOpen ? '1.5px solid #E2E8F0' : 'none',
                        }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <IC name="users" size={15} color={cat.color} strokeWidth={2} />
                            <span style={{ fontWeight: 700, fontSize: 13, color: '#1E293B' }}>{team.name}</span>
                            {team.description && <span style={{ fontSize: 11, color: '#94A3B8' }}>· {team.description}</span>}
                            <span style={{
                              fontSize: 11, background: `${cat.color}18`, color: cat.color,
                              borderRadius: 99, padding: '2px 9px', fontWeight: 600,
                            }}>
                              {memberCount} member{memberCount !== 1 ? 's' : ''}
                            </span>
                          </div>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                            <button onClick={e => {
                              e.stopPropagation();
                              if (addingMemberFor !== team.id) setNewMember({ name: '', email: '' });
                              setAddingMemberFor(isAddingMember ? null : team.id);
                              if (!isTeamOpen) toggleTeam(team.id);
                            }} style={{
                              background: '#EFF6FF', color: BRAND_NAVY, border: 'none', borderRadius: 6,
                              padding: '4px 11px', fontSize: 11, fontWeight: 700, cursor: 'pointer',
                              fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 4,
                            }}>
                              <IC name="userplus" size={11} color={BRAND_NAVY} strokeWidth={2.5} /> Add Member
                            </button>
                            <button onClick={e => { e.stopPropagation(); deleteTeam(team); }} style={{
                              background: '#FEF2F2', color: '#EF4444', border: 'none', borderRadius: 6,
                              padding: '4px 11px', fontSize: 11, fontWeight: 700, cursor: 'pointer',
                              fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 4,
                            }}>
                              <IC name="x" size={11} color="#EF4444" strokeWidth={2.5} /> Delete
                            </button>
                            <IC name={isTeamOpen ? 'chevron_d' : 'chevron_r'} size={14} color="#CBD5E1" />
                          </div>
                        </div>

                        {/* Team expanded body */}
                        {isTeamOpen && (
                          <div>
                            {/* Add member inline form */}
                            {isAddingMember && (
                              <form onSubmit={e => addMember(e, team)} style={{
                                padding: '12px 16px', background: '#F0F7FF', borderBottom: '1.5px solid #DBEAFE',
                              }}>
                                <div style={{ fontSize: 11, fontWeight: 700, color: BRAND_NAVY, marginBottom: 8, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                                  Add Member to {team.name}
                                </div>
                                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                                  <input style={{ ...INPUT, flex: '1 1 150px' }} placeholder="Full name *" value={newMember.name}
                                    onChange={e => setNewMember(f => ({ ...f, name: e.target.value }))} required autoFocus />
                                  <input style={{ ...INPUT, flex: '2 1 200px' }} type="email" placeholder="email@zentiti.com *" value={newMember.email}
                                    onChange={e => setNewMember(f => ({ ...f, email: e.target.value }))} required />
                                  <button type="submit" disabled={saving} style={{
                                    background: BRAND_NAVY, color: '#fff', border: 'none', borderRadius: 8,
                                    padding: '8px 16px', fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
                                  }}>{saving ? 'Adding…' : 'Add'}</button>
                                  <button type="button" onClick={() => setAddingMemberFor(null)} style={{
                                    background: '#F1F5F9', color: '#64748B', border: 'none', borderRadius: 8,
                                    padding: '8px 12px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
                                  }}>Cancel</button>
                                </div>
                              </form>
                            )}

                            {/* Members list */}
                            {memberCount === 0 ? (
                              <div style={{ padding: '20px', textAlign: 'center', color: '#CBD5E1', fontSize: 12 }}>
                                No members yet — click "Add Member" to add someone.
                              </div>
                            ) : (team.members || []).map((m, i) => (
                              <div key={m.id} style={{
                                display: 'flex', alignItems: 'center', gap: 12, padding: '10px 16px',
                                borderBottom: i < team.members.length - 1 ? '1px solid #F8FAFC' : 'none',
                                background: '#fff',
                              }}>
                                <Avatar name={m.name} size={32} color={cat.color} />
                                <div style={{ flex: 1, minWidth: 0 }}>
                                  <div style={{ fontSize: 13, fontWeight: 700, color: '#1E293B' }}>{m.name}</div>
                                  <div style={{ fontSize: 11, color: '#94A3B8' }}>{m.email}</div>
                                </div>
                                <button onClick={() => removeMember(team, m.id, m.name)} style={{
                                  background: '#FEF2F2', border: 'none', borderRadius: 6,
                                  padding: '4px 10px', cursor: 'pointer', color: '#EF4444',
                                  fontFamily: 'inherit', fontSize: 11, fontWeight: 700,
                                  display: 'flex', alignItems: 'center', gap: 4,
                                }}>
                                  <IC name="x" size={11} color="#EF4444" strokeWidth={2.5} /> Remove
                                </button>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── Admin Management Page ─────────────────────────────────────────────────────
function AdminManagement() {
  const [users,   setUsers]   = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [flash,   setFlash]   = React.useState(null);
  const [form,    setForm]    = React.useState({ name: '', email: '' });
  const [formError, setFormError] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);
  const [promoteTarget, setPromoteTarget] = React.useState('');
  const [promoting, setPromoting] = React.useState(false);
  const [grantMode, setGrantMode] = React.useState('new'); // 'new' | 'existing'

  function authH() { return { Authorization: 'Bearer ' + (localStorage.getItem('syn_token') || '') }; }
  function showFlash(type, text) { setFlash({ type, text }); setTimeout(() => setFlash(null), 6000); }
  function fmtDate(val) {
    if (!val) return '—';
    try { return new Date(val).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }); }
    catch { return String(val); }
  }

  async function fetchUsers() {
    setLoading(true);
    try {
      const res = await fetch('/api/users', { headers: authH() });
      if (!res.ok) throw new Error('Failed');
      setUsers(await res.json());
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  }
  React.useEffect(() => { fetchUsers(); }, []);

  async function handleAddAdmin(e) {
    e.preventDefault();
    setFormError(null);
    const name  = form.name.trim();
    const email = form.email.trim().toLowerCase();
    if (!name)  { setFormError('Full name is required.'); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { setFormError('Please enter a valid email.'); return; }
    if (users.some(u => u.email.toLowerCase() === email)) { setFormError('This email is already registered.'); return; }
    setSubmitting(true);
    try {
      const res  = await fetch('/api/users/onboard', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...authH() },
        body: JSON.stringify({ name, email, role: 'admin', department: 'Admin' }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to add admin');
      showFlash('success', `${name} added as Admin. Temporary password: ${data.tempPassword}`);
      setForm({ name: '', email: '' });
      fetchUsers();
    } catch (e) { setFormError(e.message); }
    finally { setSubmitting(false); }
  }

  async function handleChangeRole(userId, newRole, name) {
    try {
      const res  = await fetch(`/api/users/${userId}/change-role`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', ...authH() },
        body: JSON.stringify({ role: newRole }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed');
      showFlash('success', data.message || `${name}'s role updated.`);
      fetchUsers();
    } catch (e) { showFlash('error', e.message); }
  }

  async function handlePromote() {
    if (!promoteTarget) return;
    const target = users.find(u => String(u.id) === String(promoteTarget));
    if (!target) return;
    setPromoting(true);
    await handleChangeRole(promoteTarget, 'admin', target.name);
    setPromoteTarget('');
    setPromoting(false);
  }

  const admins   = users.filter(u => u.role === 'admin' && u.status === 'active');
  const nonAdmins = users.filter(u => u.role !== 'admin' && u.status === 'active');

  const INPUT = {
    width: '100%', padding: '10px 14px', borderRadius: 8, border: '1.5px solid #E2E8F0',
    fontSize: 14, fontFamily: 'inherit', color: '#1E293B', background: '#FAFBFF',
    outline: 'none', boxSizing: 'border-box', transition: 'border-color 0.15s',
  };
  const LABEL = {
    display: 'block', fontSize: 11, fontWeight: 700, color: '#374151',
    textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6,
  };

  return (
    <div>
      {/* Flash */}
      {flash && (
        <div style={{
          padding: '12px 18px', borderRadius: 10, marginBottom: 20, fontSize: 13, fontWeight: 600,
          display: 'flex', alignItems: 'flex-start', gap: 10,
          background: flash.type === 'success' ? '#ECFDF5' : '#FEF2F2',
          color:      flash.type === 'success' ? '#065F46' : '#B91C1C',
          border:     `1.5px solid ${flash.type === 'success' ? '#A7F3D0' : '#FECACA'}`,
        }}>
          <IC name={flash.type === 'success' ? 'check' : 'alert'} size={16} color={flash.type === 'success' ? '#10B981' : '#EF4444'} />
          <span style={{ flex: 1 }}>{flash.text}</span>
          <button onClick={() => setFlash(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, opacity: 0.5 }}>
            <IC name="x" size={14} color="currentColor" />
          </button>
        </div>
      )}

      {/* ── Stats row ── */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginBottom: 24 }}>
        {[
          { label: 'Active Admins',    value: admins.length,                                         icon: 'lock',    bg: '#FFFBEB', ic: '#D97706' },
          { label: 'Regular Users',    value: users.filter(u => u.role === 'user'   && u.status === 'active').length, icon: 'users',   bg: '#E8EFF8', ic: '#1A5090' },
          { label: 'Team Agents',      value: users.filter(u => u.role === 'agent'  && u.status === 'active').length, icon: 'megaphone', bg: '#F5F3FF', ic: '#8B5CF6' },
        ].map(c => (
          <div key={c.label} style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', padding: '18px 22px', display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 44, height: 44, borderRadius: 11, background: c.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <IC name={c.icon} size={20} color={c.ic} />
            </div>
            <div>
              <div style={{ fontSize: 30, fontWeight: 800, color: '#0F172A', lineHeight: 1 }}>{loading ? '—' : c.value}</div>
              <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 4, fontWeight: 600 }}>{c.label}</div>
            </div>
          </div>
        ))}
      </div>

      {/* ── Main layout: admins table left, grant access right ── */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 20, alignItems: 'start' }}>

        {/* Current admins table */}
        <div style={{ background: '#fff', borderRadius: 14, border: '1.5px solid #E2E8F0', overflow: 'hidden' }}>
          <div style={{ padding: '16px 22px', borderBottom: '1.5px solid #F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontWeight: 700, color: '#0F172A', fontSize: 15 }}>Current Admins</div>
              <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 2 }}>People with full platform access</div>
            </div>
            <span style={{
              fontSize: 12, fontWeight: 700, color: '#D97706',
              background: '#FFFBEB', border: '1.5px solid #FDE68A',
              padding: '4px 12px', borderRadius: 20,
            }}>{admins.length} admin{admins.length !== 1 ? 's' : ''}</span>
          </div>

          {/* Column headers */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 200px 110px 140px', gap: 12, padding: '9px 22px', background: '#F8FAFC', borderBottom: '1px solid #F1F5F9' }}>
            {['Name & Email', 'Added', 'Status', 'Action'].map(h => (
              <span key={h} style={{ fontSize: 10, fontWeight: 700, color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{h}</span>
            ))}
          </div>

          {loading ? (
            <div style={{ padding: 48, textAlign: 'center', color: '#94A3B8' }}>Loading…</div>
          ) : admins.length === 0 ? (
            <div style={{ padding: 48, textAlign: 'center', color: '#94A3B8', fontSize: 14 }}>No admins found.</div>
          ) : admins.map((u, i) => {
            const isMe        = u.email === window._synUser?.email;
            const isLastAdmin = admins.length === 1;
            return (
              <div key={u.id} style={{
                display: 'grid', gridTemplateColumns: '1fr 200px 110px 140px', gap: 12,
                padding: '14px 22px', alignItems: 'center',
                borderBottom: i < admins.length - 1 ? '1px solid #F8FAFC' : 'none',
                background: isMe ? '#FFFDF5' : '#fff',
              }}>
                {/* Name + email */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 }}>
                  <Avatar name={u.name} size={36} />
                  <div style={{ minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <span style={{ fontSize: 13, fontWeight: 700, color: '#1E293B', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{u.name}</span>
                      {isMe && (
                        <span style={{ fontSize: 10, fontWeight: 700, color: '#D97706', background: '#FFFBEB', padding: '1px 8px', borderRadius: 20, whiteSpace: 'nowrap' }}>You</span>
                      )}
                    </div>
                    <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{u.email}</div>
                  </div>
                </div>
                {/* Date */}
                <span style={{ fontSize: 12, color: '#64748B' }}>{fmtDate(u.created_at)}</span>
                {/* Status badge */}
                <span style={{
                  fontSize: 11, fontWeight: 700, color: '#D97706',
                  background: '#FFFBEB', border: '1.5px solid #FDE68A',
                  padding: '3px 10px', borderRadius: 20, display: 'inline-flex', alignItems: 'center', gap: 5, width: 'fit-content',
                }}>
                  <IC name="lock" size={10} color="#D97706" /> Admin
                </span>
                {/* Action */}
                <div>
                  {isMe ? (
                    <span style={{ fontSize: 11, color: '#CBD5E1', fontStyle: 'italic' }}>That's you</span>
                  ) : isLastAdmin ? (
                    <span style={{ fontSize: 11, color: '#CBD5E1', fontStyle: 'italic' }}>Last admin</span>
                  ) : (
                    <button onClick={() => handleChangeRole(u.id, 'user', u.name)} style={{
                      padding: '6px 12px', borderRadius: 7, border: '1.5px solid #FDE68A',
                      background: '#fff', color: '#B45309',
                      fontFamily: 'inherit', fontSize: 12, fontWeight: 600, cursor: 'pointer',
                      display: 'inline-flex', alignItems: 'center', gap: 5,
                      transition: 'all 0.15s',
                    }}
                      onMouseEnter={e => { e.currentTarget.style.background = '#FFFBEB'; }}
                      onMouseLeave={e => { e.currentTarget.style.background = '#fff'; }}>
                      <IC name="userminus" size={12} color="#B45309" /> Revoke
                    </button>
                  )}
                </div>
              </div>
            );
          })}
        </div>

        {/* Grant Admin Access — right panel */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

          {/* Mode toggle card */}
          <div style={{ background: '#fff', borderRadius: 14, border: '1.5px solid #E2E8F0', overflow: 'hidden' }}>
            {/* Header */}
            <div style={{ padding: '16px 20px', borderBottom: '1.5px solid #F1F5F9' }}>
              <div style={{ fontWeight: 700, color: '#0F172A', fontSize: 14 }}>Grant Admin Access</div>
              <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 2 }}>Add a new admin or promote an existing user</div>
            </div>

            {/* Toggle */}
            <div style={{ padding: '14px 20px 0', display: 'flex', gap: 8 }}>
              {[{ id: 'new', label: 'New User' }, { id: 'existing', label: 'Existing User' }].map(m => (
                <button key={m.id} onClick={() => { setGrantMode(m.id); setFormError(null); }} style={{
                  flex: 1, padding: '8px', borderRadius: 8, border: 'none', cursor: 'pointer',
                  fontFamily: 'inherit', fontSize: 13, fontWeight: 700, transition: 'all 0.15s',
                  background: grantMode === m.id ? '#D97706' : '#F1F5F9',
                  color:      grantMode === m.id ? '#fff'    : '#64748B',
                }}>
                  {m.label}
                </button>
              ))}
            </div>

            {/* Form */}
            <div style={{ padding: '18px 20px 20px' }}>
              {grantMode === 'new' ? (
                <form onSubmit={handleAddAdmin}>
                  {formError && (
                    <div style={{ background: '#FEF2F2', border: '1.5px solid #FECACA', borderRadius: 8, padding: '9px 12px', marginBottom: 14, fontSize: 12, color: '#B91C1C', fontWeight: 600, display: 'flex', gap: 7 }}>
                      <IC name="x" size={13} color="#EF4444" strokeWidth={2.5} style={{ flexShrink: 0, marginTop: 1 }} />
                      {formError}
                    </div>
                  )}
                  <div style={{ marginBottom: 12 }}>
                    <label style={LABEL}>Full Name <span style={{ color: '#D96228' }}>*</span></label>
                    <input style={INPUT} placeholder="e.g. Pradeep Kumar" value={form.name}
                      onChange={e => { setForm(f => ({ ...f, name: e.target.value })); setFormError(null); }} />
                  </div>
                  <div style={{ marginBottom: 16 }}>
                    <label style={LABEL}>Email Address <span style={{ color: '#D96228' }}>*</span></label>
                    <input style={INPUT} type="email" placeholder="admin@zentiti.com" value={form.email}
                      onChange={e => { setForm(f => ({ ...f, email: e.target.value })); setFormError(null); }} />
                  </div>
                  <button type="submit" disabled={submitting} style={{
                    width: '100%', padding: '11px', borderRadius: 9, border: 'none',
                    background: submitting ? '#9CA3AF' : '#D97706', color: '#fff',
                    fontFamily: 'inherit', fontSize: 14, fontWeight: 700, cursor: submitting ? 'not-allowed' : 'pointer',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                  }}>
                    <IC name="userplus" size={15} color="#fff" />
                    {submitting ? 'Adding…' : 'Create Admin Account'}
                  </button>
                </form>
              ) : (
                <div>
                  <div style={{ marginBottom: 14 }}>
                    <label style={LABEL}>Select User to Promote</label>
                    <select style={INPUT} value={promoteTarget} onChange={e => setPromoteTarget(e.target.value)}>
                      <option value="">Choose an active user…</option>
                      {nonAdmins.map(u => (
                        <option key={u.id} value={u.id}>{u.name} — {u.email}</option>
                      ))}
                    </select>
                  </div>
                  <button onClick={handlePromote} disabled={!promoteTarget || promoting} style={{
                    width: '100%', padding: '11px', borderRadius: 9, border: 'none',
                    background: !promoteTarget || promoting ? '#E2E8F0' : '#D97706',
                    color: !promoteTarget || promoting ? '#94A3B8' : '#fff',
                    fontFamily: 'inherit', fontSize: 14, fontWeight: 700,
                    cursor: !promoteTarget || promoting ? 'not-allowed' : 'pointer',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, transition: 'all 0.15s',
                  }}>
                    <IC name="userplus" size={15} color="currentColor" />
                    {promoting ? 'Promoting…' : 'Promote to Admin'}
                  </button>
                </div>
              )}
            </div>

            {/* Warning */}
            <div style={{ margin: '0 20px 18px', background: '#FFFBEB', border: '1.5px solid #FDE68A', borderRadius: 8, padding: '10px 12px', fontSize: 12, color: '#92400E', display: 'flex', gap: 7, alignItems: 'flex-start' }}>
              <IC name="alert" size={13} color="#D97706" style={{ flexShrink: 0, marginTop: 1 }} />
              <span>Admins have full access to all tickets, users and settings. Only grant access to trusted members.</span>
            </div>
          </div>

          {/* Access info card */}
          <div style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', padding: '18px 20px' }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: '#0F172A', marginBottom: 12, display: 'flex', alignItems: 'center', gap: 6 }}>
              <IC name="lock" size={13} color="#D97706" /> Admin Access Includes
            </div>
            {[
              { icon: 'ticket',    color: '#1A5090', bg: '#E8EFF8', text: 'View, manage & delete all tickets' },
              { icon: 'users',     color: '#10B981', bg: '#ECFDF5', text: 'Add, remove & manage all users' },
              { icon: 'chart',     color: '#8B5CF6', bg: '#F5F3FF', text: 'Full dashboard & export access' },
              { icon: 'settings',  color: '#D97706', bg: '#FFFBEB', text: 'Department & category settings' },
            ].map((s, i) => (
              <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: i < 3 ? 10 : 0 }}>
                <div style={{ width: 28, height: 28, borderRadius: 7, background: s.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <IC name={s.icon} size={13} color={s.color} />
                </div>
                <span style={{ fontSize: 12, color: '#475569', lineHeight: 1.4 }}>{s.text}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── All Members ───────────────────────────────────────────────────────────────
function AllMembers() {
  const [users, setUsers]             = React.useState([]);
  const [loading, setLoading]         = React.useState(true);
  const [search, setSearch]           = React.useState('');
  const [flash, setFlash]             = React.useState(null);
  const [confirmUser, setConfirmUser] = React.useState(null);
  const [deleteUser, setDeleteUser]   = React.useState(null);

  function authH() { return { Authorization: 'Bearer ' + (localStorage.getItem('syn_token') || '') }; }
  function showFlash(type, text) { setFlash({ type, text }); setTimeout(() => setFlash(null), 6000); }
  function fmtDate(val) {
    if (!val) return '—';
    try { return new Date(val).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }); }
    catch { return val; }
  }

  async function fetchUsers() {
    setLoading(true);
    try {
      const res = await fetch('/api/users', { headers: authH() });
      if (!res.ok) throw new Error('Status ' + res.status);
      setUsers(await res.json());
    } catch (e) { showFlash('error', 'Could not load users: ' + e.message); }
    finally { setLoading(false); }
  }
  React.useEffect(() => { fetchUsers(); }, []);

  async function doOffboard(user) {
    setConfirmUser(null);
    try {
      const res = await fetch(`/api/users/${user.id}/offboard`, { method: 'PUT', headers: authH() });
      if (!res.ok) throw new Error((await res.json()).error || 'Failed');
      showFlash('success', `${user.name}'s access has been removed.`);
      fetchUsers();
    } catch (e) { showFlash('error', e.message); }
  }

  async function doReactivate(user) {
    try {
      const res = await fetch(`/api/users/${user.id}/reactivate`, { method: 'PUT', headers: authH() });
      if (!res.ok) throw new Error('Failed');
      showFlash('success', `${user.name} has been reactivated.`);
      fetchUsers();
    } catch (e) { showFlash('error', e.message); }
  }

  async function doResetPassword(user) {
    if (!window.confirm(`Reset password for ${user.name}? A temporary password will be sent to ${user.email}.`)) return;
    try {
      const res  = await fetch(`/api/users/${user.id}/reset-password`, { method: 'POST', headers: authH() });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed');
      showFlash('success', `Password reset for ${user.name}. Temp: ${data.tempPassword} — email sent.`);
    } catch (e) { showFlash('error', e.message); }
  }

  async function doDelete(user) {
    setDeleteUser(null);
    try {
      const res = await fetch(`/api/users/${user.id}`, { method: 'DELETE', headers: authH() });
      if (!res.ok) throw new Error((await res.json()).error || 'Failed');
      showFlash('success', `${user.name} has been permanently deleted.`);
      fetchUsers();
    } catch (e) { showFlash('error', e.message); }
  }

  const ROLE_BADGE = {
    admin:       { label: 'Admin',       color: '#D97706', bg: '#FFFBEB', border: '#FDE68A' },
    coordinator: { label: 'Coordinator', color: '#0284C7', bg: '#E0F2FE', border: '#BAE6FD' },
    agent:       { label: 'Agent',       color: '#7C3AED', bg: '#F5F3FF', border: '#DDD6FE' },
    user:        { label: 'User',        color: '#1A5090', bg: '#E8EFF8', border: '#BFDBFE' },
  };

  const filtered = React.useMemo(() => {
    if (!search.trim()) return users;
    const q = search.toLowerCase();
    return users.filter(u => u.name.toLowerCase().includes(q) || u.email.toLowerCase().includes(q));
  }, [users, search]);

  const activeCount       = users.filter(u => u.status === 'active').length;
  const removedCount      = users.filter(u => u.status !== 'active').length;
  const adminCount        = users.filter(u => u.role === 'admin'       && u.status === 'active').length;
  const coordinatorCount  = users.filter(u => u.role === 'coordinator' && u.status === 'active').length;
  const agentCount        = users.filter(u => u.role === 'agent'       && u.status === 'active').length;
  const userCount         = users.filter(u => u.role === 'user'        && u.status === 'active').length;

  const COLS = '40px 1fr 220px 100px 110px 90px 1fr';
  const HDRS = ['#', 'Name', 'Email', 'Joined', 'Role', 'Status', 'Actions'];

  return (
    <div>
      {/* ── Delete confirm modal ── */}
      {deleteUser && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(15,37,64,0.6)', zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
          <div style={{ background: '#fff', borderRadius: 16, width: '100%', maxWidth: 440, boxShadow: '0 32px 80px rgba(0,0,0,0.2)', overflow: 'hidden' }}>
            <div style={{ background: '#7F1D1D', padding: '22px 28px', display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 44, height: 44, borderRadius: '50%', background: 'rgba(255,255,255,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <IC name="userminus" size={22} color="#fff" />
              </div>
              <div style={{ fontSize: 17, fontWeight: 800, color: '#fff' }}>Permanently Delete User</div>
            </div>
            <div style={{ padding: '24px 28px' }}>
              <p style={{ margin: '0 0 6px', fontSize: 14, color: '#374151', lineHeight: 1.65 }}>
                Are you sure you want to permanently delete <strong>{deleteUser.name}</strong>?
              </p>
              <p style={{ margin: '0 0 0', fontSize: 13, color: '#64748B' }}>{deleteUser.email}</p>
              <div style={{ margin: '18px 0 24px', background: '#FEF2F2', border: '1.5px solid #FECACA', borderRadius: 8, padding: '12px 14px', fontSize: 13, color: '#B91C1C', fontWeight: 600, lineHeight: 1.6 }}>
                ⚠️ This action is <u>irreversible</u>. The user and all their data will be permanently removed.
              </div>
              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                <button onClick={() => setDeleteUser(null)} style={{ padding: '9px 20px', borderRadius: 8, border: '1.5px solid #E2E8F0', background: '#fff', color: '#64748B', fontFamily: 'inherit', fontSize: 14, fontWeight: 600, cursor: 'pointer' }}>Cancel</button>
                <button onClick={() => doDelete(deleteUser)} style={{ padding: '9px 20px', borderRadius: 8, border: 'none', background: '#7F1D1D', color: '#fff', fontFamily: 'inherit', fontSize: 14, fontWeight: 700, cursor: 'pointer' }}>Yes, Delete Permanently</button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ── Offboard confirm modal ── */}
      {confirmUser && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(15,37,64,0.6)', zIndex: 2000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
          <div style={{ background: '#fff', borderRadius: 16, width: '100%', maxWidth: 440, boxShadow: '0 32px 80px rgba(0,0,0,0.2)', overflow: 'hidden' }}>
            <div style={{ background: '#FEF2F2', padding: '22px 28px', borderBottom: '1.5px solid #FECACA', display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 44, height: 44, borderRadius: '50%', background: '#FEE2E2', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <IC name="x" size={22} color="#EF4444" strokeWidth={2.5} />
              </div>
              <div style={{ fontSize: 17, fontWeight: 800, color: '#7F1D1D' }}>Confirm Removal</div>
            </div>
            <div style={{ padding: '24px 28px' }}>
              <p style={{ margin: '0 0 6px', fontSize: 14, color: '#374151', lineHeight: 1.65 }}>
                Remove <strong>{confirmUser.name}</strong>'s platform access?
              </p>
              <p style={{ margin: '0 0 0', fontSize: 13, color: '#64748B' }}>{confirmUser.email}</p>
              <div style={{ margin: '18px 0 24px', background: '#FEF2F2', border: '1.5px solid #FECACA', borderRadius: 8, padding: '10px 14px', fontSize: 13, color: '#B91C1C', fontWeight: 600 }}>
                This will immediately revoke their platform access. You can reactivate them later.
              </div>
              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                <button onClick={() => setConfirmUser(null)} style={{ padding: '9px 20px', borderRadius: 8, border: '1.5px solid #E2E8F0', background: '#fff', color: '#64748B', fontFamily: 'inherit', fontSize: 14, fontWeight: 600, cursor: 'pointer' }}>Cancel</button>
                <button onClick={() => doOffboard(confirmUser)} style={{ padding: '9px 20px', borderRadius: 8, border: 'none', background: '#EF4444', color: '#fff', fontFamily: 'inherit', fontSize: 14, fontWeight: 700, cursor: 'pointer' }}>Yes, Remove Access</button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ── Flash ── */}
      {flash && (
        <div style={{
          padding: '12px 18px', borderRadius: 10, marginBottom: 20, fontSize: 13, fontWeight: 600,
          display: 'flex', alignItems: 'flex-start', gap: 10,
          background: flash.type === 'success' ? '#ECFDF5' : '#FEF2F2',
          color:      flash.type === 'success' ? '#065F46' : '#B91C1C',
          border:     `1.5px solid ${flash.type === 'success' ? '#A7F3D0' : '#FECACA'}`,
        }}>
          <IC name={flash.type === 'success' ? 'check' : 'alert'} size={16} color={flash.type === 'success' ? '#10B981' : '#EF4444'} />
          <span style={{ flex: 1 }}>{flash.text}</span>
          <button onClick={() => setFlash(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, opacity: 0.5 }}>
            <IC name="x" size={14} color="currentColor" />
          </button>
        </div>
      )}

      {/* ── Stats ── */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, marginBottom: 24 }}>
        {[
          { label: 'Total Users',     value: users.length,   icon: 'users',   bg: '#E8EFF8', ic: '#1A5090' },
          { label: 'Active',          value: activeCount,    icon: 'check',   bg: '#ECFDF5', ic: '#10B981' },
          { label: 'Removed',         value: removedCount,   icon: 'x',       bg: '#FEF2F2', ic: '#EF4444' },
          { label: 'Admins',          value: adminCount,       icon: 'lock',      bg: '#FFFBEB', ic: '#D97706' },
          { label: 'Coordinators',    value: coordinatorCount, icon: 'users',     bg: '#E0F2FE', ic: '#0284C7' },
          { label: 'Agents',          value: agentCount,       icon: 'megaphone', bg: '#F5F3FF', ic: '#8B5CF6' },
        ].map(c => (
          <div key={c.label} style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 38, height: 38, borderRadius: 10, background: c.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <IC name={c.icon} size={17} color={c.ic} />
            </div>
            <div>
              <div style={{ fontSize: 24, fontWeight: 800, color: '#0F172A', lineHeight: 1 }}>{loading ? '—' : c.value}</div>
              <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 3, fontWeight: 600 }}>{c.label}</div>
            </div>
          </div>
        ))}
      </div>

      {/* ── Search + table ── */}
      <div style={{ background: '#fff', borderRadius: 14, border: '1.5px solid #E2E8F0', overflow: 'hidden' }}>
        {/* Table header bar */}
        <div style={{ padding: '14px 20px', borderBottom: '1.5px solid #F1F5F9', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
          <div>
            <span style={{ fontWeight: 700, fontSize: 14, color: '#0F172A' }}>All Members</span>
            <span style={{ fontSize: 12, color: '#94A3B8', marginLeft: 8 }}>{loading ? '…' : `${filtered.length} shown`}</span>
          </div>
          <div style={{ position: 'relative', width: 280 }}>
            <IC name="search" size={14} color="#94A3B8" style={{ position: 'absolute', left: 11, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }} />
            <input value={search} onChange={e => setSearch(e.target.value)}
              placeholder="Search name or email…"
              style={{
                width: '100%', padding: '8px 12px 8px 34px', borderRadius: 8,
                border: '1.5px solid #E2E8F0', fontSize: 13, fontFamily: 'inherit',
                color: '#1E293B', background: '#FAFBFF', outline: 'none', boxSizing: 'border-box',
              }} />
          </div>
        </div>

        {/* Column headers */}
        <div style={{ display: 'grid', gridTemplateColumns: COLS, gap: 12, padding: '9px 20px', background: '#F8FAFC', borderBottom: '1px solid #F1F5F9' }}>
          {HDRS.map(h => <span key={h} style={{ fontSize: 10, fontWeight: 700, color: '#94A3B8', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{h}</span>)}
        </div>

        {/* Rows */}
        {loading ? (
          <div style={{ padding: 60, textAlign: 'center', color: '#94A3B8' }}>Loading members…</div>
        ) : filtered.length === 0 ? (
          <div style={{ padding: 60, textAlign: 'center', color: '#94A3B8', fontSize: 14 }}>
            {search ? 'No members match your search.' : 'No members yet.'}
          </div>
        ) : filtered.map((u, i) => {
          const isActive = u.status === 'active';
          const badge    = ROLE_BADGE[u.role] || ROLE_BADGE.user;
          const isAdmin  = u.role === 'admin';
          return (
            <div key={u.id} style={{
              display: 'grid', gridTemplateColumns: COLS, gap: 12, padding: '13px 20px',
              alignItems: 'center', opacity: isActive ? 1 : 0.6,
              borderBottom: i < filtered.length - 1 ? '1px solid #F8FAFC' : 'none',
              background: i % 2 === 0 ? '#fff' : '#FAFBFF',
            }}>
              <span style={{ fontSize: 12, fontWeight: 600, color: '#CBD5E1' }}>{i + 1}</span>

              {/* Name + avatar */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                <Avatar name={u.name} size={32} />
                <span style={{
                  fontSize: 13, fontWeight: 700, color: '#1E293B',
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                  textDecoration: isActive ? 'none' : 'line-through',
                }}>{u.name}</span>
              </div>

              {/* Email */}
              <span style={{ fontSize: 12, color: '#64748B', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{u.email}</span>

              {/* Joined date */}
              <span style={{ fontSize: 12, color: '#64748B' }}>{fmtDate(u.created_at)}</span>

              {/* Role badge */}
              <span style={{
                fontSize: 11, fontWeight: 700, color: badge.color,
                background: badge.bg, border: `1.5px solid ${badge.border}`,
                padding: '3px 10px', borderRadius: 20, display: 'inline-block', width: 'fit-content',
              }}>{badge.label}</span>

              {/* Status badge */}
              <span style={{
                fontSize: 11, fontWeight: 700, display: 'inline-flex', alignItems: 'center', gap: 5,
                color: isActive ? '#065F46' : '#B91C1C',
                background: isActive ? '#ECFDF5' : '#FEF2F2',
                padding: '3px 10px', borderRadius: 20, width: 'fit-content',
              }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: isActive ? '#10B981' : '#EF4444', display: 'inline-block' }} />
                {isActive ? 'Active' : 'Removed'}
              </span>

              {/* Actions */}
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {isAdmin ? (
                  <span style={{ fontSize: 11, color: '#CBD5E1', fontStyle: 'italic' }}>Protected</span>
                ) : isActive ? (
                  <>
                    <button onClick={() => doResetPassword(u)} style={{
                      padding: '5px 10px', borderRadius: 7, border: '1.5px solid #E2E8F0', background: '#fff',
                      color: '#1A5090', fontFamily: 'inherit', fontSize: 11, fontWeight: 600, cursor: 'pointer',
                      display: 'inline-flex', alignItems: 'center', gap: 4,
                    }}>
                      <IC name="lock" size={10} color="#1A5090" /> Reset Pwd
                    </button>
                    <button onClick={() => setConfirmUser(u)} style={{
                      padding: '5px 10px', borderRadius: 7, border: 'none', background: '#FEF2F2',
                      color: '#EF4444', fontFamily: 'inherit', fontSize: 11, fontWeight: 600, cursor: 'pointer',
                      display: 'inline-flex', alignItems: 'center', gap: 4,
                    }}>
                      <IC name="x" size={10} color="#EF4444" strokeWidth={2.5} /> Remove
                    </button>
                    <button onClick={() => setDeleteUser(u)} style={{
                      padding: '5px 10px', borderRadius: 7, border: 'none', background: '#FEF2F2',
                      color: '#7F1D1D', fontFamily: 'inherit', fontSize: 11, fontWeight: 600, cursor: 'pointer',
                      display: 'inline-flex', alignItems: 'center', gap: 4,
                    }}>
                      <IC name="userminus" size={10} color="#7F1D1D" /> Delete
                    </button>
                  </>
                ) : (
                  <>
                    <button onClick={() => doReactivate(u)} style={{
                      padding: '5px 10px', borderRadius: 7, border: '1.5px solid #E2E8F0', background: '#fff',
                      color: '#64748B', fontFamily: 'inherit', fontSize: 11, fontWeight: 600, cursor: 'pointer',
                    }}>Reactivate</button>
                    <button onClick={() => setDeleteUser(u)} style={{
                      padding: '5px 10px', borderRadius: 7, border: 'none', background: '#FEF2F2',
                      color: '#7F1D1D', fontFamily: 'inherit', fontSize: 11, fontWeight: 600, cursor: 'pointer',
                      display: 'inline-flex', alignItems: 'center', gap: 4,
                    }}>
                      <IC name="userminus" size={10} color="#7F1D1D" /> Delete
                    </button>
                  </>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── Coordinator Tab ──────────────────────────────────────────────────────────
function CoordinatorTab({ users, loading, onRefresh, authH, showFlash }) {
  const [promoteTarget, setPromoteTarget] = React.useState('');
  const [promoting, setPromoting]         = React.useState(false);
  const [demoting, setDemoting]           = React.useState(null);

  const coordinators = users.filter(u => u.role === 'coordinator' && u.status === 'active');
  const eligible     = users.filter(u => u.role !== 'coordinator' && u.role !== 'admin' && u.status === 'active');

  function fmtDate(val) {
    if (!val) return '—';
    try { return new Date(val).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }); }
    catch { return val; }
  }

  async function grantCoordinator() {
    if (!promoteTarget) return;
    const target = users.find(u => String(u.id) === String(promoteTarget));
    if (!target) return;
    setPromoting(true);
    try {
      const res  = await fetch(`/api/users/${promoteTarget}/change-role`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', ...authH() },
        body: JSON.stringify({ role: 'coordinator' }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed');
      showFlash('success', `${target.name} is now a Coordinator.`);
      setPromoteTarget('');
      onRefresh();
    } catch (e) { showFlash('error', e.message); }
    finally { setPromoting(false); }
  }

  async function changeRole(u, role) {
    setDemoting(u.id);
    try {
      const res  = await fetch(`/api/users/${u.id}/change-role`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', ...authH() },
        body: JSON.stringify({ role }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed');
      showFlash('success', `${u.name}'s role changed to ${role}.`);
      onRefresh();
    } catch (e) { showFlash('error', e.message); }
    finally { setDemoting(null); }
  }

  return (
    <div>
      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginBottom: 24 }}>
        {[
          { label: 'Active Coordinators', value: coordinators.length,                                               icon: 'users',     bg: '#E0F2FE', ic: '#0EA5E9' },
          { label: 'Regular Users',       value: users.filter(u => u.role === 'user'  && u.status === 'active').length, icon: 'users',     bg: '#E8EFF8', ic: '#1A5090' },
          { label: 'Team Agents',         value: users.filter(u => u.role === 'agent' && u.status === 'active').length, icon: 'megaphone', bg: '#F5F3FF', ic: '#8B5CF6' },
        ].map(c => (
          <div key={c.label} style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', padding: '18px 20px', display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: c.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <IC name={c.icon} size={18} color={c.ic} />
            </div>
            <div>
              <div style={{ fontSize: 26, fontWeight: 800, color: '#0F172A', lineHeight: 1 }}>{loading ? '…' : c.value}</div>
              <div style={{ fontSize: 12, color: '#94A3B8', marginTop: 4 }}>{c.label}</div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 20, alignItems: 'start' }}>
        {/* Current coordinators */}
        <div style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', overflow: 'hidden' }}>
          <div style={{ padding: '14px 20px', background: '#E0F2FE', borderBottom: '1.5px solid #BAE6FD', display: 'flex', alignItems: 'center', gap: 8 }}>
            <IC name="users" size={15} color="#0284C7" />
            <span style={{ fontWeight: 700, fontSize: 14, color: '#0284C7' }}>Current Coordinators</span>
            <span style={{ marginLeft: 'auto', fontSize: 12, color: '#0284C7', fontWeight: 600 }}>{coordinators.length} active</span>
          </div>
          {loading ? (
            <div style={{ padding: '40px 20px', textAlign: 'center', color: '#94A3B8' }}>Loading…</div>
          ) : coordinators.length === 0 ? (
            <div style={{ padding: '40px 20px', textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>No coordinators yet. Grant access using the panel on the right.</div>
          ) : coordinators.map((u, i) => (
            <div key={u.id} style={{
              display: 'grid', gridTemplateColumns: '1fr 180px 180px', gap: 12, alignItems: 'center',
              padding: '13px 20px', borderBottom: i < coordinators.length - 1 ? '1px solid #F1F5F9' : 'none',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                <Avatar name={u.name} size={30} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: '#0F172A', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{u.name}</div>
                  <div style={{ fontSize: 11, color: '#64748B', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{u.email}</div>
                </div>
              </div>
              <div style={{ fontSize: 12, color: '#64748B' }}>Since {fmtDate(u.created_at)}</div>
              <div style={{ display: 'flex', gap: 6 }}>
                <button disabled={demoting === u.id} onClick={() => changeRole(u, 'user')} style={{
                  padding: '5px 10px', borderRadius: 7, border: '1.5px solid #E2E8F0', background: '#fff',
                  color: '#64748B', fontFamily: 'inherit', fontSize: 11, fontWeight: 600,
                  cursor: demoting === u.id ? 'wait' : 'pointer', opacity: demoting === u.id ? 0.5 : 1,
                }}>
                  Demote
                </button>
                <button disabled={demoting === u.id} onClick={() => changeRole(u, 'admin')} style={{
                  padding: '5px 10px', borderRadius: 7, border: 'none', background: '#FFFBEB',
                  color: '#D97706', fontFamily: 'inherit', fontSize: 11, fontWeight: 600,
                  cursor: demoting === u.id ? 'wait' : 'pointer', opacity: demoting === u.id ? 0.5 : 1,
                }}>
                  Make Admin
                </button>
              </div>
            </div>
          ))}
        </div>

        {/* Grant coordinator access */}
        <div style={{ background: '#fff', borderRadius: 12, border: '1.5px solid #E2E8F0', padding: '20px' }}>
          <div style={{ fontWeight: 700, fontSize: 14, color: '#0F172A', marginBottom: 4 }}>Grant Coordinator Access</div>
          <div style={{ fontSize: 12, color: '#94A3B8', marginBottom: 18 }}>
            Coordinators have the same access as admins but appear under the Coordinator section.
          </div>
          <label style={{ display: 'block', fontSize: 11, fontWeight: 700, color: '#374151', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>
            Select existing user
          </label>
          <select
            value={promoteTarget}
            onChange={e => setPromoteTarget(e.target.value)}
            style={{
              width: '100%', padding: '10px 12px', borderRadius: 8, border: '1.5px solid #E2E8F0',
              fontSize: 13, fontFamily: 'inherit', color: '#374151', background: '#fff',
              outline: 'none', marginBottom: 14, cursor: 'pointer',
            }}>
            <option value="">— Choose a user —</option>
            {eligible.map(u => (
              <option key={u.id} value={u.id}>{u.name} ({u.email})</option>
            ))}
          </select>
          <button
            disabled={!promoteTarget || promoting}
            onClick={grantCoordinator}
            style={{
              width: '100%', padding: '10px', borderRadius: 8, border: 'none',
              background: promoteTarget && !promoting ? '#0EA5E9' : '#E2E8F0',
              color: promoteTarget && !promoting ? '#fff' : '#94A3B8',
              fontFamily: 'inherit', fontSize: 13, fontWeight: 700,
              cursor: promoteTarget && !promoting ? 'pointer' : 'not-allowed',
              transition: 'all 0.15s',
            }}>
            {promoting ? 'Granting…' : 'Grant Coordinator Access'}
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AdminOnboarding, AdminAllTickets, AdminUsers, AdminTeams, AdminManagement, AllMembers });
