function fmtLastActive(v) { if (!v) return 'Never'; const days = Math.floor((Date.now() - new Date(v)) / 86400000); if (days <= 0) return 'Today'; if (days === 1) return 'Yesterday'; return days + ' days ago'; }

function UserDetailDialog({ user, onClose }) {
  const { Badge, Button } = window.TheUpperDeckDesignSystem_4d3294;
  const [resetMsg, setResetMsg] = React.useState('');
  const [resetting, setResetting] = React.useState(false);
  if (!user) return null;
  async function sendReset() {
    setResetting(true); setResetMsg('');
    try { await window.sendPasswordResetLive(user.email); setResetMsg('Reset email sent to ' + user.email + '.'); }
    catch (e) { setResetMsg('Failed: ' + e.message); }
    setResetting(false);
  }
  const fullName = [user.first_name, user.middle_name, user.last_name, user.suffix].filter(Boolean).join(' ');
  const addressLine = [user.address, user.city, user.province, user.zip].filter(Boolean).join(', ');
  const emergency = [user.emergency_contact_name, user.emergency_contact_relationship, user.emergency_contact_phone].filter(Boolean).join(' \u00b7 ');
  const org = [user.org_name, user.org_role_title, user.org_license_number].filter(Boolean).join(' \u00b7 ');
  return ReactDOM.createPortal(
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(8,21,27,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 24 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 480, maxHeight: '90vh', overflowY: 'auto', background: 'white', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)', padding: 28, position: 'relative' }}>
        <button onClick={onClose} style={{ position: 'absolute', top: 16, right: 16, width: 28, height: 28, borderRadius: '50%', border: 'none', background: 'var(--bg-sunken)', cursor: 'pointer' }}>{'\u00d7'}</button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
          <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--navy-800)', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-lg)' }}>{((user.first_name || '?')[0] + (user.last_name || '')[0]).toUpperCase()}</div>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-lg)' }}>{fullName}</div>
            <Badge tone={user.role === 'admin' ? 'brand' : 'default'}>{user.role}</Badge>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: 'var(--text-sm)' }}>
          <div><span style={{ color: 'var(--text-muted)' }}>Email: </span>{user.email}</div>
          <div><span style={{ color: 'var(--text-muted)' }}>Phone: </span>{user.phone || '\u2014'}</div>
          <div><span style={{ color: 'var(--text-muted)' }}>Address: </span>{addressLine || '\u2014'}</div>
          <div><span style={{ color: 'var(--text-muted)' }}>Sex: </span>{user.sex || '\u2014'}</div>
          <div><span style={{ color: 'var(--text-muted)' }}>Birthday: </span>{user.birthday ? new Date(user.birthday).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : '\u2014'}</div>
          <div><span style={{ color: 'var(--text-muted)' }}>Height / Weight: </span>{user.height_cm ? user.height_cm + ' cm' : '\u2014'} / {user.weight_kg ? user.weight_kg + ' kg' : '\u2014'}</div>
          {user.bio && <div><span style={{ color: 'var(--text-muted)' }}>Bio: </span>{user.bio}</div>}
          <div><span style={{ color: 'var(--text-muted)' }}>Emergency contact: </span>{emergency || '\u2014'}</div>
          <div><span style={{ color: 'var(--text-muted)' }}>Organization: </span>{org || '\u2014'}</div>
          <div><span style={{ color: 'var(--text-muted)' }}>How they heard about us: </span>{user.hear_about_us || '\u2014'}</div>
          <div><span style={{ color: 'var(--text-muted)' }}>Interests: </span>{(user.interests && user.interests.length) ? user.interests.join(', ') : '\u2014'}</div>
          <div><span style={{ color: 'var(--text-muted)' }}>Newsletter: </span>{user.newsletter_opted_in ? 'Subscribed' : 'Not subscribed'}</div>
          <div><span style={{ color: 'var(--text-muted)' }}>Joined: </span>{new Date(user.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</div>
          <div><span style={{ color: 'var(--text-muted)' }}>Last active: </span>{fmtLastActive(user.last_active_at)}</div>
        </div>
        <div style={{ borderTop: '1px solid var(--border-default)', marginTop: 20, paddingTop: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
          {resetMsg && <div style={{ fontSize: 'var(--text-sm)', color: resetMsg.startsWith('Failed') ? 'var(--status-error)' : 'var(--status-success)' }}>{resetMsg}</div>}
          <Button variant="secondary" onClick={sendReset} disabled={resetting} style={{ alignSelf: 'flex-start' }}>{resetting ? 'Sending\u2026' : 'Send password reset email'}</Button>
        </div>
      </div>
    </div>, document.body
  );
}

function UsersScreen() {
  const { Badge } = window.TheUpperDeckDesignSystem_4d3294;
  const { SearchInput, CustomSelect, Btn, ColumnPicker, useColumnPrefs } = window.UdUI;
  const [users, setUsers] = React.useState(null);
  const [query, setQuery] = React.useState('');
  const [roleFilter, setRoleFilter] = React.useState('');
  const [sort, setSort] = React.useState('joined_desc');
  const [viewing, setViewing] = React.useState(null);
  const ALL_COLUMNS = [
    { key: 'name', label: 'Name', locked: true }, { key: 'email', label: 'Email' }, { key: 'phone', label: 'Phone' },
    { key: 'city', label: 'City' }, { key: 'role', label: 'Role' }, { key: 'joined', label: 'Joined' }, { key: 'lastActive', label: 'Last active' },
  ];
  const [cols, setCols] = useColumnPrefs('users', ALL_COLUMNS.map((c) => c.key));

  React.useEffect(() => { window.fetchAllUsersLive().then(setUsers); }, []);
  if (users === null) return <div style={{ padding: 32, color: 'var(--text-muted)' }}>Loading{'\u2026'}</div>;

  let filtered = users.filter((u) => {
    const q = query.toLowerCase();
    const matchQ = !q || (u.first_name + ' ' + u.last_name).toLowerCase().includes(q) || (u.email || '').toLowerCase().includes(q);
    const matchRole = !roleFilter || u.role === roleFilter;
    return matchQ && matchRole;
  });
  filtered = filtered.slice().sort((a, b) => {
    if (sort === 'name_asc') return (a.first_name + a.last_name).localeCompare(b.first_name + b.last_name);
    if (sort === 'city_asc') return (a.city || '').localeCompare(b.city || '');
    if (sort === 'joined_asc') return new Date(a.created_at) - new Date(b.created_at);
    if (sort === 'joined_desc') return new Date(b.created_at) - new Date(a.created_at);
    if (sort === 'active_desc') return new Date(b.last_active_at || 0) - new Date(a.last_active_at || 0);
    return 0;
  });

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20, flexWrap: 'wrap', gap: 12 }}>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
          <SearchInput value={query} onChange={setQuery} placeholder="Search name or email…" width={220} />
          <CustomSelect value={roleFilter} onChange={setRoleFilter} placeholder="All roles" width={140} options={[{ value: 'admin', label: 'Admin' }, { value: 'user', label: 'User' }]} />
          <CustomSelect value={sort} onChange={setSort} placeholder="Sort by" width={170} options={[
            { value: 'joined_desc', label: 'Newest joined' }, { value: 'joined_asc', label: 'Oldest joined' },
            { value: 'name_asc', label: 'Name (A\u2013Z)' }, { value: 'city_asc', label: 'City (A\u2013Z)' }, { value: 'active_desc', label: 'Most recently active' },
          ]} />
        </div>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <ColumnPicker columns={ALL_COLUMNS} visible={cols} onChange={setCols} />
          <div style={{ color: 'var(--text-muted)', fontSize: 'var(--text-sm)' }}>{filtered.length} accounts</div>
        </div>
      </div>
      <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', overflowX: 'auto' }}>
        <table style={{ width: '100%', minWidth: 620, borderCollapse: 'collapse', fontSize: 'var(--text-sm)' }}>
          <thead><tr style={{ textAlign: 'left', background: 'var(--bg-sunken)', color: 'var(--text-muted)', fontSize: 'var(--text-xs)', textTransform: 'uppercase' }}>
            {cols.includes('name') && <th style={{ padding: '12px 16px' }}>Name</th>}
            {cols.includes('email') && <th>Email</th>}
            {cols.includes('phone') && <th>Phone</th>}
            {cols.includes('city') && <th>City</th>}
            {cols.includes('role') && <th>Role</th>}
            {cols.includes('joined') && <th>Joined</th>}
            {cols.includes('lastActive') && <th>Last active</th>}
            <th></th>
          </tr></thead>
          <tbody>
            {filtered.map((u) => (
              <tr key={u.id} className="ud-row" style={{ borderTop: '1px solid var(--border-default)' }}>
                {cols.includes('name') && <td style={{ padding: '12px 16px', fontWeight: 600 }}>{u.first_name} {u.last_name}</td>}
                {cols.includes('email') && <td style={{ color: 'var(--text-secondary)' }}>{u.email}</td>}
                {cols.includes('phone') && <td style={{ color: 'var(--text-secondary)' }}>{u.phone || '\u2014'}</td>}
                {cols.includes('city') && <td style={{ color: 'var(--text-secondary)' }}>{u.city || '\u2014'}</td>}
                {cols.includes('role') && <td><Badge tone={u.role === 'admin' ? 'brand' : 'default'}>{u.role}</Badge></td>}
                {cols.includes('joined') && <td style={{ color: 'var(--text-muted)', fontSize: 'var(--text-xs)' }}>{new Date(u.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}</td>}
                {cols.includes('lastActive') && <td style={{ color: 'var(--text-muted)', fontSize: 'var(--text-xs)' }}>{fmtLastActive(u.last_active_at)}</td>}
                <td style={{ textAlign: 'right', paddingRight: 16 }}><Btn size="sm" variant="secondary" onClick={() => setViewing(u)}>View</Btn></td>
              </tr>
            ))}
            {filtered.length === 0 && <tr><td colSpan={8} style={{ padding: 16, color: 'var(--text-muted)' }}>No accounts found.</td></tr>}
          </tbody>
        </table>
      </div>
      <UserDetailDialog user={viewing} onClose={() => setViewing(null)} />
    </div>
  );
}
window.UsersScreen = UsersScreen;
