(() => {
  const { useEffect, useMemo, useState, useCallback } = React;

  const ADMIN_TABS = [
    { id: 'overview', label: 'Overview' },
    { id: 'users', label: 'Users' },
    { id: 'health', label: 'Health' },
    { id: 'audit', label: 'Audit Logs' },
    { id: 'export', label: 'Data Export' },
  ];

  const ROLE_OPTIONS = [
    { value: 'admin', label: 'Admin' },
    { value: 'superadmin', label: 'Super Admin' },
    { value: 'host', label: 'Host' },
    { value: 'user', label: 'User' },
  ];

  const STATUS_OPTIONS = [
    { value: 'active', label: 'Active' },
    { value: 'suspended', label: 'Suspended' },
    { value: 'invited', label: 'Invited' },
  ];

  function StatCard({ icon, label, value, trend }) {
    return (
      <div className="bg-gray-800 border border-gray-700 rounded-lg p-4">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm text-gray-400">{label}</p>
            <p className="text-2xl font-bold mt-1">{value}</p>
          </div>
          <div className="text-blue-400 text-3xl">
            <i className={`fas ${icon}`}></i>
          </div>
        </div>
        {trend !== undefined && (
          <p className={`mt-3 text-sm ${trend >= 0 ? 'text-green-400' : 'text-red-400'}`}>
            {trend >= 0 ? '+' : ''}{trend}% vs last period
          </p>
        )}
      </div>
    );
  }

  function UsersTable({
    users,
    selectedIds,
    toggleSelect,
    onEdit,
    onDelete,
    onReset,
  }) {
    return (
      <div className="overflow-auto border border-gray-700 rounded-lg">
        <table className="min-w-full divide-y divide-gray-700">
          <thead className="bg-gray-800">
            <tr>
              <th className="px-4 py-3">
                <input
                  type="checkbox"
                  checked={users.length > 0 && selectedIds.length === users.length}
                  onChange={(e) => {
                    if (e.target.checked) {
                      toggleSelect(users.map((u) => u.id));
                    } else {
                      toggleSelect([]);
                    }
                  }}
                />
              </th>
              <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-400">User</th>
              <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-400">Role</th>
              <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-400">Status</th>
              <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-400">Created</th>
              <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-400">Actions</th>
            </tr>
          </thead>
          <tbody className="bg-gray-900 divide-y divide-gray-800">
            {users.map((user) => (
              <tr key={user.id}>
                <td className="px-4 py-3">
                  <input
                    type="checkbox"
                    checked={selectedIds.includes(user.id)}
                    onChange={(e) => {
                      if (e.target.checked) {
                        toggleSelect([...selectedIds, user.id]);
                      } else {
                        toggleSelect(selectedIds.filter((id) => id !== user.id));
                      }
                    }}
                  />
                </td>
                <td className="px-4 py-3">
                  <div className="font-medium text-white">{user.name}</div>
                  <div className="text-sm text-gray-400">{user.email}</div>
                </td>
                <td className="px-4 py-3">
                  <span className="px-2 py-1 text-xs rounded bg-blue-900 text-blue-200 uppercase tracking-wide">
                    {user.role}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <span
                    className={`px-2 py-1 text-xs rounded uppercase tracking-wide ${
                      user.status === 'active'
                        ? 'bg-green-900 text-green-200'
                        : 'bg-yellow-900 text-yellow-200'
                    }`}
                  >
                    {user.status}
                  </span>
                </td>
                <td className="px-4 py-3 text-sm text-gray-400">
                  {new Date(user.created_at).toLocaleString()}
                </td>
                <td className="px-4 py-3 text-right space-x-2">
                  <button
                    className="px-3 py-1 bg-gray-700 hover:bg-gray-600 rounded text-sm"
                    onClick={() => onEdit(user)}
                  >
                    Edit
                  </button>
                  <button
                    className="px-3 py-1 bg-yellow-600 hover:bg-yellow-700 rounded text-sm"
                    onClick={() => onReset && onReset(user)}
                  >
                    Reset
                  </button>
                  <button
                    className="px-3 py-1 bg-red-600 hover:bg-red-700 rounded text-sm"
                    onClick={() => onDelete(user)}
                  >
                    Delete
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }

  function UserForm({ initialValues, onSubmit, onCancel, submitLabel }) {
    const [form, setForm] = useState(() => ({
      email: initialValues?.email || '',
      name: initialValues?.name || '',
      role: initialValues?.role || 'user',
      status: initialValues?.status || 'active',
      password: '',
    }));

    const handleChange = (field) => (event) => {
      setForm((prev) => ({ ...prev, [field]: event.target.value }));
    };

    const handleSubmit = (event) => {
      event.preventDefault();
      onSubmit(form);
    };

    return (
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="block text-sm text-gray-300 mb-1">Email</label>
          <input
            type="email"
            value={form.email}
            onChange={handleChange('email')}
            className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded"
            required
            disabled={Boolean(initialValues?.email)}
          />
        </div>
        <div>
          <label className="block text-sm text-gray-300 mb-1">Full name</label>
          <input
            type="text"
            value={form.name}
            onChange={handleChange('name')}
            className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded"
            required
          />
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm text-gray-300 mb-1">Role</label>
            <select
              value={form.role}
              onChange={handleChange('role')}
              className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded"
            >
              {ROLE_OPTIONS.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm text-gray-300 mb-1">Status</label>
            <select
              value={form.status}
              onChange={handleChange('status')}
              className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded"
            >
              {STATUS_OPTIONS.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>
        </div>
        <div>
          <label className="block text-sm text-gray-300 mb-1">Password {initialValues ? '(optional)' : '(required)'}</label>
          <input
            type="password"
            value={form.password}
            onChange={handleChange('password')}
            className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded"
            required={!initialValues}
            placeholder={initialValues ? 'Leave blank to keep existing password' : 'Temporary password'}
          />
        </div>
        <div className="flex justify-end space-x-3">
          <button
            type="button"
            onClick={onCancel}
            className="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded"
          >
            Cancel
          </button>
          <button
            type="submit"
            className="px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded"
          >
            {submitLabel}
          </button>
        </div>
      </form>
    );
  }

  function SectionCard({ title, description, children, actions }) {
    return (
      <div className="bg-gray-900 border border-gray-800 rounded-xl p-6 shadow-lg">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-6">
          <div>
            <h3 className="text-xl font-semibold text-white">{title}</h3>
            {description && <p className="text-sm text-gray-400 mt-1">{description}</p>}
          </div>
          {actions}
        </div>
        {children}
      </div>
    );
  }

  function usePolling(fetcher, intervalMs, deps = []) {
    useEffect(() => {
      let isMounted = true;
      let timeoutId;

      const execute = async () => {
        try {
          await fetcher();
        } finally {
          if (isMounted) {
            timeoutId = setTimeout(execute, intervalMs);
          }
        }
      };

      execute();
      return () => {
        isMounted = false;
        clearTimeout(timeoutId);
      };
    }, deps);
  }

  function AdminDashboard({ token, user, onClose }) {
    const api = window.cloudRTCApi;

    if (!api) {
      return (
        <div className="fixed inset-0 sketch-overlay z-50 flex items-center justify-center p-6">
          <div className="sketch-card text-center max-w-md p-6">
            <h2 className="text-xl font-semibold sketch-heading mb-2">Admin interface unavailable</h2>
            <p className="text-sm text-slate-500">
              Core application scripts have not loaded yet. Please refresh the page.
            </p>
            <button
              onClick={onClose}
              className="mt-4 sketch-button sketch-button--secondary"
            >
              Close
            </button>
          </div>
        </div>
      );
    }

    const [activeTab, setActiveTab] = useState('overview');
    const [overviewData, setOverviewData] = useState(null);
    const [overviewLoading, setOverviewLoading] = useState(false);

    const [usersData, setUsersData] = useState({ users: [], total: 0, limit: 50, offset: 0 });
    const [usersLoading, setUsersLoading] = useState(false);
    const [userFilters, setUserFilters] = useState({ search: '', role: '', status: '' });
    const [selectedUserIds, setSelectedUserIds] = useState([]);
    const [showCreateModal, setShowCreateModal] = useState(false);
    const [editingUser, setEditingUser] = useState(null);
    const [resettingUser, setResettingUser] = useState(null);
    const [resetPasswordValue, setResetPasswordValue] = useState('');
    const [resetLoading, setResetLoading] = useState(false);
    const [userError, setUserError] = useState(null);

    const [healthData, setHealthData] = useState(null);
    const [healthLoading, setHealthLoading] = useState(false);

    const [auditData, setAuditData] = useState({ logs: [], limit: 200 });
    const [auditLoading, setAuditLoading] = useState(false);

    const fetchOverview = useCallback(async () => {
      try {
        setOverviewLoading(true);
        const result = await api.adminAnalyticsOverview(token);
        setOverviewData(result);
      } catch (error) {
        console.error('Failed to load admin overview', error);
      } finally {
        setOverviewLoading(false);
      }
    }, [token, api]);

    const fetchUsers = useCallback(async (overrides = {}) => {
      try {
        setUsersLoading(true);
        setUserError(null);
        const result = await api.adminListUsers(token, {
          ...userFilters,
          ...overrides,
        });
        if (result.error) {
          setUserError(result.error);
        } else {
          setUsersData(result);
        }
      } catch (error) {
        setUserError('Failed to load users');
      } finally {
        setUsersLoading(false);
      }
    }, [token, userFilters, api]);

    const fetchHealth = useCallback(async () => {
      try {
        setHealthLoading(true);
        const result = await api.adminHealth(token);
        setHealthData(result);
      } catch (error) {
        console.error('Failed to load health data', error);
      } finally {
        setHealthLoading(false);
      }
    }, [token, api]);

    const fetchAudit = useCallback(async () => {
      try {
        setAuditLoading(true);
        const result = await api.adminAuditLogs(token, auditData.limit);
        setAuditData(result);
      } catch (error) {
        console.error('Failed to load audit logs', error);
      } finally {
        setAuditLoading(false);
      }
    }, [token, auditData.limit, api]);

    useEffect(() => {
      fetchOverview();
      fetchUsers();
      fetchHealth();
      fetchAudit();
    }, [fetchOverview, fetchUsers, fetchHealth, fetchAudit]);

    usePolling(fetchHealth, 30000, [fetchHealth]);

    const handleCreateUser = async (form) => {
      try {
        const payload = { ...form };
        if (!payload.password) {
          payload.password = Math.random().toString(36).slice(2, 10);
        }
        const result = await api.adminCreateUser(token, payload);
        if (result.error) {
          alert(result.error);
          return;
        }
        setShowCreateModal(false);
        fetchUsers();
      } catch (error) {
        alert('Failed to create user');
      }
    };

    const handleUpdateUser = async (form) => {
      try {
        const payload = { ...form };
        if (!payload.password) {
          delete payload.password;
        }
        const result = await api.adminUpdateUser(token, editingUser.id, payload);
        if (result.error) {
          alert(result.error);
          return;
        }
        setEditingUser(null);
        fetchUsers();
      } catch (error) {
        alert('Failed to update user');
      }
    };

    const handleDeleteUser = async (target) => {
      if (!confirm(`Delete ${target.email}?`)) {
        return;
      }
      const result = await api.adminDeleteUser(token, target.id);
      if (result.error) {
        alert(result.error);
      } else {
        fetchUsers();
        setSelectedUserIds((prev) => prev.filter((id) => id !== target.id));
      }
    };

    const handleBulkAction = async (action, payload = {}) => {
      if (!selectedUserIds.length) {
        alert('Select at least one user');
        return;
      }
      const result = await api.adminBulkUsers(token, {
        action,
        ids: selectedUserIds,
        ...payload,
      });
      if (result.error) {
        alert(result.error);
      } else {
        fetchUsers();
        setSelectedUserIds([]);
      }
    };

    const handleExport = async (entity) => {
      try {
        const csv = await api.adminExport(token, entity);
        const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `${entity}-export-${Date.now()}.csv`;
        link.click();
        URL.revokeObjectURL(url);
      } catch (error) {
        alert('Failed to export data');
      }
    };

    const overviewCards = useMemo(() => {
      if (!overviewData?.overview) {
        return [];
      }
      const { overview, revenue } = overviewData;
      return [
        {
          icon: 'fa-users',
          label: 'Total Users',
          value: overview.total_users ?? 0,
        },
        {
          icon: 'fa-user-check',
          label: 'Active Users',
          value: overview.active_users ?? 0,
        },
        {
          icon: 'fa-calendar',
          label: 'Meetings',
          value: overview.total_meetings ?? 0,
        },
        {
          icon: 'fa-video',
          label: 'Recordings',
          value: overview.total_recordings ?? 0,
        },
        {
          icon: 'fa-file-alt',
          label: 'Transcripts',
          value: overview.total_transcripts ?? 0,
        },
        {
          icon: 'fa-dollar-sign',
          label: 'Revenue (all time)',
          value: `$${(overview.total_revenue ?? 0).toLocaleString()}`,
        },
      ];
    }, [overviewData]);

    return (
      <div className="fixed inset-0 sketch-overlay z-50 flex items-center justify-center p-6 sketch-admin">
        <div className="w-full max-w-6xl sketch-admin-shell">
          <div className="sketch-toolbar sketch-toolbar--header flex flex-col md:flex-row md:items-center md:justify-between gap-4 px-6 py-4">
            <div>
              <span className="sketch-tagline">Ops Intelligence • Edge Cohort</span>
              <h2 className="text-2xl font-bold sketch-heading">Admin Control Center</h2>
              <p className="text-sm text-slate-500">Manage users, monitor system health, and export mission-critical data.</p>
            </div>
            <button
              onClick={onClose}
              className="sketch-icon-button"
              title="Close admin dashboard"
            >
              <i className="fas fa-times"></i>
            </button>
          </div>

          <div className="px-6 pt-4">
            <div className="flex gap-2 overflow-auto pb-2">
              {ADMIN_TABS.map((tab) => (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  className={`px-4 py-2 rounded-lg text-sm font-medium ${
                    activeTab === tab.id
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
                  }`}
                >
                  {tab.label}
                </button>
              ))}
            </div>
          </div>

          <div className="max-h-[75vh] overflow-y-auto px-6 py-4 space-y-6">
            {activeTab === 'overview' && (
              <>
                {overviewLoading ? (
                  <div className="text-center py-12 text-gray-400">
                    <i className="fas fa-spinner fa-spin text-3xl"></i>
                  </div>
                ) : (
                  <>
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                      {overviewCards.map((card) => (
                        <StatCard key={card.label} {...card} />
                      ))}
                    </div>
                    {overviewData?.overview?.recent_users?.length > 0 && (
                      <SectionCard
                        title="Newly onboarded users"
                        description="Latest accounts created on the platform"
                      >
                        <div className="grid md:grid-cols-2 gap-4">
                          {overviewData.overview.recent_users.map((recent) => (
                            <div key={recent.id} className="bg-gray-900 border border-gray-800 rounded-lg p-4">
                              <div className="text-white font-medium">{recent.name}</div>
                              <div className="text-sm text-gray-400">{recent.email}</div>
                              <div className="text-xs uppercase tracking-wide text-blue-300 mt-2">{recent.role}</div>
                              <div className="text-xs text-gray-500 mt-1">
                                Created {new Date(recent.created_at).toLocaleString()}
                              </div>
                            </div>
                          ))}
                        </div>
                      </SectionCard>
                    )}
                  </>
                )}
              </>
            )}

            {activeTab === 'users' && (
              <SectionCard
                title="User Management"
                description="Create, update, suspend, or delete platform accounts."
                actions={(
                  <div className="flex flex-wrap gap-2">
                    <button
                      onClick={() => setShowCreateModal(true)}
                      className="px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded"
                    >
                      <i className="fas fa-plus mr-2"></i>Create user
                    </button>
                    <button
                      onClick={() => handleBulkAction('set-role', { role: 'host' })}
                      className="px-4 py-2 bg-gray-800 hover:bg-gray-700 rounded text-sm"
                    >
                      Set as host
                    </button>
                    <button
                      onClick={() => handleBulkAction('set-status', { status: 'suspended' })}
                      className="px-4 py-2 bg-yellow-800 hover:bg-yellow-700 rounded text-sm"
                    >
                      Suspend
                    </button>
                    <button
                      onClick={() => handleBulkAction('delete')}
                      className="px-4 py-2 bg-red-600 hover:bg-red-700 rounded text-sm"
                    >
                      Delete
                    </button>
                  </div>
                )}
              >
                <div className="grid md:grid-cols-4 gap-4 mb-4">
                  <input
                    type="text"
                    placeholder="Search name or email"
                    value={userFilters.search}
                    onChange={(e) => setUserFilters((prev) => ({ ...prev, search: e.target.value }))}
                    className="px-3 py-2 bg-gray-800 border border-gray-700 rounded"
                  />
                  <select
                    value={userFilters.role}
                    onChange={(e) => setUserFilters((prev) => ({ ...prev, role: e.target.value }))}
                    className="px-3 py-2 bg-gray-800 border border-gray-700 rounded"
                  >
                    <option value="">Role: Any</option>
                    {ROLE_OPTIONS.map((option) => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                  <select
                    value={userFilters.status}
                    onChange={(e) => setUserFilters((prev) => ({ ...prev, status: e.target.value }))}
                    className="px-3 py-2 bg-gray-800 border border-gray-700 rounded"
                  >
                    <option value="">Status: Any</option>
                    {STATUS_OPTIONS.map((option) => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                  <button
                    onClick={() => fetchUsers()}
                    className="px-3 py-2 bg-gray-800 hover:bg-gray-700 rounded"
                  >
                    Apply filters
                  </button>
                </div>

                {userError && (
                  <div className="p-3 bg-red-900 text-red-100 rounded mb-4">{userError}</div>
                )}

                {usersLoading ? (
                  <div className="text-center py-12 text-gray-400">
                    <i className="fas fa-spinner fa-spin text-2xl"></i>
                  </div>
                ) : (
                  <UsersTable
                    users={usersData.users}
                    selectedIds={selectedUserIds}
                    toggleSelect={(ids) => setSelectedUserIds(ids)}
                    onEdit={(target) => setEditingUser(target)}
                    onReset={(target) => { setResettingUser(target); setResetPasswordValue(''); }}
                    onDelete={handleDeleteUser}
                  />
                )}

                <div className="mt-4 flex items-center justify-between text-sm text-gray-500">
                  <span>
                    Showing {usersData.users.length} of {usersData.total} users
                  </span>
                  {selectedUserIds.length > 0 && (
                    <span>{selectedUserIds.length} selected</span>
                  )}
                </div>

                {showCreateModal && (
                  <div className="fixed inset-0 sketch-overlay flex items-center justify-center z-50">
                    <div className="sketch-modal w-full max-w-lg p-6">
                      <h3 className="text-xl font-semibold sketch-heading mb-4">Create new user</h3>
                      <UserForm
                        onSubmit={handleCreateUser}
                        onCancel={() => setShowCreateModal(false)}
                        submitLabel="Create user"
                      />
                    </div>
                  </div>
                )}

                {editingUser && (
                  <div className="fixed inset-0 sketch-overlay flex items-center justify-center z-50">
                    <div className="sketch-modal w-full max-w-lg p-6">
                      <h3 className="text-xl font-semibold sketch-heading mb-4">Edit user</h3>
                      <UserForm
                        initialValues={editingUser}
                        onSubmit={handleUpdateUser}
                        onCancel={() => setEditingUser(null)}
                        submitLabel="Save changes"
                      />
                    </div>
                  </div>
                )}

                {resettingUser && (
                  <div className="fixed inset-0 sketch-overlay flex items-center justify-center z-50">
                    <div className="sketch-modal w-full max-w-md p-6">
                      <h3 className="text-xl font-semibold sketch-heading mb-4">Reset password for {resettingUser.email}</h3>
                      <div className="space-y-4">
                        <div>
                          <label className="block text-sm text-gray-300 mb-1">New password</label>
                          <input
                            type="password"
                            value={resetPasswordValue}
                            onChange={(e) => setResetPasswordValue(e.target.value)}
                            className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded"
                            placeholder="Enter a new password (min 8 chars)"
                          />
                        </div>
                        <div className="flex justify-between">
                          <button
                            onClick={() => {
                              // generate random temporary password
                              const pw = Math.random().toString(36).slice(2, 10) + 'A1!';
                              setResetPasswordValue(pw);
                            }}
                            className="px-3 py-2 bg-gray-700 hover:bg-gray-600 rounded"
                          >
                            Generate
                          </button>
                          <div className="space-x-2">
                            <button
                              onClick={() => { setResettingUser(null); setResetPasswordValue(''); }}
                              className="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded"
                            >
                              Cancel
                            </button>
                            <button
                              onClick={async () => {
                                if (!resetPasswordValue || resetPasswordValue.length < 8) {
                                  alert('Password must be at least 8 characters');
                                  return;
                                }
                                try {
                                  setResetLoading(true);
                                  const result = await api.adminResetPassword(token, resettingUser.id, { password: resetPasswordValue });
                                  if (result.error) {
                                    alert(result.error);
                                  } else {
                                    alert('Password reset successfully');
                                    setResettingUser(null);
                                    setResetPasswordValue('');
                                    fetchUsers();
                                  }
                                } catch (err) {
                                  alert('Failed to reset password');
                                } finally {
                                  setResetLoading(false);
                                }
                              }}
                              className="px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded"
                              disabled={resetLoading}
                            >
                              {resetLoading ? 'Resetting…' : 'Reset password'}
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </SectionCard>
            )}

            {activeTab === 'health' && (
              <SectionCard
                title="Real-time system health"
                description="Live status checks, error spikes, and triggered alerts."
                actions={
                  <button
                    onClick={fetchHealth}
                    className="px-4 py-2 bg-gray-800 hover:bg-gray-700 rounded"
                  >
                    <i className="fas fa-sync mr-2"></i>Refresh
                  </button>
                }
              >
                {healthLoading ? (
                  <div className="text-center py-10 text-gray-400">
                    <i className="fas fa-spinner fa-spin text-2xl"></i>
                  </div>
                ) : (
                  <div className="grid lg:grid-cols-3 gap-4">
                    <div className="lg:col-span-1">
                      <h4 className="text-white font-semibold mb-2 flex items-center">
                        <i className="fas fa-heartbeat text-red-400 mr-2"></i> Health checks
                      </h4>
                      <div className="space-y-3 max-h-80 overflow-auto pr-2">
                        {(healthData?.health_logs || []).map((log, index) => (
                          <div key={index} className="bg-gray-900 border border-gray-800 rounded-lg p-3">
                            <div className="flex justify-between text-sm">
                              <span className="text-white font-medium">{log.component}</span>
                              <span
                                className={`text-xs uppercase tracking-wide ${
                                  log.status === 'healthy'
                                    ? 'text-green-400'
                                    : log.status === 'degraded'
                                    ? 'text-yellow-400'
                                    : 'text-red-400'
                                }`}
                              >
                                {log.status}
                              </span>
                            </div>
                            <div className="text-xs text-gray-500 mt-1">
                              {new Date(log.timestamp).toLocaleTimeString()} • {log.response_time_ms}ms
                            </div>
                            {log.error_message && (
                              <div className="text-xs text-red-300 mt-2">{log.error_message}</div>
                            )}
                          </div>
                        ))}
                      </div>
                    </div>
                    <div className="lg:col-span-1">
                      <h4 className="text-white font-semibold mb-2 flex items-center">
                        <i className="fas fa-exclamation-triangle text-yellow-400 mr-2"></i> Recent errors
                      </h4>
                      <div className="space-y-3 max-h-80 overflow-auto pr-2">
                        {(healthData?.errors || []).map((issue, index) => (
                          <div key={index} className="bg-gray-900 border border-gray-800 rounded-lg p-3">
                            <div className="text-xs uppercase tracking-wide text-red-400">
                              {issue.severity} • {issue.category}
                            </div>
                            <div className="text-white text-sm mt-1 truncate">{issue.message}</div>
                            <div className="text-xs text-gray-500 mt-1">
                              {new Date(issue.timestamp).toLocaleString()}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                    <div className="lg:col-span-1">
                      <h4 className="text-white font-semibold mb-2 flex items-center">
                        <i className="fas fa-bell text-blue-400 mr-2"></i> Alerts pipeline
                      </h4>
                      <div className="space-y-3 max-h-80 overflow-auto pr-2">
                        {(healthData?.alerts || []).map((alert, index) => (
                          <div key={index} className="bg-gray-900 border border-gray-800 rounded-lg p-3">
                            <div className="flex justify-between text-sm">
                              <span className="text-white font-medium">{alert.title}</span>
                              <span className="text-xs uppercase tracking-wide text-purple-300">
                                {alert.severity}
                              </span>
                            </div>
                            <div className="text-xs text-gray-500 mt-1">
                              {alert.alert_type} • {alert.status}
                            </div>
                            <div className="text-xs text-gray-400 mt-1">
                              {new Date(alert.timestamp).toLocaleString()}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                )}
              </SectionCard>
            )}

            {activeTab === 'audit' && (
              <SectionCard
                title="Audit trail"
                description="Immutable record of privileged activity across the platform."
                actions={
                  <button
                    onClick={fetchAudit}
                    className="px-4 py-2 bg-gray-800 hover:bg-gray-700 rounded"
                  >
                    Refresh
                  </button>
                }
              >
                {auditLoading ? (
                  <div className="text-center py-10 text-gray-400">
                    <i className="fas fa-spinner fa-spin text-2xl"></i>
                  </div>
                ) : (
                  <div className="space-y-3 max-h-96 overflow-auto">
                    {(auditData?.logs || []).map((log) => (
                      <div key={log.id} className="bg-gray-900 border border-gray-800 rounded-lg p-4">
                        <div className="flex justify-between text-sm text-gray-400">
                          <span>{new Date(log.created_at).toLocaleString()}</span>
                          <span className="text-xs uppercase text-blue-300">{log.action}</span>
                        </div>
                        <div className="mt-2 text-white text-sm">
                          {log.actor_email || 'System'} → {log.entity_type} {log.entity_id || ''}
                        </div>
                        {log.details && (
                          <pre className="mt-2 bg-gray-950 border border-gray-800 rounded p-2 text-xs text-gray-400 overflow-auto">
                            {(() => {
                              try {
                                return JSON.stringify(JSON.parse(log.details), null, 2);
                              } catch (error) {
                                return String(log.details);
                              }
                            })()}
                          </pre>
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </SectionCard>
            )}

            {activeTab === 'export' && (
              <SectionCard
                title="Data export"
                description="Generate CSV snapshots for compliance, retention, and BI pipelines."
              >
                <div className="grid sm:grid-cols-2 gap-4">
                  {[
                    { entity: 'users', icon: 'fa-users', label: 'Users' },
                    { entity: 'meetings', icon: 'fa-calendar', label: 'Meetings' },
                    { entity: 'recordings', icon: 'fa-video', label: 'Recordings' },
                    { entity: 'transcripts', icon: 'fa-file-alt', label: 'Transcripts' },
                  ].map((item) => (
                    <div key={item.entity} className="bg-gray-900 border border-gray-800 rounded-lg p-4 flex items-center justify-between">
                      <div>
                        <div className="text-white font-semibold">{item.label}</div>
                        <div className="text-xs text-gray-400 mt-1">
                          CSV export with structured metadata
                        </div>
                      </div>
                      <button
                        onClick={() => handleExport(item.entity)}
                        className="px-3 py-2 bg-blue-600 hover:bg-blue-700 rounded text-sm"
                      >
                        <i className={`fas ${item.icon} mr-2`}></i>
                        Export
                      </button>
                    </div>
                  ))}
                </div>
              </SectionCard>
            )}
          </div>
        </div>
      </div>
    );
  }

  window.AdminDashboard = AdminDashboard;
})();
