
// AdminDashboard.jsx — Master control: commission, listings, user verification, alert banners

const ALL_LISTINGS = [
  { id: 1, name: 'Box Dental Premium', owner: 'Clínica Sonrisa', location: 'Las Condes', price: 8500, status: 'active', verified: true },
  { id: 2, name: 'Box Kinesiología', owner: 'Centro Rehabilita', location: 'Providencia', price: 6000, status: 'active', verified: true },
  { id: 3, name: 'Box Psicología', owner: 'Espacio Mental', location: 'Ñuñoa', price: 4500, status: 'pending', verified: false },
  { id: 4, name: 'Box Medicina General', owner: 'MedCenter SpA', location: 'Santiago Centro', price: 5500, status: 'active', verified: true },
  { id: 5, name: 'Box Dermatología', owner: 'DermaClínica', location: 'Vitacura', price: 12000, status: 'suspended', verified: true },
];

const ALL_USERS = [
  { id: 1, name: 'Dr. Carlos Muñoz', rut: '12.345.678-9', role: 'professional', specialty: 'Odontología', sisStatus: 'verified', email: 'cmunoz@mail.cl' },
  { id: 2, name: 'Dra. Ana Torres', rut: '9.876.543-2', role: 'professional', specialty: 'Kinesiología', sisStatus: 'pending', email: 'atorres@mail.cl' },
  { id: 3, name: 'Clínica Sonrisa', rut: '76.123.456-7', role: 'owner', specialty: '—', sisStatus: 'verified', email: 'admin@sonrisa.cl' },
  { id: 4, name: 'Dr. Pedro Soto', rut: '15.432.109-K', role: 'professional', specialty: 'Psicología', sisStatus: 'rejected', email: 'psoto@mail.cl' },
];

const AdminDashboard = ({ onBack, onNavigate }) => {
  const [tab, setTab] = React.useState('overview'); // overview | listings | users | alerts
  const isMobile = useWindowWidth() <= 768;
  const [commission, setCommission] = React.useState(10);
  const [editingCommission, setEditingCommission] = React.useState(false);
  const [commissionDraft, setCommissionDraft] = React.useState(10);
  const [listings, setListings] = React.useState(ALL_LISTINGS);
  const [users, setUsers] = React.useState(ALL_USERS);
  const [alerts, setAlerts] = React.useState([
    { id: 1, text: 'Mantenimiento programado el 10 de mayo de 9:00–11:00 hrs.', active: true, type: 'warning' },
  ]);
  const [alertDraft, setAlertDraft] = React.useState('');
  const [alertType, setAlertType] = React.useState('info');
  const [deleteConfirm, setDeleteConfirm] = React.useState(null);

  // Backend stats
  const [stats, setStats] = React.useState(null);
  const [statsLoading, setStatsLoading] = React.useState(false);
  const [statsError, setStatsError] = React.useState(null);

  // Backend users and boxes
  const [adminUsers, setAdminUsers] = React.useState([]);
  const [adminBoxes, setAdminBoxes] = React.useState([]);
  const [adminUsersLoading, setAdminUsersLoading] = React.useState(false);
  const [adminBoxesLoading, setAdminBoxesLoading] = React.useState(false);

  // Edit modals and selections
  const [editingListing, setEditingListing] = React.useState(null);
  const [editingListingDraft, setEditingListingDraft] = React.useState(null);
  const [editingUser, setEditingUser] = React.useState(null);
  const [editingUserDraft, setEditingUserDraft] = React.useState(null);
  const [selectedListingIds, setSelectedListingIds] = React.useState([]);
  const [selectedUserIds, setSelectedUserIds] = React.useState([]);
  const [successMessage, setSuccessMessage] = React.useState(null);
  const [tempPassword, setTempPassword] = React.useState(null);
  const [passwordCopied, setPasswordCopied] = React.useState(false);
  const [resetPasswordLoading, setResetPasswordLoading] = React.useState(false);

  // Search filters
  const [professionalSearch, setProfessionalSearch] = React.useState('');
  const [ownerSearch, setOwnerSearch] = React.useState('');
  const [listingsSearch, setListingsSearch] = React.useState('');

  // System operations
  const [resetRateLimitLoading, setResetRateLimitLoading] = React.useState(false);

  // Create user modal
  const [showCreateUser, setShowCreateUser] = React.useState(false);
  const [createForm, setCreateForm] = React.useState({ full_name: '', email: '', password: '', phone: '', role: 'professional', specialty: '' });
  const [createErrors, setCreateErrors] = React.useState({});
  const [createLoading, setCreateLoading] = React.useState(false);

  // Authentication guard: Check on mount
  React.useEffect(() => {
    const token = localStorage.getItem('lokat_token');
    const userJson = localStorage.getItem('lokat_user');
    const parsedUser = userJson ? JSON.parse(userJson) : null;

    // Redirect if no token or role is not admin / admin_limited
    if (!token || !parsedUser || (parsedUser.role !== 'admin' && parsedUser.role !== 'admin_limited')) {
      console.log('🔐 Admin access denied. Redirecting to login.');
      onNavigate('auth', { defaultRole: 'admin' });
    }
  }, [onNavigate]);

  // Fetch admin stats on mount
  React.useEffect(() => {
    const fetchStats = async () => {
      try {
        setStatsLoading(true);
        const token = localStorage.getItem('lokat_token');
        if (!token) {
          throw new Error('No token found');
        }

        console.log('📊 Fetching admin stats...');
        const response = await fetchWithAuth('https://lokat.fly.dev/api/admin/stats', {});

        if (!response.ok) {
          throw new Error(`Failed to fetch stats: ${response.status}`);
        }

        const data = await response.json();
        console.log('✅ Admin stats fetched:', data);
        setStats(data);
        setStatsError(null);
      } catch (error) {
        if (error.sessionExpired) return;
        console.error('❌ Error fetching admin stats:', error);
        setStatsError(error.message);
      } finally {
        setStatsLoading(false);
      }
    };

    fetchStats();
  }, []);

  // Fetch admin users — extracted so it can be called on mount AND after create
  const fetchUsers = React.useCallback(async () => {
    try {
      setAdminUsersLoading(true);
      const token = localStorage.getItem('lokat_token');
      console.log('👥 [FETCH_USERS] Starting fetch... Token present:', !!token);
      if (!token) { console.warn('👥 [FETCH_USERS] No token — skipping'); return; }

      const response = await fetchWithAuth('https://lokat.fly.dev/api/admin/users', {});
      console.log('👥 [FETCH_USERS] Response:', response.status, response.ok);
      if (!response.ok) throw new Error(`Failed to fetch users: ${response.status} ${response.statusText}`);

      const data = await response.json();
      console.log('✅ [FETCH_USERS]', data?.length || 0, 'users fetched');
      setAdminUsers(data || []);
    } catch (error) {
      console.error('❌ [FETCH_USERS]', error?.message);
    } finally {
      setAdminUsersLoading(false);
    }
  }, []);

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

  // Fetch admin boxes on mount
  React.useEffect(() => {
    const fetchBoxes = async () => {
      try {
        setAdminBoxesLoading(true);
        const token = localStorage.getItem('lokat_token');
        if (!token) return;

        console.log('📦 Fetching admin boxes...');
        const response = await fetchWithAuth('https://lokat.fly.dev/api/admin/boxes', {});

        if (!response.ok) throw new Error('Failed to fetch boxes');

        const data = await response.json();
        console.log('✅ Admin boxes fetched:', data);
        setAdminBoxes(data || []);
      } catch (error) {
        console.error('❌ Error fetching admin boxes:', error);
      } finally {
        setAdminBoxesLoading(false);
      }
    };

    fetchBoxes();
  }, []);

  const TABS = [
    { id: 'overview', label: 'Resumen' },
    { id: 'listings', label: 'Listings' },
    { id: 'users', label: 'Usuarios' },
    { id: 'alerts', label: 'Alertas' },
  ];

  // ─── EDIT LISTING ───
  const openEditListing = (box) => {
    setEditingListing(box);
    setEditingListingDraft({
      name: box.name,
      price_per_slot: box.price_per_slot,
      location: box.location || '',
      status: box.status || 'open',
      verified: box.verified || false,
    });
  };

  const saveListing = () => {
    if (!editingListingDraft.name.trim()) {
      alert('El nombre del box es requerido');
      return;
    }
    setAdminBoxes(prev => prev.map(b => b.id === editingListing.id
      ? { ...b, ...editingListingDraft }
      : b
    ));
    setEditingListing(null);
    setEditingListingDraft(null);
    setSuccessMessage('Listing actualizado exitosamente');
    setTimeout(() => setSuccessMessage(null), 3000);
  };

  // ─── EDIT USER ───
  const openEditUser = (user) => {
    console.log('════════════════════════════════════════════════════════════════');
    console.log('👤 [EDIT_USER] Opening edit modal for user:');
    console.log('  - ID:', user.id);
    console.log('  - ID type:', typeof user.id);
    console.log('  - ID is valid:', !!user.id);
    console.log('  - Email:', user.email);
    console.log('  - Name:', user.full_name || user.email);
    console.log('  - Role:', user.role);
    console.log('  - Specialty:', user.specialty || 'N/A');
    console.log('  - Full user object:', user);
    console.log('════════════════════════════════════════════════════════════════');

    setEditingUser(user);
    console.log('👤 [EDIT_USER] editingUser state set');

    // NOTE: sisStatus does NOT come from backend database - it's UI-only state
    // In production, this should be persisted to database if needed
    // For now, default to 'pending' for all users
    setEditingUserDraft({
      full_name: user.full_name || user.email,
      email: user.email,
      phone: user.phone || '',
      role: user.role,
      specialty: user.specialty || '',
      sisStatus: 'pending', // Default value - sisStatus doesn't exist in database yet
    });
    console.log('👤 [EDIT_USER] editingUserDraft state set (sisStatus defaulted to pending, phone initialized)');
    console.log('  - Phone:', user.phone || 'N/A');

    // Also clear the temp password when opening a new user
    setTempPassword(null);
    setPasswordCopied(false);
    console.log('👤 [EDIT_USER] Cleared previous temp password');
  };

  const saveUser = () => {
    if (!editingUserDraft.full_name.trim()) {
      alert('El nombre es requerido');
      return;
    }
    setAdminUsers(prev => prev.map(u => u.id === editingUser.id
      ? { ...u, ...editingUserDraft }
      : u
    ));
    setEditingUser(null);
    setEditingUserDraft(null);
    setSuccessMessage('Usuario actualizado exitosamente');
    setTimeout(() => setSuccessMessage(null), 3000);
  };

  // ─── LISTING SELECTIONS & BULK ACTIONS ───
  const toggleListingSelection = (id) => {
    setSelectedListingIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  };

  const bulkActivateListings = () => {
    setAdminBoxes(prev => prev.map(b => selectedListingIds.includes(b.id) ? { ...b, status: 'open' } : b));
    setSelectedListingIds([]);
    setSuccessMessage(`${selectedListingIds.length} listing(s) activado(s)`);
    setTimeout(() => setSuccessMessage(null), 3000);
  };

  const bulkSuspendListings = () => {
    setAdminBoxes(prev => prev.map(b => selectedListingIds.includes(b.id) ? { ...b, status: 'closed' } : b));
    setSelectedListingIds([]);
    setSuccessMessage(`${selectedListingIds.length} listing(s) suspendido(s)`);
    setTimeout(() => setSuccessMessage(null), 3000);
  };

  const bulkDeleteListings = () => {
    if (!window.confirm(`¿Está seguro que desea eliminar ${selectedListingIds.length} listing(s)?`)) return;
    setAdminBoxes(prev => prev.filter(b => !selectedListingIds.includes(b.id)));
    setSelectedListingIds([]);
    setSuccessMessage(`${selectedListingIds.length} listing(s) eliminado(s)`);
    setTimeout(() => setSuccessMessage(null), 3000);
  };

  // ─── USER SELECTIONS & BULK ACTIONS ───
  const toggleUserSelection = (id) => {
    setSelectedUserIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  };

  const bulkVerifyUsers = () => {
    console.warn('⚠️ [BULK_VERIFY] sisStatus is UI-only state - NOT persisted to database');
    setAdminUsers(prev => prev.map(u => selectedUserIds.includes(u.id) ? { ...u, sisStatus: 'verified' } : u));
    setSelectedUserIds([]);
    setSuccessMessage(`${selectedUserIds.length} usuario(s) verificado(s)`);
    setTimeout(() => setSuccessMessage(null), 3000);
  };

  const bulkRejectUsers = () => {
    console.warn('⚠️ [BULK_REJECT] sisStatus is UI-only state - NOT persisted to database');
    setAdminUsers(prev => prev.map(u => selectedUserIds.includes(u.id) ? { ...u, sisStatus: 'rejected' } : u));
    setSelectedUserIds([]);
    setSuccessMessage(`${selectedUserIds.length} usuario(s) rechazado(s)`);
    setTimeout(() => setSuccessMessage(null), 3000);
  };

  const bulkDeleteUsers = async () => {
    if (!window.confirm(`¿Está seguro que desea eliminar ${selectedUserIds.length} usuario(s)? Esta acción es irreversible.`)) return;
    const token = localStorage.getItem('lokat_token');
    let deleted = 0;
    let failed = 0;
    for (const uid of selectedUserIds) {
      try {
        const res = await fetch(`https://lokat.fly.dev/api/admin/users/${uid}`, {
          method: 'DELETE',
          headers: { Authorization: `Bearer ${token}` },
        });
        if (res.ok) {
          deleted++;
        } else {
          const body = await res.json().catch(() => ({}));
          console.error(`❌ [DELETE_USER] Failed for ${uid}:`, body.error);
          failed++;
        }
      } catch (err) {
        console.error(`❌ [DELETE_USER] Network error for ${uid}:`, err.message);
        failed++;
      }
    }
    setAdminUsers(prev => prev.filter(u => !selectedUserIds.includes(u.id)));
    setSelectedUserIds([]);
    const msg = failed > 0
      ? `${deleted} usuario(s) eliminado(s), ${failed} error(es)`
      : `${deleted} usuario(s) eliminado(s)`;
    setSuccessMessage(msg);
    setTimeout(() => setSuccessMessage(null), 3000);
  };

  // ─── PASSWORD RESET ───
  const generateTempPassword = () => {
    console.log('🔐 [GENERATE_TEMP] Generating temporary password...');
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let password = '';
    for (let i = 0; i < 10; i++) {
      password += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    console.log('🔐 [GENERATE_TEMP] Password generated, length:', password.length);
    console.log('🔐 [GENERATE_TEMP] Password preview:', password.substring(0, 3) + '***' + password.substring(password.length - 2));
    setTempPassword(password);
    setPasswordCopied(false);
    console.log('✅ [GENERATE_TEMP] State updated with new password');
  };

  const copyPasswordToClipboard = () => {
    console.log('📋 [COPY_PASSWORD] Copy button clicked');
    console.log('📋 [COPY_PASSWORD] Current tempPassword state:', tempPassword ? `[${tempPassword.length} chars]` : 'EMPTY');

    if (!tempPassword) {
      console.error('❌ [COPY_PASSWORD] No password to copy!');
      alert('No password generated yet');
      return;
    }

    navigator.clipboard.writeText(tempPassword);
    console.log('✅ [COPY_PASSWORD] Password copied to clipboard');
    setPasswordCopied(true);
    setTimeout(() => {
      setPasswordCopied(false);
      console.log('📋 [COPY_PASSWORD] Copied feedback cleared after 2s');
    }, 2000);
  };

  const sendTempPasswordEmail = async () => {
    // FIRST LINE: Log everything at the start
    console.log('SEND START', { tempPassword: tempPassword, userId: editingUser?.id, userEmail: editingUser?.email });

    // Guard: Check if temp password is set
    if (!tempPassword) {
      console.error('❌ [SEND_TEMP_PASSWORD] No temp password generated');
      alert('Genera una contraseña primero');
      return;
    }

    // Guard: Check if user is selected
    if (!editingUser) {
      console.error('❌ [SEND_TEMP_PASSWORD] No user selected');
      alert('Error: No user selected');
      return;
    }

    // Guard: Check if user has an ID
    if (!editingUser.id) {
      console.error('❌ [SEND_TEMP_PASSWORD] User has no ID');
      alert('Error: User ID is missing');
      return;
    }

    console.log('✅ [SEND_TEMP_PASSWORD] All guards passed. Proceeding with send...');
    setResetPasswordLoading(true);
    try {
      const token = localStorage.getItem('lokat_token');
      const url = `https://lokat.fly.dev/api/admin/users/${editingUser.id}/send-temp-password`;

      // Prepare request body
      const requestBody = { tempPassword };
      const requestBodyJSON = JSON.stringify(requestBody);

      console.log('🔐 [SEND_TEMP_PASSWORD] Initiating email send:');
      console.log('  - userId:', editingUser.id);
      console.log('  - userEmail:', editingUser.email);
      console.log('  - URL:', url);
      console.log('  - Token present:', !!token);
      console.log('  - Temp password length:', tempPassword.length);
      console.log('🔐 [SEND_TEMP_PASSWORD] Request body details:');
      console.log('  - Body object:', requestBody);
      console.log('  - JSON string:', requestBodyJSON);
      console.log('  - Field name:', 'tempPassword');
      console.log('  - Field value length:', requestBody.tempPassword.length);
      console.log('🔐 [SEND_TEMP_PASSWORD] Request headers:');
      console.log('  - Content-Type: application/json');

      const response = await fetchWithAuth(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: requestBodyJSON,
      });

      console.log('════════════════════════════════════════════════════════════════');
      console.log('🔐 [SEND_TEMP_PASSWORD] Response received:');
      console.log('  - Status:', response.status);
      console.log('  - Status text:', response.statusText);
      console.log('  - Ok:', response.ok);
      console.log('  - Content-Type:', response.headers.get('content-type'));
      console.log('════════════════════════════════════════════════════════════════');

      if (!response.ok) {
        throw new Error('Failed to send temporary password');
      }

      const data = await response.json();
      setSuccessMessage(`Contraseña enviada a ${data.email}`);
      setTimeout(() => setSuccessMessage(null), 3000);
      setTempPassword(null);
      setPasswordCopied(false);
    } catch (error) {
      console.error('❌ Error sending temp password:', error);
      setSuccessMessage(`❌ Error: ${error.message}`);
      setTimeout(() => setSuccessMessage(null), 3000);
    } finally {
      setResetPasswordLoading(false);
    }
  };

  const bulkResetPasswords = async () => {
    if (selectedUserIds.length === 0) return;

    setResetPasswordLoading(true);
    let successCount = 0;
    let failureCount = 0;

    for (const userId of selectedUserIds) {
      try {
        const token = localStorage.getItem('lokat_token');
        const response = await fetchWithAuth(`https://lokat.fly.dev/api/admin/users/${userId}/reset-password`, {
          method: 'POST',
        });

        if (response.ok) {
          successCount++;
        } else {
          failureCount++;
        }
      } catch (error) {
        console.error('❌ Error resetting password for user:', userId, error);
        failureCount++;
      }
    }

    setResetPasswordLoading(false);
    setSelectedUserIds([]);

    if (successCount > 0) {
      setSuccessMessage(`${successCount} correo(s) de restablecimiento enviado(s)`);
      setTimeout(() => setSuccessMessage(null), 3000);
    }
    if (failureCount > 0) {
      setSuccessMessage(`⚠️ ${failureCount} error(es) al enviar correos`);
      setTimeout(() => setSuccessMessage(null), 3000);
    }
  };

  const resetRateLimiter = async () => {
    console.log('🔄 [RESET_RATE_LIMIT] Admin initiated rate limit reset');
    setResetRateLimitLoading(true);
    try {
      const response = await fetchWithAuth('https://lokat.fly.dev/api/admin/reset-rate-limit', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error('Failed to reset rate limit');
      }

      const data = await response.json();
      console.log('✅ [RESET_RATE_LIMIT] Rate limit reset successfully:', data);
      setSuccessMessage('🔄 Rate limiter reseteado exitosamente');
      setTimeout(() => setSuccessMessage(null), 3000);
    } catch (error) {
      console.error('❌ Error resetting rate limit:', error);
      setSuccessMessage(`❌ Error: ${error.message}`);
      setTimeout(() => setSuccessMessage(null), 3000);
    } finally {
      setResetRateLimitLoading(false);
    }
  };

  // ─── CREATE USER ───
  const CU_PREFIX = '+56 9 ';

  const handleCreatePhoneFocus = () => {
    if (!createForm.phone) setCreateForm(p => ({...p, phone: CU_PREFIX}));
  };

  const handleCreatePhoneChange = (e) => {
    const raw = e.target.value;
    if (!raw.startsWith(CU_PREFIX)) { setCreateForm(p => ({...p, phone: CU_PREFIX})); return; }
    const digits = raw.slice(CU_PREFIX.length).replace(/\D/g, '').slice(0, 8);
    const formatted = digits.length > 4 ? digits.slice(0, 4) + ' ' + digits.slice(4) : digits;
    setCreateForm(p => ({...p, phone: CU_PREFIX + formatted}));
    setCreateErrors(p => ({...p, phone: undefined}));
  };

  const handleCreateUser = async () => {
    const e = {};
    if (!createForm.full_name.trim()) e.full_name = 'Requerido';
    if (!createForm.email.includes('@')) e.email = 'Email inválido';
    if (createForm.password.length < 6) e.password = 'Mínimo 6 caracteres';
    if (createForm.phone && createForm.phone !== CU_PREFIX && !/^\+56 9 \d{4} \d{4}$/.test(createForm.phone)) {
      e.phone = 'Formato inválido: +56 9 XXXX XXXX';
    }
    if (Object.keys(e).length) { setCreateErrors(e); return; }

    setCreateLoading(true);
    setCreateErrors({});
    try {
      const payload = {
        full_name: createForm.full_name.trim(),
        email: createForm.email.trim(),
        password: createForm.password,
        role: createForm.role,
        phone: (createForm.phone && createForm.phone !== CU_PREFIX) ? createForm.phone : undefined,
        specialty: (createForm.role === 'professional' && createForm.specialty) ? createForm.specialty : undefined,
      };

      const response = await fetchWithAuth('https://lokat.fly.dev/api/admin/users/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const data = await response.json();
      if (!response.ok) {
        setCreateErrors({ submit: data.error || 'Error al crear usuario' });
        return;
      }

      // Refresh list from backend so new user appears with full data
      await fetchUsers();
      setShowCreateUser(false);
      setCreateForm({ full_name: '', email: '', password: '', phone: '', role: 'professional', specialty: '' });
      setCreateErrors({});
      setSuccessMessage(`✅ Usuario ${data.full_name} creado exitosamente`);
      setTimeout(() => setSuccessMessage(null), 4000);
    } catch (err) {
      setCreateErrors({ submit: 'Error de conexión. Intenta de nuevo.' });
    } finally {
      setCreateLoading(false);
    }
  };

  const handleDeleteListing = (id) => {
    setListings(prev => prev.filter(l => l.id !== id));
    setDeleteConfirm(null);
  };

  const handleToggleListingStatus = (id) => {
    setListings(prev => prev.map(l => l.id === id
      ? { ...l, status: l.status === 'active' ? 'suspended' : 'active' }
      : l
    ));
  };

  const handleUserVerification = (id, status) => {
    setUsers(prev => prev.map(u => u.id === id ? { ...u, sisStatus: status } : u));
  };

  const handleAddAlert = () => {
    if (!alertDraft.trim()) return;
    setAlerts(prev => [...prev, { id: Date.now(), text: alertDraft, active: true, type: alertType }]);
    setAlertDraft('');
  };

  const saveCommission = () => {
    setCommission(commissionDraft);
    setEditingCommission(false);
  };

  const activeAlerts = alerts.filter(a => a.active).length;

  return (
    <div style={adStyles.page}>
      {/* TOP BAR */}
      <div style={adStyles.topBar}>
        <button style={adStyles.backBtn} onClick={onBack}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m15 18-6-6 6-6"/></svg>
        </button>
        <div style={adStyles.topBarInfo}>
          <div style={adStyles.topBarTitle}>Admin Dashboard</div>
          <div style={adStyles.topBarSub}>Control total del sistema</div>
        </div>
        <div style={adStyles.adminBadge}>ADMIN</div>
        <button
          style={adStyles.logoutBtn}
          title="Cerrar sesión"
          onClick={() => {
            localStorage.removeItem('lokat_token');
            localStorage.removeItem('lokat_user');
            localStorage.removeItem('lokat_screen');
            onBack();
          }}
        >
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
        </button>
      </div>

      {/* TABS */}
      <div style={adStyles.tabBar}>
        {TABS.map(t => (
          <button key={t.id} style={{...adStyles.tabBtn, ...(tab === t.id ? adStyles.tabBtnActive : {})}} onClick={() => setTab(t.id)}>
            {t.label}
            {t.id === 'users' && <span style={adStyles.alertDot}>{adminUsers.length}</span>}
            {t.id === 'listings' && <span style={adStyles.alertDot}>{adminBoxes.length}</span>}
            {t.id === 'alerts' && activeAlerts > 0 && <span style={adStyles.alertDot}>{activeAlerts}</span>}
          </button>
        ))}
      </div>

      <div style={{...adStyles.content, padding: isMobile ? '16px 12px' : '24px 20px'}}>
        {/* ── OVERVIEW ── */}
        {tab === 'overview' && (
          <div>
            {/* ACTIVE ALERT PREVIEW */}
            {alerts.filter(a => a.active).map(a => (
              <div key={a.id} style={{...adStyles.sysAlert, ...(a.type === 'warning' ? adStyles.sysAlertWarn : adStyles.sysAlertInfo)}}>
                <span style={adStyles.sysAlertIcon}>{a.type === 'warning' ? '⚠️' : 'ℹ️'}</span>
                {a.text}
              </div>
            ))}

            {/* KPI GRID */}
            <div style={{...adStyles.kpiGrid, gridTemplateColumns: isMobile ? 'repeat(2,1fr)' : 'repeat(4,1fr)'}}>
              {[
                { label: 'Total boxes', value: stats?.totalBoxes || 0, sub: 'en el sistema', color: '#0984e3' },
                { label: 'Usuarios registrados', value: stats?.totalUsers || 0, sub: 'profesionales y dueños', color: '#00b894' },
                { label: 'Total reservas', value: stats?.totalBookings || 0, sub: 'completadas y activas', color: '#6c5ce7' },
                { label: 'Ingresos totales', value: stats?.totalRevenue ? `$${(stats.totalRevenue).toLocaleString()}` : '$0', sub: 'en la plataforma', color: '#fd79a8' },
              ].map(k => (
                <div key={k.label} style={adStyles.kpiCard}>
                  <div style={{...adStyles.kpiValue, color: k.color}}>{k.value}</div>
                  <div style={adStyles.kpiLabel}>{k.label}</div>
                  <div style={adStyles.kpiSub}>{k.sub}</div>
                </div>
              ))}
            </div>

            {/* COMMISSION CONTROL */}
            <div style={adStyles.commissionCard}>
              <div style={{...adStyles.commissionHeader, flexDirection: isMobile ? 'column' : 'row', alignItems: isMobile ? 'flex-start' : 'center', gap: isMobile ? 12 : 0}}>
                <div>
                  <div style={adStyles.commissionTitle}>Comisión Global</div>
                  <div style={adStyles.commissionSub}>Se aplica a todas las reservas de la plataforma</div>
                </div>
                {!editingCommission ? (
                  <div style={adStyles.commissionDisplay}>
                    <span style={adStyles.commissionValue}>{commission}%</span>
                    <button style={adStyles.editBtn} onClick={() => { setCommissionDraft(commission); setEditingCommission(true); }}>Editar</button>
                  </div>
                ) : (
                  <div style={adStyles.commissionEdit}>
                    <input
                      style={adStyles.commissionInput}
                      type="number"
                      min="1" max="50"
                      value={commissionDraft}
                      onChange={e => setCommissionDraft(Number(e.target.value))}
                    />
                    <span style={adStyles.commissionPct}>%</span>
                    <button style={adStyles.saveBtn} onClick={saveCommission}>Guardar</button>
                    <button style={adStyles.cancelBtn} onClick={() => setEditingCommission(false)}>✕</button>
                  </div>
                )}
              </div>
              <div style={adStyles.commissionBar}>
                <div style={{...adStyles.commissionBarFill, width: `${Math.min(commission * 2, 100)}%`}}></div>
              </div>
              <div style={adStyles.commissionFootnote}>Ingresos estimados este mes: <strong>${(47 * 7000 * commission / 100).toLocaleString()}</strong></div>
            </div>

            {/* SYSTEM OPERATIONS */}
            <div style={adStyles.commissionCard}>
              <div style={{...adStyles.commissionHeader, flexDirection: isMobile ? 'column' : 'row', alignItems: isMobile ? 'flex-start' : 'center', gap: isMobile ? 12 : 0}}>
                <div>
                  <div style={adStyles.commissionTitle}>⚙️ Sistema</div>
                  <div style={adStyles.commissionSub}>Operaciones administrativas y mantenimiento</div>
                </div>
              </div>
              <div style={{display: 'flex', gap: 12, flexWrap: 'wrap', marginTop: 16}}>
                <button
                  style={{
                    background: '#0984e3',
                    color: '#fff',
                    border: 'none',
                    borderRadius: 8,
                    padding: '10px 16px',
                    fontSize: 13,
                    fontWeight: 600,
                    cursor: 'pointer',
                    opacity: resetRateLimitLoading ? 0.6 : 1,
                    display: 'flex',
                    alignItems: 'center',
                    gap: 8,
                  }}
                  onClick={resetRateLimiter}
                  disabled={resetRateLimitLoading}
                >
                  {resetRateLimitLoading ? '⏳ Reseteando...' : '🔄 Reset Rate Limit'}
                </button>
              </div>
              <div style={{fontSize: 12, color: '#adb5bd', marginTop: 12}}>
                💡 Limpia el limitador de tasa para todos los IPs. Ú
salo si el sistema está bloqueado por demasiadas solicitudes.
              </div>
            </div>
          </div>
        )}

        {/* ── LISTINGS ── */}
        {tab === 'listings' && (
          <div>
            <div style={adStyles.tableHeader}>
              <div>
                <div style={adStyles.tableTitle}>Todos los listings</div>
                <div style={adStyles.tableSubtitle}>
                  {adminBoxes.filter(b =>
                    (b.name?.toLowerCase().includes(listingsSearch.toLowerCase()) || false) ||
                    (b.owner?.full_name?.toLowerCase().includes(listingsSearch.toLowerCase()) || false) ||
                    (b.specialty?.toLowerCase().includes(listingsSearch.toLowerCase()) || false)
                  ).length} de {adminBoxes.length} boxes
                </div>
              </div>
              <input
                type="text"
                placeholder="Buscar por nombre, propietario o especialidad..."
                value={listingsSearch}
                onChange={(e) => setListingsSearch(e.target.value)}
                style={{
                  padding: '10px 14px',
                  border: '1px solid #dee2e6',
                  borderRadius: 6,
                  fontSize: 14,
                  width: isMobile ? '100%' : 280,
                  marginTop: isMobile ? 12 : 0,
                }}
              />
            </div>

            {/* BULK ACTION BAR FOR LISTINGS */}
            {selectedListingIds.length > 0 && (
              <div style={adStyles.bulkActionBar}>
                <span style={adStyles.bulkActionText}>
                  {selectedListingIds.length} listing{selectedListingIds.length !== 1 ? 's' : ''} seleccionado{selectedListingIds.length !== 1 ? 's' : ''}
                </span>
                <div style={adStyles.bulkActionBtns}>
                  <button style={adStyles.bulkActionActivate} onClick={bulkActivateListings}>✓ Activar</button>
                  <button style={adStyles.bulkActionSuspend} onClick={bulkSuspendListings}>⊗ Suspender</button>
                  <button style={adStyles.bulkActionDelete} onClick={bulkDeleteListings}>🗑 Eliminar</button>
                  <button style={adStyles.bulkActionCancel} onClick={() => setSelectedListingIds([])}>Cancelar</button>
                </div>
              </div>
            )}

            {adminBoxesLoading ? (
              <div style={{textAlign: 'center', padding: '40px', color: '#636e72'}}>
                <div style={{fontSize: 14}}>Cargando boxes...</div>
              </div>
            ) : (
              <div style={adStyles.tableWrap}>
                <table style={adStyles.table}>
                  <thead>
                    <tr>
                      <th style={{...adStyles.th, width: 40, padding: '12px 8px'}}>
                        <input type="checkbox" onChange={(e) => {
                          if (e.target.checked) {
                            setSelectedListingIds(adminBoxes.map(b => b.id));
                          } else {
                            setSelectedListingIds([]);
                          }
                        }} checked={selectedListingIds.length === adminBoxes.length && adminBoxes.length > 0} />
                      </th>
                      {['Nombre', 'Propietario', 'Especialidad', 'Precio/hr', 'Reservas', 'Estado'].map(h => (
                        <th key={h} style={adStyles.th}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {(() => {
                      const filteredBoxes = adminBoxes.filter(b =>
                        (b.name?.toLowerCase().includes(listingsSearch.toLowerCase()) || false) ||
                        (b.owner?.full_name?.toLowerCase().includes(listingsSearch.toLowerCase()) || false) ||
                        (b.specialty?.toLowerCase().includes(listingsSearch.toLowerCase()) || false)
                      );
                      return filteredBoxes.length > 0 ? filteredBoxes.map(box => (
                      <tr key={box.id} style={{...adStyles.tr, background: selectedListingIds.includes(box.id) ? '#f0f4f8' : 'inherit'}} onClick={() => openEditListing(box)}>
                        <td style={{...adStyles.td, padding: '12px 8px'}} onClick={(e) => { e.stopPropagation(); toggleListingSelection(box.id); }}>
                          <input type="checkbox" checked={selectedListingIds.includes(box.id)} onChange={() => toggleListingSelection(box.id)} onClick={(e) => e.stopPropagation()} />
                        </td>
                        <td style={adStyles.td}>
                          <div style={adStyles.listingName}>{box.name}</div>
                        </td>
                        <td style={adStyles.td}><span style={adStyles.tdSub}>{box.owner?.full_name || 'N/A'}</span></td>
                        <td style={adStyles.td}><span style={adStyles.tdSub}>{box.specialty || 'General'}</span></td>
                        <td style={adStyles.td}><strong>${box.price_per_slot?.toLocaleString() || '0'}</strong></td>
                        <td style={adStyles.td}><strong>{box.bookingCount || 0}</strong></td>
                        <td style={adStyles.td}>
                          <span style={{
                            ...adStyles.statusBadge,
                            background: box.status === 'open' ? '#d4edda' : box.status === 'closed' ? '#fff3cd' : '#f8d7da',
                            color: box.status === 'open' ? '#155724' : box.status === 'closed' ? '#856404' : '#721c24',
                          }}>
                            {box.status === 'open' ? 'Abierto' : box.status === 'closed' ? 'Cerrado' : 'Archivado'}
                          </span>
                        </td>
                      </tr>
                      )) : (
                        <tr>
                          <td colSpan="7" style={{...adStyles.td, textAlign: 'center', color: '#adb5bd', padding: '20px'}}>
                            {listingsSearch ? 'No se encontraron boxes' : 'No hay boxes registrados'}
                          </td>
                        </tr>
                      );
                    })()}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        )}

        {/* ── USERS ── */}
        {tab === 'users' && (
          <div>
            <div style={{...adStyles.tableHeader, alignItems: 'flex-start'}}>
              <div>
                <div style={adStyles.tableTitle}>Gestión de usuarios</div>
                <div style={adStyles.tableSubtitle}>{adminUsers.length} usuarios en la plataforma</div>
              </div>
              <button
                style={{
                  background: '#0984e3',
                  color: '#fff',
                  border: 'none',
                  borderRadius: 8,
                  padding: '10px 18px',
                  fontSize: 13,
                  fontWeight: 700,
                  cursor: 'pointer',
                  display: 'flex',
                  alignItems: 'center',
                  gap: 6,
                  whiteSpace: 'nowrap',
                  flexShrink: 0,
                }}
                onClick={() => { setShowCreateUser(true); setCreateErrors({}); }}
              >
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                Crear Usuario
              </button>
            </div>

            {/* BULK ACTION BAR FOR USERS */}
            {selectedUserIds.length > 0 && (
              <div style={adStyles.bulkActionBar}>
                <span style={adStyles.bulkActionText}>
                  {selectedUserIds.length} usuario{selectedUserIds.length !== 1 ? 's' : ''} seleccionado{selectedUserIds.length !== 1 ? 's' : ''}
                </span>
                <div style={adStyles.bulkActionBtns}>
                  <button style={adStyles.bulkActionVerify} onClick={bulkVerifyUsers}>✓ Verificar</button>
                  <button style={adStyles.bulkActionReject} onClick={bulkRejectUsers}>✕ Rechazar</button>
                  <button style={adStyles.bulkActionReset} onClick={bulkResetPasswords} disabled={resetPasswordLoading}>
                    {resetPasswordLoading ? '⏳ Enviando...' : '🔐 Reset Pass'}
                  </button>
                  <button style={adStyles.bulkActionDelete} onClick={bulkDeleteUsers}>🗑 Eliminar</button>
                  <button style={adStyles.bulkActionCancel} onClick={() => setSelectedUserIds([])}>Cancelar</button>
                </div>
              </div>
            )}

            {adminUsersLoading ? (
              <div style={{textAlign: 'center', padding: '40px', color: '#636e72'}}>
                <div style={{fontSize: 14}}>Cargando usuarios...</div>
              </div>
            ) : (
              <React.Fragment>
              <div style={{display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 24, alignItems: 'start'}}>
                {/* PROFESSIONALS SECTION — LEFT COLUMN */}
                {(() => {
                  const professionals = adminUsers.filter(u => u.role === 'professional');
                  const filteredProfessionals = professionals.filter(u =>
                    (u.full_name?.toLowerCase().includes(professionalSearch.toLowerCase()) || false) ||
                    (u.email?.toLowerCase().includes(professionalSearch.toLowerCase()) || false) ||
                    (u.specialty?.toLowerCase().includes(professionalSearch.toLowerCase()) || false)
                  );
                  return (
                    <div style={{display: 'flex', flexDirection: 'column', height: '100%'}}>
                      <div style={{fontSize: 16, fontWeight: 700, marginBottom: 12, color: '#2D3436'}}>
                        👨‍⚕️ Profesionales ({filteredProfessionals.length})
                      </div>
                      <input
                        type="text"
                        placeholder="Buscar por nombre, email o especialidad..."
                        value={professionalSearch}
                        onChange={(e) => setProfessionalSearch(e.target.value)}
                        style={{
                          padding: '10px 12px',
                          border: '1px solid #dee2e6',
                          borderRadius: 6,
                          fontSize: 13,
                          marginBottom: 12,
                          width: '100%',
                        }}
                      />
                      <div style={{...adStyles.userList, flex: 1, overflowY: 'auto', maxHeight: 'calc(100vh - 400px)', paddingRight: 8}}>
                        {filteredProfessionals.length > 0 ? filteredProfessionals.map(u => (
                          <div key={u.id} style={{...adStyles.userCard, background: selectedUserIds.includes(u.id) ? '#f0f4f8' : '#fff', cursor: 'pointer'}} onClick={() => openEditUser(u)}>
                            <input type="checkbox" checked={selectedUserIds.includes(u.id)} onChange={() => toggleUserSelection(u.id)} onClick={(e) => e.stopPropagation()} style={{width: 18, height: 18, cursor: 'pointer'}} />
                            <div style={adStyles.userAvatar}>{(u.full_name || u.email || 'U').split(' ').map(n => n[0]).join('').toUpperCase().substring(0, 2)}</div>
                            <div style={adStyles.userInfo}>
                              <div style={adStyles.userName}>{u.full_name || u.email}</div>
                              <div style={adStyles.userMeta}>
                                <span style={adStyles.userMetaItem}>📧 {u.email}</span>
                                {u.specialty && <span style={adStyles.userMetaItem}>📋 {u.specialty}</span>}
                                <span style={{...adStyles.userMetaItem, padding: '2px 6px', borderRadius: 4, background: u.sisStatus === 'verified' ? '#d4edda' : u.sisStatus === 'rejected' ? '#f8d7da' : '#fff3cd', fontSize: 11, fontWeight: 600, color: u.sisStatus === 'verified' ? '#155724' : u.sisStatus === 'rejected' ? '#721c24' : '#856404'}}>
                                  {u.sisStatus === 'verified' ? '✓ Verificado' : u.sisStatus === 'rejected' ? '✕ Rechazado' : '⧖ Pendiente'}
                                </span>
                              </div>
                            </div>
                          </div>
                        )) : (
                          <div style={{color: '#adb5bd', padding: '20px'}}>
                            {professionalSearch ? 'No se encontraron profesionales' : 'No hay profesionales registrados'}
                          </div>
                        )}
                      </div>
                    </div>
                  );
                })()}

                {/* OWNERS SECTION — RIGHT COLUMN */}
                {(() => {
                  const owners = adminUsers.filter(u => u.role === 'owner');
                  const filteredOwners = owners.filter(u =>
                    (u.full_name?.toLowerCase().includes(ownerSearch.toLowerCase()) || false) ||
                    (u.email?.toLowerCase().includes(ownerSearch.toLowerCase()) || false) ||
                    (u.specialty?.toLowerCase().includes(ownerSearch.toLowerCase()) || false)
                  );
                  return (
                    <div style={{display: 'flex', flexDirection: 'column', height: '100%'}}>
                      <div style={{fontSize: 16, fontWeight: 700, marginBottom: 12, color: '#2D3436'}}>
                        🏢 Propietarios ({filteredOwners.length})
                      </div>
                      <input
                        type="text"
                        placeholder="Buscar por nombre, email o especialidad..."
                        value={ownerSearch}
                        onChange={(e) => setOwnerSearch(e.target.value)}
                        style={{
                          padding: '10px 12px',
                          border: '1px solid #dee2e6',
                          borderRadius: 6,
                          fontSize: 13,
                          marginBottom: 12,
                          width: '100%',
                        }}
                      />
                      <div style={{...adStyles.userList, flex: 1, overflowY: 'auto', maxHeight: 'calc(100vh - 400px)', paddingRight: 8}}>
                        {filteredOwners.length > 0 ? filteredOwners.map(u => (
                          <div key={u.id} style={{...adStyles.userCard, background: selectedUserIds.includes(u.id) ? '#f0f4f8' : '#fff', cursor: 'pointer'}} onClick={() => openEditUser(u)}>
                            <input type="checkbox" checked={selectedUserIds.includes(u.id)} onChange={() => toggleUserSelection(u.id)} onClick={(e) => e.stopPropagation()} style={{width: 18, height: 18, cursor: 'pointer'}} />
                            <div style={adStyles.userAvatar}>{(u.full_name || u.email || 'U').split(' ').map(n => n[0]).join('').toUpperCase().substring(0, 2)}</div>
                            <div style={adStyles.userInfo}>
                              <div style={adStyles.userName}>{u.full_name || u.email}</div>
                              <div style={adStyles.userMeta}>
                                <span style={adStyles.userMetaItem}>📧 {u.email}</span>
                                {u.phone && <span style={adStyles.userMetaItem}>📱 {u.phone}</span>}
                                <span style={{...adStyles.userMetaItem, padding: '2px 6px', borderRadius: 4, background: u.sisStatus === 'verified' ? '#d4edda' : u.sisStatus === 'rejected' ? '#f8d7da' : '#fff3cd', fontSize: 11, fontWeight: 600, color: u.sisStatus === 'verified' ? '#155724' : u.sisStatus === 'rejected' ? '#721c24' : '#856404'}}>
                                  {u.sisStatus === 'verified' ? '✓ Verificado' : u.sisStatus === 'rejected' ? '✕ Rechazado' : '⧖ Pendiente'}
                                </span>
                              </div>
                            </div>
                          </div>
                        )) : (
                          <div style={{color: '#adb5bd', padding: '20px'}}>
                            {ownerSearch ? 'No se encontraron propietarios' : 'No hay propietarios registrados'}
                          </div>
                        )}
                      </div>
                    </div>
                  );
                })()}
              </div>

              {/* ADMINS SECTION — full width below the two columns */}
              {(() => {
                const admins = adminUsers.filter(u => u.role === 'admin' || u.role === 'admin_limited');
                return admins.length > 0 ? (
                  <div style={{marginTop: 24}}>
                    <div style={{fontSize: 16, fontWeight: 700, marginBottom: 12, color: '#2D3436'}}>
                      👑 Administradores ({admins.length})
                    </div>
                    <div style={{display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(auto-fill, minmax(280px, 1fr))', gap: 10}}>
                      {admins.map(u => (
                        <div key={u.id} style={{...adStyles.userCard, cursor: 'pointer', background: selectedUserIds.includes(u.id) ? '#f0f4f8' : '#fff'}} onClick={() => openEditUser(u)}>
                          <input type="checkbox" checked={selectedUserIds.includes(u.id)} onChange={() => toggleUserSelection(u.id)} onClick={e => e.stopPropagation()} style={{width: 18, height: 18, cursor: 'pointer'}} />
                          <div style={{...adStyles.userAvatar, background: u.role === 'admin' ? '#6c5ce7' : '#a29bfe'}}>
                            {(u.full_name || u.email || 'U').split(' ').map(n => n[0]).join('').toUpperCase().substring(0, 2)}
                          </div>
                          <div style={adStyles.userInfo}>
                            <div style={adStyles.userName}>{u.full_name || u.email}</div>
                            <div style={adStyles.userMeta}>
                              <span style={adStyles.userMetaItem}>📧 {u.email}</span>
                              {u.phone && <span style={adStyles.userMetaItem}>📱 {u.phone}</span>}
                              <span style={{
                                ...adStyles.userMetaItem,
                                padding: '2px 8px',
                                borderRadius: 4,
                                fontSize: 11,
                                fontWeight: 700,
                                background: u.role === 'admin' ? '#ede9fe' : '#f0f0ff',
                                color: u.role === 'admin' ? '#5b21b6' : '#7c3aed',
                              }}>
                                {u.role === 'admin' ? '🔑 Admin' : '🔒 Admin Limitado'}
                              </span>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                ) : null;
              })()}
              </React.Fragment>
            )}
          </div>
        )}

        {/* ── ALERTS ── */}
        {tab === 'alerts' && (
          <div>
            <div style={adStyles.tableHeader}>
              <div style={adStyles.tableTitle}>Gestión de alertas</div>
              <div style={adStyles.tableSubtitle}>Banners visibles en toda la plataforma</div>
            </div>

            {/* CREATE ALERT */}
            <div style={adStyles.createAlertCard}>
              <div style={adStyles.createAlertTitle}>Nueva alerta del sistema</div>
              <div style={adStyles.alertTypeRow}>
                {['info', 'warning', 'critical'].map(t => (
                  <button key={t} style={{...adStyles.alertTypeBtn, ...(alertType === t ? adStyles.alertTypeBtnActive : {})}} onClick={() => setAlertType(t)}>
                    {t === 'info' ? 'ℹ️ Info' : t === 'warning' ? '⚠️ Aviso' : '🚨 Crítico'}
                  </button>
                ))}
              </div>
              <textarea
                style={adStyles.alertTextarea}
                placeholder="Escribe el mensaje de alerta aquí..."
                value={alertDraft}
                onChange={e => setAlertDraft(e.target.value)}
                rows={3}
              />
              <button style={{...adStyles.publishAlertBtn, opacity: alertDraft.trim() ? 1 : 0.5}} onClick={handleAddAlert} disabled={!alertDraft.trim()}>
                Publicar alerta
              </button>
            </div>

            {/* ACTIVE ALERTS */}
            <div style={adStyles.alertList}>
              {alerts.map(a => (
                <div key={a.id} style={{
                  ...adStyles.alertItem,
                  borderLeft: `4px solid ${a.type === 'warning' ? '#ffc107' : a.type === 'critical' ? '#dc3545' : '#0984e3'}`,
                  opacity: a.active ? 1 : 0.45,
                }}>
                  <div style={adStyles.alertItemIcon}>{a.type === 'warning' ? '⚠️' : a.type === 'critical' ? '🚨' : 'ℹ️'}</div>
                  <div style={adStyles.alertItemText}>{a.text}</div>
                  <div style={adStyles.alertItemActions}>
                    <div style={adStyles.toggleWrapper} onClick={() => setAlerts(prev => prev.map(x => x.id === a.id ? {...x, active: !x.active} : x))}>
                      <div style={{...adStyles.toggleTrack, background: a.active ? '#0984e3' : '#dee2e6'}}>
                        <div style={{...adStyles.toggleThumb, left: a.active ? 22 : 2}}></div>
                      </div>
                      <span style={{fontSize:12, color: a.active ? '#0984e3' : '#adb5bd', fontWeight:600}}>{a.active ? 'Activa' : 'Inactiva'}</span>
                    </div>
                    <button style={adStyles.removeAlertBtn} onClick={() => setAlerts(prev => prev.filter(x => x.id !== a.id))}>✕</button>
                  </div>
                </div>
              ))}
              {alerts.length === 0 && <div style={adStyles.emptyState}>No hay alertas activas</div>}
            </div>
          </div>
        )}
      </div>

      {/* SUCCESS MESSAGE */}
      {successMessage && (
        <div style={adStyles.successNotification}>
          ✓ {successMessage}
        </div>
      )}

      {/* EDIT LISTING MODAL */}
      {editingListing && editingListingDraft && (
        <div style={adStyles.modalOverlay} onClick={() => setEditingListing(null)}>
          <div style={adStyles.modalContent} onClick={(e) => e.stopPropagation()}>
            <div style={adStyles.modalHeader}>
              <div style={adStyles.modalTitle}>Editar Listing</div>
              <button style={adStyles.modalCloseBtn} onClick={() => setEditingListing(null)}>✕</button>
            </div>

            <div style={adStyles.modalBody}>
              <div style={adStyles.formGroup}>
                <label style={adStyles.formLabel}>Nombre del Box</label>
                <input
                  type="text"
                  style={adStyles.formInput}
                  value={editingListingDraft.name}
                  onChange={(e) => setEditingListingDraft({...editingListingDraft, name: e.target.value})}
                />
              </div>

              <div style={adStyles.formGroup}>
                <label style={adStyles.formLabel}>Precio por hora (CLP)</label>
                <input
                  type="number"
                  style={adStyles.formInput}
                  value={editingListingDraft.price_per_slot}
                  onChange={(e) => setEditingListingDraft({...editingListingDraft, price_per_slot: Number(e.target.value)})}
                />
              </div>

              <div style={adStyles.formGroup}>
                <label style={adStyles.formLabel}>Ubicación</label>
                <input
                  type="text"
                  style={adStyles.formInput}
                  value={editingListingDraft.location}
                  onChange={(e) => setEditingListingDraft({...editingListingDraft, location: e.target.value})}
                />
              </div>

              <div style={adStyles.formGroup}>
                <label style={adStyles.formLabel}>Estado</label>
                <select
                  style={adStyles.formSelect}
                  value={editingListingDraft.status}
                  onChange={(e) => setEditingListingDraft({...editingListingDraft, status: e.target.value})}
                >
                  <option value="open">Abierto</option>
                  <option value="closed">Cerrado</option>
                  <option value="archived">Archivado</option>
                </select>
              </div>

              <div style={adStyles.formGroup}>
                <label style={{...adStyles.formLabel, display: 'flex', alignItems: 'center', gap: 8}}>
                  <input
                    type="checkbox"
                    checked={editingListingDraft.verified}
                    onChange={(e) => setEditingListingDraft({...editingListingDraft, verified: e.target.checked})}
                  />
                  Verified
                </label>
              </div>
            </div>

            <div style={adStyles.modalFooter}>
              <button style={adStyles.modalCancelBtn} onClick={() => setEditingListing(null)}>Cancelar</button>
              <button style={adStyles.modalSaveBtn} onClick={saveListing}>Guardar cambios</button>
            </div>
          </div>
        </div>
      )}

      {/* CREATE USER MODAL */}
      {showCreateUser && (
        <div style={adStyles.modalOverlay} onClick={() => setShowCreateUser(false)}>
          <div style={{...adStyles.modalContent, maxWidth: 480}} onClick={e => e.stopPropagation()}>
            <div style={adStyles.modalHeader}>
              <div style={adStyles.modalTitle}>➕ Crear Usuario</div>
              <button style={adStyles.modalCloseBtn} onClick={() => setShowCreateUser(false)}>✕</button>
            </div>

            <div style={adStyles.modalBody}>
              {/* Name */}
              <div style={adStyles.formGroup}>
                <label style={adStyles.formLabel}>Nombre completo *</label>
                <input
                  type="text"
                  style={{...adStyles.formInput, ...(createErrors.full_name ? {borderColor:'#dc3545'} : {})}}
                  placeholder="Dr. Juan Pérez"
                  value={createForm.full_name}
                  onChange={e => { setCreateForm(p => ({...p, full_name: e.target.value})); setCreateErrors(p => ({...p, full_name: undefined})); }}
                />
                {createErrors.full_name && <span style={{fontSize:12,color:'#dc3545',marginTop:3,display:'block'}}>{createErrors.full_name}</span>}
              </div>

              {/* Email */}
              <div style={adStyles.formGroup}>
                <label style={adStyles.formLabel}>Email *</label>
                <input
                  type="email"
                  style={{...adStyles.formInput, ...(createErrors.email ? {borderColor:'#dc3545'} : {})}}
                  placeholder="usuario@email.cl"
                  value={createForm.email}
                  onChange={e => { setCreateForm(p => ({...p, email: e.target.value})); setCreateErrors(p => ({...p, email: undefined})); }}
                />
                {createErrors.email && <span style={{fontSize:12,color:'#dc3545',marginTop:3,display:'block'}}>{createErrors.email}</span>}
              </div>

              {/* Password */}
              <div style={adStyles.formGroup}>
                <label style={adStyles.formLabel}>Contraseña *</label>
                <input
                  type="text"
                  style={{...adStyles.formInput, fontFamily:'monospace', ...(createErrors.password ? {borderColor:'#dc3545'} : {})}}
                  placeholder="Mínimo 6 caracteres"
                  value={createForm.password}
                  onChange={e => { setCreateForm(p => ({...p, password: e.target.value})); setCreateErrors(p => ({...p, password: undefined})); }}
                />
                {createErrors.password && <span style={{fontSize:12,color:'#dc3545',marginTop:3,display:'block'}}>{createErrors.password}</span>}
                <span style={{fontSize:11,color:'#636e72',marginTop:4,display:'block'}}>Esta contraseña se enviará al usuario por email junto con sus credenciales.</span>
              </div>

              {/* Phone */}
              <div style={adStyles.formGroup}>
                <label style={adStyles.formLabel}>Teléfono <span style={{color:'#adb5bd',fontWeight:400}}>(opcional)</span></label>
                <input
                  type="tel"
                  style={{...adStyles.formInput, ...(createErrors.phone ? {borderColor:'#dc3545'} : {})}}
                  placeholder="+56 9 XXXX XXXX"
                  value={createForm.phone}
                  maxLength={15}
                  onFocus={handleCreatePhoneFocus}
                  onChange={handleCreatePhoneChange}
                />
                {createErrors.phone && <span style={{fontSize:12,color:'#dc3545',marginTop:3,display:'block'}}>{createErrors.phone}</span>}
              </div>

              {/* Role */}
              <div style={adStyles.formGroup}>
                <label style={adStyles.formLabel}>Rol *</label>
                <select
                  style={adStyles.formSelect}
                  value={createForm.role}
                  onChange={e => setCreateForm(p => ({...p, role: e.target.value, specialty: ''}))}
                >
                  <option value="professional">🩺 Profesional</option>
                  <option value="owner">🏥 Propietario</option>
                  <option value="admin">🔑 Administrador</option>
                  <option value="admin_limited">🔒 Admin Limitado (solo gestión de usuarios)</option>
                </select>
              </div>

              {/* Specialty — only for professional */}
              {createForm.role === 'professional' && (
                <div style={adStyles.formGroup}>
                  <label style={adStyles.formLabel}>Especialidad <span style={{color:'#adb5bd',fontWeight:400}}>(opcional)</span></label>
                  <select
                    style={adStyles.formSelect}
                    value={createForm.specialty}
                    onChange={e => setCreateForm(p => ({...p, specialty: e.target.value}))}
                  >
                    <option value="">Sin especialidad</option>
                    {['Medicina General','Odontología','Kinesiología','Psicología','Nutrición','Fonoaudiología','Dermatología','Otra'].map(s => (
                      <option key={s} value={s}>{s}</option>
                    ))}
                  </select>
                </div>
              )}

              {createErrors.submit && (
                <div style={{background:'#f8d7da',border:'1px solid #f5c6cb',borderRadius:8,padding:'10px 14px',fontSize:13,color:'#721c24',marginTop:8}}>
                  {createErrors.submit}
                </div>
              )}
            </div>

            <div style={adStyles.modalFooter}>
              <button style={adStyles.modalCancelBtn} onClick={() => setShowCreateUser(false)}>Cancelar</button>
              <button
                style={{...adStyles.modalSaveBtn, opacity: createLoading ? 0.7 : 1, display:'flex', alignItems:'center', gap:8}}
                onClick={handleCreateUser}
                disabled={createLoading}
              >
                {createLoading ? '⏳ Creando...' : '✓ Crear usuario y enviar email'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* EDIT USER MODAL */}
      {editingUser && editingUserDraft && (
        <div style={adStyles.modalOverlay} onClick={() => setEditingUser(null)}>
          <div style={adStyles.modalContent} onClick={(e) => e.stopPropagation()}>
            <div style={adStyles.modalHeader}>
              <div style={adStyles.modalTitle}>Editar Usuario</div>
              <button style={adStyles.modalCloseBtn} onClick={() => setEditingUser(null)}>✕</button>
            </div>

            <div style={adStyles.modalBody}>
              <div style={adStyles.formGroup}>
                <label style={adStyles.formLabel}>Nombre completo</label>
                <input
                  type="text"
                  style={adStyles.formInput}
                  value={editingUserDraft.full_name}
                  onChange={(e) => setEditingUserDraft({...editingUserDraft, full_name: e.target.value})}
                />
              </div>

              <div style={adStyles.formGroup}>
                <label style={adStyles.formLabel}>Email</label>
                <input
                  type="email"
                  style={adStyles.formInput}
                  value={editingUserDraft.email}
                  onChange={(e) => setEditingUserDraft({...editingUserDraft, email: e.target.value})}
                />
              </div>

              <div style={adStyles.formGroup}>
                <label style={adStyles.formLabel}>Teléfono</label>
                <input
                  type="tel"
                  style={adStyles.formInput}
                  value={editingUserDraft.phone || ''}
                  onChange={(e) => setEditingUserDraft({...editingUserDraft, phone: e.target.value})}
                  placeholder="+56 9 1234 5678"
                />
              </div>

              <div style={adStyles.formGroup}>
                <label style={adStyles.formLabel}>Rol</label>
                <select
                  style={adStyles.formSelect}
                  value={editingUserDraft.role}
                  onChange={(e) => setEditingUserDraft({...editingUserDraft, role: e.target.value})}
                >
                  <option value="professional">Profesional</option>
                  <option value="owner">Propietario</option>
                </select>
              </div>

              {editingUserDraft.role === 'professional' && (
                <div style={adStyles.formGroup}>
                  <label style={adStyles.formLabel}>Especialidad</label>
                  <input
                    type="text"
                    style={adStyles.formInput}
                    value={editingUserDraft.specialty}
                    onChange={(e) => setEditingUserDraft({...editingUserDraft, specialty: e.target.value})}
                  />
                </div>
              )}

              <div style={adStyles.formGroup}>
                <label style={adStyles.formLabel}>Estado SIS</label>
                <select
                  style={adStyles.formSelect}
                  value={editingUserDraft.sisStatus}
                  onChange={(e) => setEditingUserDraft({...editingUserDraft, sisStatus: e.target.value})}
                >
                  <option value="pending">Pendiente</option>
                  <option value="verified">Verificado</option>
                  <option value="rejected">Rechazado</option>
                </select>
              </div>

              {/* SECURITY SECTION */}
              <div style={{borderTop: '1px solid #e9ecef', paddingTop: 16, marginTop: 16}}>
                <div style={{fontSize: 14, fontWeight: 700, color: '#2D3436', marginBottom: 12}}>🔐 Seguridad</div>

                <div style={adStyles.formGroup}>
                  <label style={adStyles.formLabel}>Contraseña temporal</label>
                  {!tempPassword ? (
                    <button
                      style={{...adStyles.securityBtn, width: '100%'}}
                      onClick={generateTempPassword}
                    >
                      Generar contraseña temporal
                    </button>
                  ) : (
                    <div style={adStyles.tempPasswordBox}>
                      <input
                        type="text"
                        readOnly
                        value={tempPassword}
                        style={{...adStyles.formInput, fontFamily: 'monospace', fontSize: 13, marginBottom: 8}}
                      />
                      <div style={{display: 'flex', gap: 8}}>
                        <button
                          style={{...adStyles.copyPasswordBtn, flex: 1}}
                          onClick={copyPasswordToClipboard}
                        >
                          {passwordCopied ? '✓ Copiado!' : '📋 Copiar contraseña'}
                        </button>
                        <button
                          style={{...adStyles.sendPasswordBtn, flex: 1}}
                          onClick={sendTempPasswordEmail}
                          disabled={resetPasswordLoading}
                        >
                          {resetPasswordLoading ? '⏳ Enviando...' : '📧 Enviar por email'}
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>

            <div style={adStyles.modalFooter}>
              <button style={adStyles.modalCancelBtn} onClick={() => setEditingUser(null)}>Cancelar</button>
              <button style={adStyles.modalSaveBtn} onClick={saveUser}>Guardar cambios</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const adStyles = {
  page: { minHeight: '100vh', background: '#F8F9FA', fontFamily: "'Helvetica Neue', Helvetica, Arial, sans-serif", color: '#2D3436' },
  topBar: { background: '#2D3436', display: 'flex', alignItems: 'center', gap: 12, padding: '0 20px', height: 64 },
  backBtn: { width: 36, height: 36, borderRadius: 8, border: '1px solid rgba(255,255,255,0.15)', background: 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: '#fff', flexShrink: 0 },
  topBarInfo: { flex: 1 },
  topBarTitle: { fontSize: 16, fontWeight: 700, color: '#fff' },
  topBarSub: { fontSize: 12, color: 'rgba(255,255,255,0.5)' },
  adminBadge: { background: '#0984e3', color: '#fff', borderRadius: 6, padding: '4px 10px', fontSize: 11, fontWeight: 800, letterSpacing: 1 },
  logoutBtn: { width: 36, height: 36, borderRadius: 8, border: '1px solid rgba(255,255,255,0.15)', background: 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: 'rgba(255,255,255,0.7)', flexShrink: 0, marginLeft: 4 },
  tabBar: { background: '#fff', borderBottom: '1px solid #e9ecef', display: 'flex', padding: '0 20px' },
  tabBtn: { background: 'none', border: 'none', padding: '14px 18px', fontSize: 14, fontWeight: 500, color: '#636e72', cursor: 'pointer', fontFamily: 'inherit', borderBottom: '2px solid transparent', position: 'relative', display: 'flex', alignItems: 'center', gap: 8 },
  tabBtnActive: { color: '#0984e3', borderBottom: '2px solid #0984e3', fontWeight: 700 },
  alertDot: { background: '#dc3545', color: '#fff', borderRadius: '50%', width: 18, height: 18, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700 },
  content: { maxWidth: 960, margin: '0 auto', padding: '24px 20px' },
  sysAlert: { borderRadius: 10, padding: '12px 16px', marginBottom: 16, fontSize: 14, display: 'flex', alignItems: 'center', gap: 10 },
  sysAlertWarn: { background: '#fff3cd', color: '#856404', border: '1px solid #ffc107' },
  sysAlertInfo: { background: '#e3f0fc', color: '#0984e3', border: '1px solid #0984e3' },
  sysAlertIcon: { fontSize: 18 },
  kpiGrid: { display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 },
  kpiCard: { background: '#fff', borderRadius: 14, padding: '20px 18px', border: '1px solid #e9ecef', boxShadow: '0 2px 8px rgba(0,0,0,0.04)' },
  kpiValue: { fontSize: 32, fontWeight: 800, letterSpacing: '-1px', marginBottom: 4 },
  kpiLabel: { fontSize: 13, fontWeight: 600, color: '#2D3436', marginBottom: 2 },
  kpiSub: { fontSize: 12, color: '#adb5bd' },
  commissionCard: { background: '#fff', borderRadius: 16, padding: 24, border: '1px solid #e9ecef', boxShadow: '0 2px 8px rgba(0,0,0,0.04)' },
  commissionHeader: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 },
  commissionTitle: { fontSize: 16, fontWeight: 700, marginBottom: 2 },
  commissionSub: { fontSize: 13, color: '#636e72' },
  commissionDisplay: { display: 'flex', alignItems: 'center', gap: 12 },
  commissionValue: { fontSize: 32, fontWeight: 800, color: '#6c5ce7' },
  editBtn: { background: '#f0f4f8', border: 'none', borderRadius: 8, padding: '8px 16px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', color: '#2D3436' },
  commissionEdit: { display: 'flex', alignItems: 'center', gap: 8 },
  commissionInput: { width: 70, border: '1.5px solid #0984e3', borderRadius: 8, padding: '8px 12px', fontSize: 18, fontWeight: 700, textAlign: 'center', fontFamily: 'inherit', outline: 'none', color: '#2D3436' },
  commissionPct: { fontSize: 18, fontWeight: 700, color: '#636e72' },
  saveBtn: { background: '#0984e3', color: '#fff', border: 'none', borderRadius: 8, padding: '8px 16px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  cancelBtn: { background: '#f8d7da', color: '#721c24', border: 'none', borderRadius: 8, padding: '8px 12px', fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' },
  commissionBar: { height: 8, background: '#e9ecef', borderRadius: 4, marginBottom: 12 },
  commissionBarFill: { height: '100%', background: 'linear-gradient(90deg, #6c5ce7, #0984e3)', borderRadius: 4, transition: 'width 0.4s' },
  commissionFootnote: { fontSize: 13, color: '#636e72' },
  tableHeader: { marginBottom: 16 },
  tableTitle: { fontSize: 18, fontWeight: 700, marginBottom: 2 },
  tableSubtitle: { fontSize: 13, color: '#636e72' },
  tableWrap: { background: '#fff', borderRadius: 14, border: '1px solid #e9ecef', overflow: 'auto' },
  table: { width: '100%', borderCollapse: 'collapse' },
  th: { padding: '12px 16px', fontSize: 12, fontWeight: 700, color: '#636e72', textTransform: 'uppercase', letterSpacing: 0.5, textAlign: 'left', background: '#f8f9fa', borderBottom: '1px solid #e9ecef' },
  tr: { borderBottom: '1px solid #f0f4f8' },
  td: { padding: '12px 16px', fontSize: 14, verticalAlign: 'middle' },
  listingName: { fontWeight: 600 },
  tdSub: { color: '#636e72' },
  statusBadge: { borderRadius: 20, padding: '4px 10px', fontSize: 12, fontWeight: 600 },
  actionRow: { display: 'flex', gap: 8, alignItems: 'center' },
  actionBtn: { background: '#e3f0fc', color: '#0984e3', border: 'none', borderRadius: 6, padding: '6px 12px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  deleteBtn: { background: '#f8d7da', color: '#721c24', border: 'none', borderRadius: 6, padding: '6px 12px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  confirmDelete: { display: 'flex', alignItems: 'center', gap: 6 },
  confirmDeleteText: { fontSize: 12, fontWeight: 600, color: '#721c24' },
  deleteConfirmYes: { background: '#dc3545', color: '#fff', border: 'none', borderRadius: 6, padding: '5px 10px', fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' },
  deleteConfirmNo: { background: '#e9ecef', color: '#2D3436', border: 'none', borderRadius: 6, padding: '5px 10px', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit' },
  userList: { display: 'flex', flexDirection: 'column', gap: 12 },
  userCard: { background: '#fff', borderRadius: 14, padding: '16px 20px', border: '1px solid #e9ecef', display: 'flex', alignItems: 'center', gap: 16, boxShadow: '0 2px 8px rgba(0,0,0,0.04)' },
  userAvatar: { width: 44, height: 44, borderRadius: '50%', background: '#e3f0fc', color: '#0984e3', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14, fontWeight: 700, flexShrink: 0 },
  userInfo: { flex: 1, minWidth: 0 },
  userName: { fontSize: 15, fontWeight: 700, marginBottom: 4 },
  userMeta: { display: 'flex', gap: 8, alignItems: 'center', marginBottom: 2 },
  roleBadge: { background: '#f0f4f8', borderRadius: 6, padding: '2px 8px', fontSize: 11, fontWeight: 600, color: '#2D3436' },
  userMetaItem: { fontSize: 12, color: '#636e72' },
  userEmail: { fontSize: 12, color: '#adb5bd' },
  userActions: { display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8, flexShrink: 0 },
  sisBadge: { borderRadius: 20, padding: '4px 12px', fontSize: 12, fontWeight: 600 },
  overrideRow: { display: 'flex', gap: 6 },
  verifyOverride: { background: '#d4edda', color: '#155724', border: 'none', borderRadius: 6, padding: '6px 12px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  rejectOverride: { background: '#f8d7da', color: '#721c24', border: 'none', borderRadius: 6, padding: '6px 12px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  createAlertCard: { background: '#fff', borderRadius: 16, padding: 24, border: '1px solid #e9ecef', marginBottom: 20, boxShadow: '0 2px 8px rgba(0,0,0,0.04)' },
  createAlertTitle: { fontSize: 16, fontWeight: 700, marginBottom: 14 },
  alertTypeRow: { display: 'flex', gap: 8, marginBottom: 14 },
  alertTypeBtn: { background: '#f0f4f8', border: '1.5px solid #dee2e6', borderRadius: 8, padding: '8px 16px', fontSize: 13, cursor: 'pointer', fontFamily: 'inherit', color: '#636e72' },
  alertTypeBtnActive: { background: '#e3f0fc', borderColor: '#0984e3', color: '#0984e3', fontWeight: 600 },
  alertTextarea: { width: '100%', border: '1.5px solid #dee2e6', borderRadius: 10, padding: '11px 14px', fontSize: 14, fontFamily: 'inherit', resize: 'vertical', outline: 'none', boxSizing: 'border-box', color: '#2D3436', marginBottom: 14 },
  publishAlertBtn: { background: '#0984e3', color: '#fff', border: 'none', borderRadius: 10, padding: '12px 24px', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  alertList: { display: 'flex', flexDirection: 'column', gap: 12 },
  alertItem: { background: '#fff', borderRadius: 12, padding: '16px 18px', border: '1px solid #e9ecef', display: 'flex', alignItems: 'center', gap: 14 },
  alertItemIcon: { fontSize: 20, flexShrink: 0 },
  alertItemText: { flex: 1, fontSize: 14, lineHeight: 1.5 },
  alertItemActions: { display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 },
  toggleWrapper: { display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' },
  toggleTrack: { width: 44, height: 24, borderRadius: 12, position: 'relative', transition: 'background 0.2s', flexShrink: 0 },
  toggleThumb: { position: 'absolute', top: 2, width: 20, height: 20, borderRadius: '50%', background: '#fff', boxShadow: '0 1px 4px rgba(0,0,0,0.2)', transition: 'left 0.2s' },
  removeAlertBtn: { background: 'none', border: 'none', cursor: 'pointer', color: '#adb5bd', fontSize: 16, padding: 4 },
  emptyState: { textAlign: 'center', color: '#adb5bd', fontSize: 14, padding: '40px 0' },
  bulkActionBar: { background: '#e3f0fc', border: '1px solid #0984e3', borderRadius: 10, padding: '12px 16px', marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, flexWrap: 'wrap' },
  bulkActionText: { fontSize: 14, fontWeight: 600, color: '#0984e3' },
  bulkActionBtns: { display: 'flex', gap: 8, flexWrap: 'wrap' },
  bulkActionActivate: { background: '#d4edda', color: '#155724', border: '1px solid #c3e6cb', borderRadius: 6, padding: '6px 12px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  bulkActionSuspend: { background: '#fff3cd', color: '#856404', border: '1px solid #ffeaa7', borderRadius: 6, padding: '6px 12px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  bulkActionDelete: { background: '#f8d7da', color: '#721c24', border: '1px solid #f5c6cb', borderRadius: 6, padding: '6px 12px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  bulkActionVerify: { background: '#d4edda', color: '#155724', border: '1px solid #c3e6cb', borderRadius: 6, padding: '6px 12px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  bulkActionReject: { background: '#f8d7da', color: '#721c24', border: '1px solid #f5c6cb', borderRadius: 6, padding: '6px 12px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  bulkActionCancel: { background: '#e9ecef', color: '#2D3436', border: '1px solid #dee2e6', borderRadius: 6, padding: '6px 12px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  successNotification: { position: 'fixed', bottom: 24, right: 24, background: '#d4edda', color: '#155724', border: '1px solid #c3e6cb', borderRadius: 10, padding: '12px 16px', fontSize: 14, fontWeight: 600, boxShadow: '0 4px 12px rgba(0,0,0,0.15)', animation: 'fadeIn 0.3s ease', zIndex: 1000 },
  modalOverlay: { position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 999 },
  modalContent: { background: '#fff', borderRadius: 16, boxShadow: '0 10px 40px rgba(0,0,0,0.15)', maxWidth: 480, width: '90vw', maxHeight: '90vh', overflow: 'auto', animation: 'fadeIn 0.25s ease' },
  modalHeader: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '20px 24px', borderBottom: '1px solid #e9ecef' },
  modalTitle: { fontSize: 18, fontWeight: 700, color: '#2D3436' },
  modalCloseBtn: { background: 'none', border: 'none', fontSize: 20, cursor: 'pointer', color: '#adb5bd', padding: 0, width: 32, height: 32, display: 'flex', alignItems: 'center', justifyContent: 'center' },
  modalBody: { padding: '24px' },
  modalFooter: { display: 'flex', gap: 12, justifyContent: 'flex-end', padding: '16px 24px', borderTop: '1px solid #e9ecef' },
  modalSaveBtn: { background: '#0984e3', color: '#fff', border: 'none', borderRadius: 8, padding: '10px 20px', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  modalCancelBtn: { background: '#f0f4f8', color: '#2D3436', border: '1px solid #dee2e6', borderRadius: 8, padding: '10px 20px', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  formGroup: { marginBottom: 16 },
  formLabel: { display: 'block', fontSize: 13, fontWeight: 600, color: '#2D3436', marginBottom: 6 },
  formInput: { width: '100%', border: '1.5px solid #dee2e6', borderRadius: 8, padding: '10px 12px', fontSize: 14, fontFamily: 'inherit', color: '#2D3436', outline: 'none', boxSizing: 'border-box' },
  formSelect: { width: '100%', border: '1.5px solid #dee2e6', borderRadius: 8, padding: '10px 12px', fontSize: 14, fontFamily: 'inherit', color: '#2D3436', outline: 'none', boxSizing: 'border-box', background: '#fff', cursor: 'pointer' },
  securityBtn: { background: '#0984e3', color: '#fff', border: 'none', borderRadius: 8, padding: '10px 16px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  tempPasswordBox: { display: 'flex', flexDirection: 'column', gap: 8 },
  copyPasswordBtn: { background: '#d4edda', color: '#155724', border: '1px solid #c3e6cb', borderRadius: 8, padding: '10px 16px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  sendPasswordBtn: { background: '#0984e3', color: '#fff', border: 'none', borderRadius: 8, padding: '10px 16px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
  bulkActionReset: { background: '#6c5ce7', color: '#fff', border: '1px solid #6c5ce7', borderRadius: 6, padding: '6px 12px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' },
};

window.AdminDashboard = AdminDashboard;
