// ---- Admin Page ----
window.AdminPage = function AdminPage({ userProfile, t }) {
  const { useState, useEffect } = React;
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState(null);

  // Analytics state
  const [analytics, setAnalytics] = useState(null);
  const [analyticsLoading, setAnalyticsLoading] = useState(true);
  const [sortField, setSortField] = useState('spendToday');
  const [sortDir, setSortDir] = useState('desc');

  // Config panel state
  const [expandedUid, setExpandedUid] = useState(null);
  const [userConfig, setUserConfig] = useState(null);
  const [configLoading, setConfigLoading] = useState(false);
  const [configSaving, setConfigSaving] = useState(false);
  const [configSuccess, setConfigSuccess] = useState(false);
  const [methods, setMethods] = useState([]);

  const refreshUsers = async () => {
    try {
      const data = await api.get('/api/admin/users');
      setUsers(data);
    } catch (err) {
      console.error('Failed to load users:', err);
    }
  };

  useEffect(() => {
    refreshUsers().then(() => setLoading(false));
    api.get('/api/training-methods').then(setMethods).catch(console.error);
    api.get('/api/admin/analytics').then(data => {
      setAnalytics(data);
      setAnalyticsLoading(false);
    }).catch(err => {
      console.error('Failed to load analytics:', err);
      setAnalyticsLoading(false);
    });
  }, []);

  const toggleApproval = async (uid, currentApproved) => {
    setActionLoading(uid);
    try {
      await api.put(`/api/admin/users/${uid}`, { approved: !currentApproved });
      await refreshUsers();
    } catch (err) {
      alert('Error: ' + err.message);
    } finally {
      setActionLoading(null);
    }
  };

  const changeRole = async (uid, newRole) => {
    setActionLoading(uid);
    try {
      await api.put(`/api/admin/users/${uid}`, { role: newRole });
      await refreshUsers();
    } catch (err) {
      alert('Error: ' + err.message);
    } finally {
      setActionLoading(null);
    }
  };

  const deleteUser = async (uid, email) => {
    if (!confirm(t('deleteUserConfirm') + ' ' + email + '?')) return;
    setActionLoading(uid);
    try {
      await api.del(`/api/admin/users/${uid}`);
      await refreshUsers();
    } catch (err) {
      alert('Error: ' + err.message);
    } finally {
      setActionLoading(null);
    }
  };

  const toggleExpand = async (uid) => {
    if (expandedUid === uid) {
      setExpandedUid(null);
      setUserConfig(null);
      return;
    }
    setExpandedUid(uid);
    setConfigLoading(true);
    try {
      const config = await api.get(`/api/admin/users/${uid}/config`);
      setUserConfig(config);
    } catch (err) {
      console.error('Failed to load config:', err);
      setUserConfig(null);
    } finally {
      setConfigLoading(false);
    }
  };

  const saveUserConfig = async (uid) => {
    if (!userConfig) return;
    setConfigSaving(true);
    setConfigSuccess(false);
    try {
      await api.put(`/api/admin/users/${uid}/config`, {
        training_method: userConfig.training_method,
        language: userConfig.language,
        sport_profile: userConfig.sport_profile,
      });
      setConfigSuccess(true);
      setTimeout(() => setConfigSuccess(false), 3000);
    } catch (err) {
      alert('Error: ' + err.message);
    } finally {
      setConfigSaving(false);
    }
  };

  const saveQuota = async (uid) => {
    if (!userConfig) return;
    setConfigSaving(true);
    setConfigSuccess(false);
    try {
      await api.put(`/api/admin/users/${uid}/quota`, {
        dailyQuota: Number(userConfig.dailyQuota),
      });
      setConfigSuccess(true);
      await refreshUsers();
      setTimeout(() => setConfigSuccess(false), 3000);
    } catch (err) {
      alert('Error: ' + err.message);
    } finally {
      setConfigSaving(false);
    }
  };

  const startImpersonation = (uid, email) => {
    if (!confirm(t('impersonateConfirm'))) return;
    localStorage.setItem('impersonate_uid', uid);
    location.reload();
  };

  const resetChats = async (uid, email) => {
    if (!confirm(t('resetChatConfirm'))) return;
    setActionLoading(uid);
    try {
      const result = await api.del(`/api/admin/users/${uid}/chats`);
      alert(result.deleted > 0 ? t('chatHistoryReset') + ` (${result.deleted})` : t('noChatsToDelete'));
    } catch (err) {
      alert('Error: ' + err.message);
    } finally {
      setActionLoading(null);
    }
  };

  const sortedPerUser = React.useMemo(() => {
    if (!analytics?.perUser) return [];
    return [...analytics.perUser].sort((a, b) => {
      let aVal = a[sortField];
      let bVal = b[sortField];
      // Handle nulls (lastActive can be null)
      if (aVal === null || aVal === undefined) aVal = sortDir === 'asc' ? Infinity : -Infinity;
      if (bVal === null || bVal === undefined) bVal = sortDir === 'asc' ? Infinity : -Infinity;
      // String comparison for lastActive and email
      if (typeof aVal === 'string' && typeof bVal === 'string') {
        return sortDir === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
      }
      return sortDir === 'asc' ? aVal - bVal : bVal - aVal;
    });
  }, [analytics, sortField, sortDir]);

  const toggleSort = (field) => {
    if (sortField === field) {
      setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortDir('desc');
    }
  };

  return (
    <div>
      <div className="page-header">
        <h2>{t('adminPage')}</h2>
        <p>{t('adminPageDesc')}</p>
      </div>

      {/* Analytics Section */}
      {analyticsLoading ? (
        <div style={{ display: 'flex', justifyContent: 'center', padding: 32 }}>
          <div className="spinner" style={{ width: 24, height: 24 }} />
        </div>
      ) : analytics && (
        <>
          {/* Section header */}
          <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--text-primary)', marginBottom: 12 }}>
            {t('analyticsTitle')}
          </div>

          {/* Summary Cards */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))',
            gap: 12,
            marginBottom: 20,
          }}>
            {/* Total Users */}
            <div style={{
              padding: '16px 14px', background: 'var(--bg-card)', borderRadius: 10,
              border: '1px solid var(--border)',
            }}>
              <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 4 }}>{t('totalUsers')}</div>
              <div style={{ fontSize: 24, fontWeight: 700, fontFamily: 'JetBrains Mono, monospace', color: 'var(--text-primary)' }}>
                {analytics.summary.totalUsers}
              </div>
            </div>

            {/* Active Today */}
            <div style={{
              padding: '16px 14px', background: 'var(--bg-card)', borderRadius: 10,
              border: '1px solid var(--border)',
            }}>
              <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 4 }}>{t('activeToday')}</div>
              <div style={{ fontSize: 24, fontWeight: 700, fontFamily: 'JetBrains Mono, monospace', color: 'var(--accent-green)' }}>
                {analytics.summary.activeToday}
              </div>
            </div>

            {/* API Calls Today */}
            <div style={{
              padding: '16px 14px', background: 'var(--bg-card)', borderRadius: 10,
              border: '1px solid var(--border)',
            }}>
              <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 4 }}>{t('apiCallsToday')}</div>
              <div style={{ fontSize: 24, fontWeight: 700, fontFamily: 'JetBrains Mono, monospace', color: 'var(--accent-blue)' }}>
                {analytics.summary.totalRequestsToday}
              </div>
            </div>

            {/* Spend Today */}
            <div style={{
              padding: '16px 14px', background: 'var(--bg-card)', borderRadius: 10,
              border: '1px solid var(--border)',
            }}>
              <div style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 4 }}>{t('spendToday')}</div>
              <div style={{ fontSize: 24, fontWeight: 700, fontFamily: 'JetBrains Mono, monospace', color: 'var(--accent-orange)' }}>
                ${analytics.summary.totalSpendToday.toFixed(2)}
              </div>
            </div>
          </div>

          {/* Per-User Usage Table */}
          <div className="card" style={{ marginBottom: 20 }}>
            <div className="card-header">
              <div className="card-title">{t('perUserUsage')}</div>
            </div>
            <div style={{ overflowX: 'auto' }}>
              <table style={{
                width: '100%', borderCollapse: 'collapse', fontSize: 13,
                fontFamily: 'DM Sans, sans-serif',
              }}>
                <thead>
                  <tr style={{ borderBottom: '1px solid var(--border)' }}>
                    {[
                      { key: 'email', label: t('email') },
                      { key: 'requestsToday', label: t('apiCalls') },
                      { key: 'spendToday', label: t('spend') },
                      { key: 'lastActive', label: t('lastActive') },
                      { key: 'chatSessionCount', label: t('chatSessions') },
                    ].map(col => (
                      <th key={col.key}
                        onClick={() => toggleSort(col.key)}
                        style={{
                          padding: '10px 12px', textAlign: 'left', cursor: 'pointer',
                          color: sortField === col.key ? 'var(--accent-blue)' : 'var(--text-secondary)',
                          fontWeight: 500, fontSize: 12, whiteSpace: 'nowrap',
                          userSelect: 'none',
                        }}
                      >
                        {col.label} {sortField === col.key ? (sortDir === 'asc' ? '\u2191' : '\u2193') : ''}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {sortedPerUser.map(u => (
                    <tr key={u.uid} style={{ borderBottom: '1px solid var(--border)' }}>
                      <td style={{ padding: '10px 12px', color: 'var(--text-primary)' }}>
                        <div>{u.displayName || u.email}</div>
                        {u.displayName && <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>{u.email}</div>}
                      </td>
                      <td style={{ padding: '10px 12px', fontFamily: 'JetBrains Mono, monospace', color: 'var(--text-primary)' }}>
                        {u.requestsToday}
                      </td>
                      <td style={{ padding: '10px 12px', fontFamily: 'JetBrains Mono, monospace', color: 'var(--text-primary)' }}>
                        ${u.spendToday.toFixed(4)}
                      </td>
                      <td style={{ padding: '10px 12px', color: 'var(--text-secondary)', fontSize: 12 }}>
                        {u.lastActive ? new Date(u.lastActive).toLocaleDateString() : t('never')}
                      </td>
                      <td style={{ padding: '10px 12px', fontFamily: 'JetBrains Mono, monospace', color: 'var(--text-primary)' }}>
                        {u.chatSessionCount}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* System Health Panel */}
          <div className="card" style={{ marginBottom: 20 }}>
            <div className="card-header">
              <div className="card-title">{t('systemHealth')}</div>
              <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                {t('checkedAt')} {new Date(analytics.systemHealth.checkedAt).toLocaleTimeString()}
              </span>
            </div>
            <div style={{ padding: '12px 14px', display: 'flex', flexDirection: 'column', gap: 10 }}>
              {/* Claude API status */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{
                  width: 10, height: 10, borderRadius: '50%',
                  background: analytics.systemHealth.claudeApi === 'ok' ? 'var(--accent-green)' :
                               analytics.systemHealth.claudeApi === 'error' ? 'var(--accent-red)' : 'var(--text-muted)',
                }} />
                <span style={{ fontSize: 13, color: 'var(--text-primary)' }}>{t('claudeApi')}</span>
                <span style={{
                  fontSize: 12, marginLeft: 'auto',
                  color: analytics.systemHealth.claudeApi === 'ok' ? 'var(--accent-green)' :
                         analytics.systemHealth.claudeApi === 'error' ? 'var(--accent-red)' : 'var(--text-muted)',
                }}>
                  {analytics.systemHealth.claudeApi === 'ok' ? t('statusOk') :
                   analytics.systemHealth.claudeApi === 'error' ? t('statusError') : t('statusUnknown')}
                </span>
              </div>

              {/* intervals.icu status */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{
                  width: 10, height: 10, borderRadius: '50%',
                  background: analytics.systemHealth.intervalsIcu === 'ok' ? 'var(--accent-green)' :
                               analytics.systemHealth.intervalsIcu === 'error' ? 'var(--accent-red)' : 'var(--text-muted)',
                }} />
                <span style={{ fontSize: 13, color: 'var(--text-primary)' }}>{t('intervalsIcu')}</span>
                <span style={{
                  fontSize: 12, marginLeft: 'auto',
                  color: analytics.systemHealth.intervalsIcu === 'ok' ? 'var(--accent-green)' :
                         analytics.systemHealth.intervalsIcu === 'error' ? 'var(--accent-red)' : 'var(--text-muted)',
                }}>
                  {analytics.systemHealth.intervalsIcu === 'ok' ? t('statusOk') :
                   analytics.systemHealth.intervalsIcu === 'error' ? t('statusError') : t('statusUnknown')}
                </span>
              </div>

              {/* Recent errors */}
              {analytics.systemHealth.recentErrors.length > 0 ? (
                <div style={{ marginTop: 6 }}>
                  {analytics.systemHealth.recentErrors.map((err, i) => (
                    <div key={i} style={{
                      padding: '8px 10px', background: 'var(--accent-red-dim)',
                      borderRadius: 6, marginBottom: 4, fontSize: 12,
                    }}>
                      <span style={{ color: 'var(--accent-red)', fontWeight: 500 }}>{err.source}</span>
                      <span style={{ color: 'var(--text-secondary)', marginLeft: 8 }}>{err.message}</span>
                    </div>
                  ))}
                </div>
              ) : (
                <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 4 }}>
                  {t('noErrors')}
                </div>
              )}
            </div>
          </div>
        </>
      )}

      <div className="card">
        <div className="card-header">
          <div className="card-title">{t('registeredUsers')}</div>
          <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>
            {users.length} {t('usersTotal')}
          </span>
        </div>

        {loading ? (
          <div style={{ display: 'flex', justifyContent: 'center', padding: 32 }}>
            <div className="spinner" style={{ width: 24, height: 24 }} />
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {users.map(u => (
              <React.Fragment key={u.uid}>
                <div style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  padding: '12px 14px', background: 'var(--bg-secondary)',
                  borderRadius: expandedUid === u.uid ? '8px 8px 0 0' : 8,
                  border: '1px solid ' + (expandedUid === u.uid ? 'var(--accent-blue)' : 'var(--border)'),
                  flexWrap: 'wrap', gap: 10,
                }}>
                  {/* Left: avatar + info */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0, flex: 1 }}>
                    {u.photoURL && <img src={u.photoURL} style={{ width: 32, height: 32, borderRadius: '50%', flexShrink: 0 }} />}
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 500 }}>{u.displayName || u.email}</div>
                      <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>{u.email}</div>
                      <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>
                        {t('lastActive')}: {u.lastActive ? new Date(u.lastActive).toLocaleDateString() : t('never')}
                      </div>
                    </div>
                  </div>

                  {/* Right: badges + actions */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
                    {/* Role badge */}
                    <span className="card-badge" style={{
                      background: u.role === 'admin' ? 'var(--accent-purple)' + '22' : 'var(--accent-blue-dim)',
                      color: u.role === 'admin' ? 'var(--accent-purple)' : 'var(--accent-blue)',
                    }}>
                      {u.role}
                    </span>

                    {/* Approval badge */}
                    <span className="card-badge" style={{
                      background: u.approved ? 'var(--accent-green-dim)' : 'var(--accent-orange-dim)',
                      color: u.approved ? 'var(--accent-green)' : 'var(--accent-orange)',
                    }}>
                      {u.approved ? t('userApproved') : t('userPending')}
                    </span>

                    {/* Intervals badge */}
                    {u.intervalsConfigured && (
                      <span style={{ fontSize: 10, color: 'var(--text-muted)' }}>intervals.icu</span>
                    )}

                    {/* Config expand button — available for all users */}
                    <button
                      className={`btn btn-sm ${expandedUid === u.uid ? 'btn-primary' : ''}`}
                      onClick={() => toggleExpand(u.uid)}
                      style={{ fontSize: 11, padding: '4px 10px' }}
                    >
                      {t('viewConfig')}
                    </button>

                    {/* Action buttons — hide for self (admin's own row) */}
                    {u.uid !== userProfile?.uid && (
                      <>
                        {/* Impersonate button */}
                        <button
                          className="btn btn-sm"
                          onClick={() => startImpersonation(u.uid, u.email)}
                          disabled={actionLoading === u.uid}
                          style={{
                            fontSize: 11, padding: '4px 10px',
                            color: 'var(--accent-orange)', borderColor: 'var(--accent-orange)',
                          }}
                        >
                          {t('impersonate')}
                        </button>

                        {/* Approve/Deny button */}
                        <button
                          className={`btn btn-sm ${u.approved ? '' : 'btn-success'}`}
                          onClick={() => toggleApproval(u.uid, u.approved)}
                          disabled={actionLoading === u.uid}
                          style={{ fontSize: 11, padding: '4px 10px' }}
                        >
                          {u.approved ? t('deny') : t('approve')}
                        </button>

                        {/* Role toggle button */}
                        <button
                          className="btn btn-sm"
                          onClick={() => changeRole(u.uid, u.role === 'admin' ? 'user' : 'admin')}
                          disabled={actionLoading === u.uid}
                          style={{ fontSize: 11, padding: '4px 10px' }}
                        >
                          {u.role === 'admin' ? t('demoteToUser') : t('promoteToAdmin')}
                        </button>

                        {/* Delete button */}
                        <button
                          className="btn btn-sm"
                          onClick={() => deleteUser(u.uid, u.email)}
                          disabled={actionLoading === u.uid}
                          style={{
                            fontSize: 11, padding: '4px 10px',
                            color: 'var(--accent-red)', borderColor: 'var(--accent-red)',
                          }}
                        >
                          {t('delete')}
                        </button>
                      </>
                    )}
                  </div>
                </div>

                {/* Config panel — shown when row is expanded */}
                {expandedUid === u.uid && (
                  <div style={{
                    padding: '16px 14px', background: 'var(--bg-card)', borderRadius: '0 0 8px 8px',
                    border: '1px solid var(--accent-blue)', borderTop: 'none',
                    marginTop: -8, marginBottom: 4,
                  }}>
                    {configLoading ? (
                      <div style={{ display: 'flex', justifyContent: 'center', padding: 20 }}>
                        <div className="spinner" style={{ width: 20, height: 20 }} />
                      </div>
                    ) : userConfig ? (
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-primary)' }}>{t('userConfig')}</div>

                        {/* Training Method */}
                        <div>
                          <label style={{ display: 'block', fontSize: 12, color: 'var(--text-secondary)', marginBottom: 4 }}>
                            {t('trainingMethod')}
                          </label>
                          <select
                            className="date-input"
                            value={userConfig.training_method || 'norwegian'}
                            onChange={e => setUserConfig(c => ({ ...c, training_method: e.target.value }))}
                            style={{ width: '100%', maxWidth: 300 }}
                          >
                            {methods.map(m => (
                              <option key={m.id} value={m.id}>{m.name}</option>
                            ))}
                          </select>
                        </div>

                        {/* Language */}
                        <div>
                          <label style={{ display: 'block', fontSize: 12, color: 'var(--text-secondary)', marginBottom: 4 }}>
                            {t('language')}
                          </label>
                          <select
                            className="date-input"
                            value={userConfig.language || 'en'}
                            onChange={e => setUserConfig(c => ({ ...c, language: e.target.value }))}
                            style={{ width: 160 }}
                          >
                            <option value="en">English</option>
                            <option value="es">Espanol</option>
                          </select>
                        </div>

                        {/* Sport Profile */}
                        <div>
                          <label style={{ display: 'block', fontSize: 12, color: 'var(--text-secondary)', marginBottom: 4 }}>
                            {t('sportProfile')}
                          </label>
                          <select
                            className="date-input"
                            value={userConfig.sport_profile || 'triathlete'}
                            onChange={e => setUserConfig(c => ({ ...c, sport_profile: e.target.value }))}
                            style={{ width: 160 }}
                          >
                            <option value="triathlete">{t('triathlete')}</option>
                            <option value="runner">{t('runner')}</option>
                            <option value="cyclist">{t('cyclist')}</option>
                          </select>
                        </div>

                        {/* Goals (read-only display) */}
                        <div>
                          <label style={{ display: 'block', fontSize: 12, color: 'var(--text-secondary)', marginBottom: 4 }}>
                            {t('goals')}
                          </label>
                          <div style={{ fontSize: 13, color: 'var(--text-primary)', padding: '8px 10px', background: 'var(--bg-secondary)', borderRadius: 6, minHeight: 20 }}>
                            {userConfig.goals || <span style={{ color: 'var(--text-muted)', fontStyle: 'italic' }}>{t('noGoals')}</span>}
                          </div>
                        </div>

                        {/* Weekly Hours (read-only display) */}
                        <div>
                          <label style={{ display: 'block', fontSize: 12, color: 'var(--text-secondary)', marginBottom: 4 }}>
                            {t('weeklyHours')}
                          </label>
                          <div style={{ fontSize: 13, color: 'var(--text-primary)', padding: '8px 10px', background: 'var(--bg-secondary)', borderRadius: 6, minHeight: 20 }}>
                            {userConfig.weekly_hours ? `${userConfig.weekly_hours}h` : <span style={{ color: 'var(--text-muted)', fontStyle: 'italic' }}>—</span>}
                          </div>
                        </div>

                        {/* Save Config Button */}
                        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                          <button
                            className="btn btn-primary btn-sm"
                            onClick={() => saveUserConfig(u.uid)}
                            disabled={configSaving}
                            style={{ fontSize: 12 }}
                          >
                            {configSaving ? t('savingConfig') : t('saveConfig')}
                          </button>
                          {configSuccess && (
                            <span style={{ color: 'var(--accent-green)', fontSize: 12 }}>{t('configSaved')}</span>
                          )}
                        </div>

                        {/* Divider */}
                        <div style={{ borderTop: '1px solid var(--border)', margin: '4px 0' }} />

                        {/* Daily API Quota */}
                        <div>
                          <label style={{ display: 'block', fontSize: 12, color: 'var(--text-secondary)', marginBottom: 4 }}>
                            {t('dailyQuota')} (USD)
                          </label>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                            <input
                              type="number"
                              className="date-input"
                              min="0"
                              max="100"
                              step="0.5"
                              value={userConfig.dailyQuota ?? 5}
                              onChange={e => setUserConfig(c => ({ ...c, dailyQuota: e.target.value }))}
                              style={{ width: 100 }}
                            />
                            <button
                              className="btn btn-sm"
                              onClick={() => saveQuota(u.uid)}
                              disabled={configSaving}
                              style={{ fontSize: 11, padding: '4px 10px' }}
                            >
                              {t('save')}
                            </button>
                          </div>
                          <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 4 }}>{t('dailyQuotaDesc')}</div>
                        </div>

                        {/* Divider */}
                        <div style={{ borderTop: '1px solid var(--border)', margin: '4px 0' }} />

                        {/* Reset Chat History */}
                        <div>
                          <button
                            className="btn btn-sm"
                            onClick={() => resetChats(u.uid, u.email)}
                            disabled={actionLoading === u.uid}
                            style={{
                              fontSize: 11, padding: '4px 10px',
                              color: 'var(--accent-red)', borderColor: 'var(--accent-red)',
                            }}
                          >
                            {t('resetChatHistory')}
                          </button>
                        </div>
                      </div>
                    ) : (
                      <div style={{ fontSize: 13, color: 'var(--text-muted)', padding: 12 }}>
                        {t('error')}
                      </div>
                    )}
                  </div>
                )}
              </React.Fragment>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};
