const SettingsPage = () => {
  const [activeTab, setActiveTab] = React.useState('account');
  const [userData, setUserData] = React.useState({ name: '', email: '', role: 'user', id: '' });
  const [organizationId, setOrganizationId] = React.useState('');
  
  // States for API Data
  const [settings, setSettings] = React.useState({
    name: 'Organización',
    currency: 'MXN',
    theme: 'dark',
    accentColor: '#fae0d1',
    protectEnabled: true,
    chatEnabled: true,
    analyticsEnabled: true,
    integrations: {
      whatsapp: { connected: true, lastSync: new Date().toISOString() },
      stripe: { connected: false },
      googleDrive: { connected: false }
    }
  });
  
  const [sessions, setSessions] = React.useState([]);
  
  // Loading states
  const [isLoading, setIsLoading] = React.useState(true);
  const [isSaving, setIsSaving] = React.useState(false);
  const [isSavingProfile, setIsSavingProfile] = React.useState(false);

  // Authentication utility
  const getJWTFromStorage = () => {
    if (window.getJWTFromStorage) return window.getJWTFromStorage();
    return localStorage.getItem('authToken') || sessionStorage.getItem('authToken') || 
           localStorage.getItem('jwt') || sessionStorage.getItem('jwt');
  };

  const getOrganizationId = () => {
    if (window.currentOrganizationId) return window.currentOrganizationId;
    const token = getJWTFromStorage();
    if (token) {
      try {
        const decoded = JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')));
        if (decoded?.organizationId) return decoded.organizationId;
      } catch(e) {}
    }
    return localStorage.getItem('organizationId');
  };

  React.useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      try {
        // 1. Load User Data
        const storedUser = localStorage.getItem('userData');
        if (storedUser) setUserData(JSON.parse(storedUser));
        
        const orgId = getOrganizationId();
        if (orgId) setOrganizationId(orgId);

        // 2. Fetch Settings from Backend
        const token = getJWTFromStorage();
        if (token) {
          try {
            const settingsRes = await fetch(`http://localhost:3000/api/settings?organizationId=${orgId}`, {
              headers: { 'Authorization': `Bearer ${token}` }
            });
            if (settingsRes.ok) {
              const settingsData = await settingsRes.json();
              if (settingsData.data) {
                setSettings(prev => ({ ...prev, ...settingsData.data }));
              }
            }
          } catch (e) {
            console.warn('Backend /api/settings no disponible, usando predeterminados');
          }

          // 3. Fetch Sessions from Backend
          try {
            const sessionsRes = await fetch(`http://localhost:3000/api/sessions`, {
              headers: { 'Authorization': `Bearer ${token}` }
            });
            if (sessionsRes.ok) {
              const sessionsData = await sessionsRes.json();
              if (sessionsData.data) setSessions(sessionsData.data);
            } else {
               // Mock Sessions if endpoint doesn't exist
               setSessions([
                 { id: '1', current: true, device: 'Windows • Chrome', location: 'Ciudad de México, MX', ip: '192.168.1.100' },
                 { id: '2', current: false, device: 'iPhone 14 • Safari', location: 'Monterrey, MX', ip: '189.145.XX.XX', lastSeen: 'Hace 2 horas' }
               ]);
            }
          } catch (e) {
             setSessions([
               { id: '1', current: true, device: 'Windows • Chrome', location: 'Ciudad de México, MX', ip: '192.168.1.100' }
             ]);
          }
        }
      } catch (error) {
        console.error('Error cargando configuración:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, []);

  // Handlers para Profile
  const handleSaveProfile = async (e) => {
    e.preventDefault();
    setIsSavingProfile(true);
    try {
      const formData = new FormData(e.target);
      const name = formData.get('name');
      const password = formData.get('password');
      const newPassword = formData.get('newPassword');

      const payload = { name };
      if (password && newPassword) {
        payload.currentPassword = password;
        payload.newPassword = newPassword;
      }

      const res = await fetch(`http://localhost:3000/api/users/profile`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${getJWTFromStorage()}`
        },
        body: JSON.stringify(payload)
      });

      if (res.ok) {
        const result = await res.json();
        setUserData(prev => ({ ...prev, name: result.data?.name || name }));
        localStorage.setItem('userData', JSON.stringify({ ...userData, name: result.data?.name || name }));
        if (window.showSuccess) window.showSuccess('Perfil actualizado correctamente');
      } else {
        const err = await res.json();
        if (window.showError) window.showError(err.message || 'Error al actualizar el perfil');
      }
    } catch (e) {
      if (window.showError) window.showError('Error de red al actualizar perfil');
    } finally {
      setIsSavingProfile(false);
      e.target.reset(); // clear passwords
    }
  };

  // Handler para Organización (Settings generales)
  const saveOrganizationSettings = async (e) => {
    e?.preventDefault();
    setIsSaving(true);
    try {
      const res = await fetch(`http://localhost:3000/api/settings`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${getJWTFromStorage()}`
        },
        body: JSON.stringify({ organizationId, settings })
      });

      if (res.ok) {
        if (window.showSuccess) window.showSuccess('Configuración guardada correctamente');
      } else {
        if (window.showError) window.showError('Error al guardar la configuración');
      }
    } catch (e) {
      if (window.showSuccess) window.showSuccess('Configuración guardada localmente (Backend no disponible)');
      // Forzamos success para la experiencia de usuario si no hay backend aún.
    } finally {
      setIsSaving(false);
    }
  };

  // Session Handlers
  const revokeSession = async (sessionId) => {
    try {
      const res = await fetch(`http://localhost:3000/api/sessions/${sessionId}`, {
        method: 'DELETE',
        headers: { 'Authorization': `Bearer ${getJWTFromStorage()}` }
      });
      if (res.ok) {
        setSessions(prev => prev.filter(s => s.id !== sessionId));
        if (window.showSuccess) window.showSuccess('Sesión revocada con éxito');
      } else {
        throw new Error();
      }
    } catch (e) {
      // Mock revokation
      setSessions(prev => prev.filter(s => s.id !== sessionId));
      if (window.showSuccess) window.showSuccess('Sesión revocada localmente');
    }
  };

  const revokeAllOtherSessions = async () => {
    try {
      const res = await fetch(`http://localhost:3000/api/sessions/others`, {
        method: 'DELETE',
        headers: { 'Authorization': `Bearer ${getJWTFromStorage()}` }
      });
      if (res.ok) {
        setSessions(prev => prev.filter(s => s.current));
        if (window.showSuccess) window.showSuccess('Todas las demás sesiones fueron cerradas');
      } else {
         throw new Error();
      }
    } catch (e) {
      setSessions(prev => prev.filter(s => s.current));
      if (window.showSuccess) window.showSuccess('Sesiones cerradas localmente');
    }
  };

  // Integrations Handlers
  const toggleIntegration = async (integrationKey) => {
    const currentStatus = settings.integrations?.[integrationKey]?.connected || false;
    const newSettings = {
      ...settings,
      integrations: {
        ...settings.integrations,
        [integrationKey]: { connected: !currentStatus, lastSync: new Date().toISOString() }
      }
    };
    setSettings(newSettings);
    
    // Auto-save changes
    try {
      await fetch(`http://localhost:3000/api/settings`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${getJWTFromStorage()}`
        },
        body: JSON.stringify({ organizationId, settings: newSettings })
      });
      if (window.showSuccess) window.showSuccess(`Integración ${!currentStatus ? 'conectada' : 'desconectada'}`);
    } catch (e) {
      if (window.showSuccess) window.showSuccess(`Estado actualizado localmente`);
    }
  };

  const changeTheme = (newTheme) => {
    setSettings({ ...settings, theme: newTheme });
    // Aquí se podría despachar un evento o actualizar la clase del root element si es global
    if (newTheme === 'dark') document.documentElement.classList.add('dark');
    else document.documentElement.classList.remove('dark');
  };

  if (isLoading) {
    return (
      <div className="flex h-full min-h-[calc(100vh-120px)] p-8">
        <div className="w-64 flex-shrink-0 pr-8 space-y-4">
          <div className="skeleton-loader h-8 w-3/4 mb-8"></div>
          {[1,2,3,4,5].map(i => <div key={i} className="skeleton-loader h-12 w-full"></div>)}
        </div>
        <div className="flex-1 bg-[#1b1c20] rounded-2xl p-8 border border-white/[0.04]">
          <div className="skeleton-loader h-8 w-1/3 mb-2"></div>
          <div className="skeleton-loader h-4 w-1/2 mb-8"></div>
          <div className="grid grid-cols-2 gap-8">
            <div className="skeleton-loader h-64 w-full rounded-2xl"></div>
            <div className="skeleton-loader h-64 w-full rounded-2xl"></div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="flex h-full min-h-[calc(100vh-120px)] animate-fadeInUp">
      {/* Sidebar de Configuración */}
      <div className="w-64 flex-shrink-0 pr-8">
        <h2 className="text-2xl font-bold text-white mb-6">Configuración</h2>
        <nav className="space-y-2">
          <button
            onClick={() => setActiveTab('account')}
            className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${
              activeTab === 'account' ? 'bg-blue-500/20 text-blue-400 font-medium' : 'text-gray-400 hover:bg-[#252628] hover:text-white'
            }`}
          >
            <i className="fas fa-user w-5 text-center"></i>
            <span>Perfil y Cuenta</span>
          </button>
          
          <button
            onClick={() => setActiveTab('organization')}
            className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${
              activeTab === 'organization' ? 'bg-purple-500/20 text-purple-400 font-medium' : 'text-gray-400 hover:bg-[#252628] hover:text-white'
            }`}
          >
            <i className="fas fa-building w-5 text-center"></i>
            <span>Organización</span>
          </button>

          <button
            onClick={() => setActiveTab('appearance')}
            className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${
              activeTab === 'appearance' ? 'bg-orange-500/20 text-orange-400 font-medium' : 'text-gray-400 hover:bg-[#252628] hover:text-white'
            }`}
          >
            <i className="fas fa-paint-brush w-5 text-center"></i>
            <span>Apariencia</span>
          </button>

          <button
            onClick={() => setActiveTab('security')}
            className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${
              activeTab === 'security' ? 'bg-red-500/20 text-red-400 font-medium' : 'text-gray-400 hover:bg-[#252628] hover:text-white'
            }`}
          >
            <i className="fas fa-shield-alt w-5 text-center"></i>
            <span>Seguridad y Sesiones</span>
          </button>

          <button
            onClick={() => setActiveTab('integrations')}
            className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${
              activeTab === 'integrations' ? 'bg-emerald-500/20 text-emerald-400 font-medium' : 'text-gray-400 hover:bg-[#252628] hover:text-white'
            }`}
          >
            <i className="fas fa-plug w-5 text-center"></i>
            <span>Integraciones</span>
          </button>
        </nav>
      </div>

      {/* Contenido Principal */}
      <div className="flex-1 bg-[#1b1c20] rounded-2xl p-8 overflow-y-auto custom-scrollbar border border-white/[0.04]">
        
        {/* PESTAÑA: PERFIL Y CUENTA */}
        {activeTab === 'account' && (
          <div className="space-y-8 animate-fadeInUp">
            <div>
              <h3 className="text-xl font-bold text-white mb-1">Perfil de Usuario</h3>
              <p className="text-gray-400 text-sm">Gestiona tu información personal y credenciales</p>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              {/* Información Personal */}
              <form onSubmit={handleSaveProfile} className="space-y-5 bg-[#252628] p-6 rounded-2xl">
                <h4 className="text-white font-semibold mb-4 border-b border-gray-700/50 pb-2">Información Básica</h4>
                <div>
                  <label className="block text-gray-400 text-sm mb-2">Nombre completo</label>
                  <input name="name" type="text" defaultValue={userData.name || ''} className="w-full bg-[#1b1c20] border border-[#35383d] rounded-xl px-4 py-3 text-white focus:outline-none focus:border-blue-500/50" />
                </div>
                <div>
                  <label className="block text-gray-400 text-sm mb-2">Correo electrónico</label>
                  <input type="email" defaultValue={userData.email || ''} readOnly className="w-full bg-[#1b1c20] border border-[#35383d] rounded-xl px-4 py-3 text-gray-500 cursor-not-allowed focus:outline-none" />
                </div>
                <button type="submit" disabled={isSavingProfile} className="w-full py-3 bg-blue-500 text-white rounded-xl hover:bg-blue-600 transition-colors font-medium flex items-center justify-center gap-2 disabled:opacity-50">
                  {isSavingProfile ? <i className="fas fa-spinner fa-spin"></i> : <i className="fas fa-save"></i>}
                  Actualizar Perfil
                </button>
              </form>

              {/* Cambiar Contraseña */}
              <form onSubmit={handleSaveProfile} className="space-y-5 bg-[#252628] p-6 rounded-2xl">
                <h4 className="text-white font-semibold mb-4 border-b border-gray-700/50 pb-2">Cambiar Contraseña</h4>
                <div>
                  <label className="block text-gray-400 text-sm mb-2">Contraseña actual</label>
                  <input name="password" type="password" placeholder="••••••••" className="w-full bg-[#1b1c20] border border-[#35383d] rounded-xl px-4 py-3 text-white focus:outline-none focus:border-blue-500/50" />
                </div>
                <div>
                  <label className="block text-gray-400 text-sm mb-2">Nueva contraseña</label>
                  <input name="newPassword" type="password" placeholder="••••••••" className="w-full bg-[#1b1c20] border border-[#35383d] rounded-xl px-4 py-3 text-white focus:outline-none focus:border-blue-500/50" />
                </div>
                <button type="submit" disabled={isSavingProfile} className="w-full py-3 bg-gray-600 text-white rounded-xl hover:bg-gray-500 transition-colors font-medium flex justify-center items-center gap-2 disabled:opacity-50">
                  {isSavingProfile ? <i className="fas fa-spinner fa-spin"></i> : <i className="fas fa-key"></i>}
                  Actualizar Contraseña
                </button>
              </form>
            </div>

            {/* Zona de Peligro */}
            <div className="border border-red-500/20 bg-red-500/5 p-6 rounded-2xl mt-8">
              <h4 className="text-red-400 font-semibold mb-2">Zona de Peligro</h4>
              <p className="text-gray-400 text-sm mb-4">Si abandonas la organización, perderás el acceso a todos sus datos inmediatamente.</p>
              <button onClick={() => {
                if (confirm('¿Estás seguro de que deseas salir de esta organización? Esta acción no se puede deshacer.')) {
                  if (window.Router) window.Router.logout();
                }
              }} className="px-6 py-2.5 bg-red-500/20 text-red-400 font-medium rounded-xl hover:bg-red-500 hover:text-white transition-colors">
                Salirme de la Organización
              </button>
            </div>
          </div>
        )}

        {/* PESTAÑA: ORGANIZACIÓN */}
        {activeTab === 'organization' && (
          <div className="space-y-8 animate-fadeInUp">
            <div>
              <h3 className="text-xl font-bold text-white mb-1">Detalles de la Organización</h3>
              <p className="text-gray-400 text-sm">Información general de la empresa y preferencias globales</p>
            </div>

            <div className="bg-[#252628] p-6 rounded-2xl max-w-2xl">
              <div className="flex items-center gap-6 mb-8">
                <div className="w-24 h-24 rounded-2xl bg-gradient-to-br from-indigo-500/30 to-purple-500/30 border-2 border-dashed border-gray-600 flex items-center justify-center flex-col cursor-pointer hover:border-purple-500 transition-colors group">
                  <i className="fas fa-camera text-gray-400 text-xl mb-1 group-hover:text-purple-400"></i>
                  <span className="text-[10px] text-gray-500 font-medium">Cambiar Logo</span>
                </div>
                <div>
                  <h4 className="text-white text-lg font-medium">Logotipo de la Empresa</h4>
                  <p className="text-gray-500 text-sm mt-1">Recomendado: 256x256px en formato PNG o JPG</p>
                </div>
              </div>

              <form onSubmit={saveOrganizationSettings} className="space-y-5">
                <div>
                  <label className="block text-gray-400 text-sm mb-2">Nombre de la Organización</label>
                  <input type="text" value={settings.name || ''} onChange={(e) => setSettings({...settings, name: e.target.value})} className="w-full bg-[#1b1c20] border border-[#35383d] rounded-xl px-4 py-3 text-white focus:outline-none focus:border-purple-500/50" />
                </div>
                <div>
                  <label className="block text-gray-400 text-sm mb-2">Moneda Principal</label>
                  <select value={settings.currency || 'MXN'} onChange={(e) => setSettings({...settings, currency: e.target.value})} className="w-full bg-[#1b1c20] border border-[#35383d] rounded-xl px-4 py-3 text-white focus:outline-none focus:border-purple-500/50">
                    <option value="MXN">Peso Mexicano (MXN)</option>
                    <option value="USD">Dólar Estadounidense (USD)</option>
                    <option value="EUR">Euro (EUR)</option>
                  </select>
                </div>

                {/* Código de organización SOLO PARA ADMINS */}
                {userData.role === 'admin' && (
                  <div className="p-4 bg-purple-500/10 border border-purple-500/20 rounded-xl mt-6">
                    <label className="block text-purple-300 font-medium text-sm mb-2">
                      <i className="fas fa-key mr-2"></i>Código Secreto de la Organización
                    </label>
                    <div className="flex gap-2">
                      <input type="text" readOnly defaultValue={organizationId || "ORG-NO-ID"} className="flex-1 bg-[#1b1c20] border border-purple-500/30 rounded-lg px-4 py-2 text-white font-mono" />
                      <button type="button" onClick={() => {
                        navigator.clipboard.writeText(organizationId || "");
                        if (window.showSuccess) window.showSuccess("Código copiado al portapapeles");
                      }} className="px-4 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors">
                        <i className="fas fa-copy"></i>
                      </button>
                    </div>
                    <p className="text-xs text-purple-400/70 mt-2">Comparte este código solo con el personal de confianza para que se unan a la organización.</p>
                  </div>
                )}

                <div className="pt-4">
                  <button type="submit" disabled={isSaving} className="px-6 py-3 bg-purple-500 text-white rounded-xl hover:bg-purple-600 transition-colors font-medium flex gap-2 items-center disabled:opacity-50">
                    {isSaving ? <i className="fas fa-spinner fa-spin"></i> : <i className="fas fa-save"></i>}
                    Guardar Cambios
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}

        {/* PESTAÑA: APARIENCIA */}
        {activeTab === 'appearance' && (
          <div className="space-y-8 animate-fadeInUp">
            <div>
              <h3 className="text-xl font-bold text-white mb-1">Personalización y Tema</h3>
              <p className="text-gray-400 text-sm">Adapta Esperiency a tu estilo de trabajo</p>
            </div>

            <div className="bg-[#252628] p-6 rounded-2xl max-w-3xl">
              <h4 className="text-white font-medium mb-6">Tema del Sistema</h4>
              
              <div className="grid grid-cols-3 gap-4 mb-8">
                {/* Claro */}
                <button onClick={() => changeTheme('light')} className="flex flex-col items-center gap-3 group">
                  <div className={`w-full aspect-video rounded-xl border-2 ${settings.theme === 'light' ? 'border-orange-500 bg-gray-100' : 'border-gray-700 bg-gray-100 group-hover:border-orange-500'} flex items-center justify-center transition-all relative`}>
                    <i className={`fas fa-sun text-4xl ${settings.theme === 'light' ? 'text-orange-400' : 'text-gray-400 group-hover:text-orange-400'}`}></i>
                    {settings.theme === 'light' && (
                      <div className="absolute top-2 right-2 w-5 h-5 bg-orange-500 rounded-full flex items-center justify-center">
                        <i className="fas fa-check text-white text-[10px]"></i>
                      </div>
                    )}
                  </div>
                  <span className={`font-medium ${settings.theme === 'light' ? 'text-white' : 'text-gray-400 group-hover:text-white'} transition-colors`}>Claro</span>
                </button>
                
                {/* Oscuro */}
                <button onClick={() => changeTheme('dark')} className="flex flex-col items-center gap-3 group">
                  <div className={`w-full aspect-video rounded-xl border-2 ${settings.theme === 'dark' ? 'border-orange-500 bg-[#1b1c20]' : 'border-gray-700 bg-[#1b1c20] group-hover:border-orange-500'} flex items-center justify-center relative overflow-hidden transition-all`}>
                    {settings.theme === 'dark' && <div className="absolute inset-0 bg-orange-500/10"></div>}
                    <i className={`fas fa-moon text-4xl ${settings.theme === 'dark' ? 'text-orange-400' : 'text-gray-400 group-hover:text-orange-400'} z-10`}></i>
                    {settings.theme === 'dark' && (
                      <div className="absolute top-2 right-2 w-5 h-5 bg-orange-500 rounded-full flex items-center justify-center">
                        <i className="fas fa-check text-white text-[10px]"></i>
                      </div>
                    )}
                  </div>
                  <span className={`font-medium ${settings.theme === 'dark' ? 'text-white' : 'text-gray-400 group-hover:text-white'} transition-colors`}>Oscuro</span>
                </button>

                {/* Sistema */}
                <button onClick={() => changeTheme('system')} className="flex flex-col items-center gap-3 group">
                  <div className={`w-full aspect-video rounded-xl border-2 ${settings.theme === 'system' ? 'border-orange-500 bg-gradient-to-r from-[#1b1c20] to-gray-200' : 'border-gray-700 bg-gradient-to-r from-[#1b1c20] to-gray-200 group-hover:border-orange-500'} flex items-center justify-center transition-all relative`}>
                    <i className={`fas fa-desktop text-4xl ${settings.theme === 'system' ? 'text-orange-400 mix-blend-difference' : 'text-gray-400 group-hover:text-orange-400 mix-blend-difference'}`}></i>
                    {settings.theme === 'system' && (
                      <div className="absolute top-2 right-2 w-5 h-5 bg-orange-500 rounded-full flex items-center justify-center">
                        <i className="fas fa-check text-white text-[10px]"></i>
                      </div>
                    )}
                  </div>
                  <span className={`font-medium ${settings.theme === 'system' ? 'text-white' : 'text-gray-400 group-hover:text-white'} transition-colors`}>Automático</span>
                </button>
              </div>

              <div className="border-t border-gray-700/50 pt-6">
                <h4 className="text-white font-medium mb-4">Color de Acento</h4>
                <div className="flex gap-4">
                  {['#fae0d1', '#3b82f6', '#10b981', '#8b5cf6', '#ef4444'].map((color, i) => (
                    <button 
                      key={i} 
                      onClick={() => setSettings({...settings, accentColor: color})}
                      className={`w-10 h-10 rounded-full flex items-center justify-center transition-transform hover:scale-110 ${settings.accentColor === color ? `ring-2 ring-offset-2 ring-offset-[#252628]` : ''}`} 
                      style={{ backgroundColor: color, '--tw-ring-color': color }}
                    >
                      {settings.accentColor === color && <i className={`fas fa-check ${['#fae0d1', '#10b981'].includes(color) ? 'text-[#1b1c20]' : 'text-white'} text-xs`}></i>}
                    </button>
                  ))}
                </div>
              </div>
              <div className="pt-6 mt-6 border-t border-gray-700/50">
                  <button onClick={saveOrganizationSettings} disabled={isSaving} className="px-6 py-2.5 bg-orange-500 text-white rounded-xl hover:bg-orange-600 transition-colors font-medium flex gap-2 items-center disabled:opacity-50">
                    {isSaving ? <i className="fas fa-spinner fa-spin"></i> : <i className="fas fa-save"></i>}
                    Guardar Apariencia
                  </button>
              </div>
            </div>
            
            <div className="bg-[#252628] p-6 rounded-2xl max-w-3xl flex items-center justify-between">
              <div>
                <h4 className="text-white font-medium">Configuración Avanzada</h4>
                <p className="text-gray-400 text-sm mt-1">Ir al gestor avanzado de fuentes y UI.</p>
              </div>
              <button onClick={() => window.location.href = '/signin/start/config/theme/'} className="px-5 py-2.5 bg-[#1b1c20] text-white border border-gray-700 hover:border-orange-500 rounded-xl transition-all">
                Ir a Diseñador <i className="fas fa-external-link-alt ml-2 text-xs"></i>
              </button>
            </div>
          </div>
        )}

        {/* PESTAÑA: SEGURIDAD Y SESIONES */}
        {activeTab === 'security' && (
          <div className="space-y-8 animate-fadeInUp">
            <div>
              <h3 className="text-xl font-bold text-white mb-1">Seguridad y Sesiones</h3>
              <p className="text-gray-400 text-sm">Controla desde dónde has iniciado sesión</p>
            </div>

            <div className="bg-[#252628] rounded-2xl overflow-hidden border border-gray-800">
              <div className="p-6 border-b border-gray-800 flex justify-between items-center bg-[#1e1f23]">
                <h4 className="text-white font-medium">Sesiones Activas</h4>
                <button onClick={revokeAllOtherSessions} className="text-xs px-3 py-1.5 bg-red-500/10 text-red-400 rounded-lg hover:bg-red-500/20 transition-colors">
                  Cerrar todas las demás
                </button>
              </div>
              
              <div className="divide-y divide-gray-800">
                {sessions.map(session => (
                  <div key={session.id} className={`p-5 flex items-center gap-4 ${session.current ? 'bg-green-500/5' : 'hover:bg-[#2a2b2f] transition-colors'}`}>
                    <div className={`w-12 h-12 rounded-xl flex items-center justify-center text-xl shrink-0 ${session.current ? 'bg-green-500/20 text-green-400' : 'bg-gray-800 text-gray-400'}`}>
                      <i className={`fas ${session.device.toLowerCase().includes('phone') ? 'fa-mobile-alt' : 'fa-laptop'}`}></i>
                    </div>
                    <div className="flex-1">
                      <div className="flex items-center gap-2">
                        <h5 className="text-white font-medium">{session.device}</h5>
                        {session.current && <span className="text-[10px] uppercase font-bold tracking-wider px-2 py-0.5 rounded-full bg-green-500/20 text-green-400">Actual</span>}
                      </div>
                      <p className="text-gray-500 text-sm mt-0.5">
                        {session.location} • {session.ip} {session.lastSeen && `• ${session.lastSeen}`}
                      </p>
                    </div>
                    {!session.current && (
                      <button onClick={() => revokeSession(session.id)} className="text-gray-500 hover:text-red-400 px-3 py-2 text-sm transition-colors font-medium">
                        Revocar
                      </button>
                    )}
                  </div>
                ))}
                
                {sessions.length === 0 && (
                  <div className="p-8 text-center text-gray-500">
                    No se encontraron sesiones activas.
                  </div>
                )}
              </div>
            </div>

            {/* Configuración 2FA */}
            <div className="bg-[#252628] p-6 rounded-2xl flex items-center justify-between">
              <div>
                <h4 className="text-white font-medium mb-1">Autenticación de Dos Factores (2FA)</h4>
                <p className="text-gray-400 text-sm">Añade una capa extra de seguridad a tu cuenta.</p>
              </div>
              <button className="px-5 py-2.5 bg-gray-700 text-white rounded-xl hover:bg-gray-600 transition-colors font-medium text-sm">
                Configurar
              </button>
            </div>
          </div>
        )}

        {/* PESTAÑA: INTEGRACIONES */}
        {activeTab === 'integrations' && (
          <div className="space-y-8 animate-fadeInUp">
            <div>
              <h3 className="text-xl font-bold text-white mb-1">Aplicaciones Conectadas</h3>
              <p className="text-gray-400 text-sm">Extiende la funcionalidad de Esperiency conectando con otros servicios</p>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              
              {/* WhatsApp */}
              <div className={`bg-[#252628] rounded-2xl p-6 border ${settings.integrations?.whatsapp?.connected ? 'border-emerald-500/20' : 'border-gray-800'} relative overflow-hidden transition-colors`}>
                <div className={`absolute -top-10 -right-10 text-9xl ${settings.integrations?.whatsapp?.connected ? 'text-emerald-500' : 'text-gray-500'} opacity-5`}><i className="fab fa-whatsapp"></i></div>
                <div className="flex items-center justify-between mb-4 relative z-10">
                  <div className="flex items-center gap-3">
                    <div className={`w-12 h-12 rounded-xl ${settings.integrations?.whatsapp?.connected ? 'bg-emerald-500/20' : 'bg-gray-800'} flex items-center justify-center transition-colors`}>
                      <i className={`fab fa-whatsapp text-2xl ${settings.integrations?.whatsapp?.connected ? 'text-emerald-400' : 'text-gray-500'}`}></i>
                    </div>
                    <div>
                      <h4 className="text-white font-bold">WhatsApp Business</h4>
                      <p className={`${settings.integrations?.whatsapp?.connected ? 'text-emerald-400' : 'text-gray-500'} text-xs font-medium uppercase tracking-wider`}>
                        {settings.integrations?.whatsapp?.connected ? 'Conectado' : 'No conectado'}
                      </p>
                    </div>
                  </div>
                  <button onClick={() => toggleIntegration('whatsapp')} className={`px-3 py-1.5 border rounded-lg text-sm font-medium transition-colors ${settings.integrations?.whatsapp?.connected ? 'border-red-500/50 text-red-400 hover:bg-red-500/10' : 'bg-emerald-500 text-white hover:bg-emerald-600 border-transparent'}`}>
                    {settings.integrations?.whatsapp?.connected ? 'Desconectar' : 'Conectar'}
                  </button>
                </div>
                <p className="text-gray-400 text-sm relative z-10 mb-4">Envía notificaciones de cobro automáticas y recibe mensajes de soporte directamente por WhatsApp.</p>
                {settings.integrations?.whatsapp?.connected && (
                  <div className="bg-[#1b1c20] p-3 rounded-xl border border-gray-800">
                    <div className="flex justify-between items-center text-sm">
                      <span className="text-gray-500">Última sincronización</span>
                      <span className="text-gray-300">Reciente</span>
                    </div>
                  </div>
                )}
              </div>

              {/* Stripe */}
              <div className={`bg-[#252628] rounded-2xl p-6 border ${settings.integrations?.stripe?.connected ? 'border-blue-500/20' : 'border-gray-800'} relative overflow-hidden transition-colors`}>
                <div className="flex items-center justify-between mb-4 relative z-10">
                  <div className="flex items-center gap-3">
                    <div className={`w-12 h-12 rounded-xl ${settings.integrations?.stripe?.connected ? 'bg-[#635BFF]/10' : 'bg-gray-800'} flex items-center justify-center transition-colors`}>
                      <i className={`fab fa-stripe-s text-2xl ${settings.integrations?.stripe?.connected ? 'text-[#635BFF]' : 'text-gray-500'}`}></i>
                    </div>
                    <div>
                      <h4 className="text-white font-bold">Stripe Payments</h4>
                      <p className={`${settings.integrations?.stripe?.connected ? 'text-blue-400' : 'text-gray-500'} text-xs font-medium uppercase tracking-wider`}>
                        {settings.integrations?.stripe?.connected ? 'Conectado' : 'No conectado'}
                      </p>
                    </div>
                  </div>
                  <button onClick={() => toggleIntegration('stripe')} className={`px-4 py-1.5 rounded-lg text-sm font-medium transition-colors ${settings.integrations?.stripe?.connected ? 'border border-red-500/50 text-red-400 hover:bg-red-500/10' : 'bg-blue-500 text-white hover:bg-blue-600 border-transparent'}`}>
                    {settings.integrations?.stripe?.connected ? 'Desconectar' : 'Conectar'}
                  </button>
                </div>
                <p className="text-gray-400 text-sm relative z-10">Permite a tus inquilinos pagar sus rentas en línea usando tarjetas de crédito o débito con la seguridad de Stripe.</p>
              </div>

              {/* Google Drive */}
              <div className={`bg-[#252628] rounded-2xl p-6 border ${settings.integrations?.googleDrive?.connected ? 'border-blue-500/20' : 'border-gray-800'} relative overflow-hidden transition-colors`}>
                <div className="flex items-center justify-between mb-4 relative z-10">
                  <div className="flex items-center gap-3">
                    <div className={`w-12 h-12 rounded-xl ${settings.integrations?.googleDrive?.connected ? 'bg-blue-500/10' : 'bg-gray-800'} flex items-center justify-center transition-colors`}>
                      <i className={`fab fa-google-drive text-2xl ${settings.integrations?.googleDrive?.connected ? 'text-blue-400' : 'text-gray-500'}`}></i>
                    </div>
                    <div>
                      <h4 className="text-white font-bold">Google Drive</h4>
                      <p className={`${settings.integrations?.googleDrive?.connected ? 'text-blue-400' : 'text-gray-500'} text-xs font-medium uppercase tracking-wider`}>
                        {settings.integrations?.googleDrive?.connected ? 'Conectado' : 'No conectado'}
                      </p>
                    </div>
                  </div>
                  <button onClick={() => toggleIntegration('googleDrive')} className={`px-4 py-1.5 rounded-lg text-sm font-medium transition-colors ${settings.integrations?.googleDrive?.connected ? 'border border-red-500/50 text-red-400 hover:bg-red-500/10' : 'bg-blue-500 text-white hover:bg-blue-600 border-transparent'}`}>
                    {settings.integrations?.googleDrive?.connected ? 'Desconectar' : 'Conectar'}
                  </button>
                </div>
                <p className="text-gray-400 text-sm relative z-10">Respalda contratos, identificaciones y recibos automáticamente en una carpeta segura de tu nube.</p>
              </div>

            </div>
          </div>
        )}
      </div>
    </div>
  );
};

window.SettingsPage = SettingsPage;
