// AdminMobileApp — Interfaz Móvil Simplificada y Dedicada para Celulares (PWA)
const AdminMobileApp = () => {
  const [authenticated, setAuthenticated] = React.useState(() => !!sessionStorage.getItem('eadq_admin_token'));
  const [password, setPassword] = React.useState('');
  const [authError, setAuthError] = React.useState(false);
  const [authLoading, setAuthLoading] = React.useState(false);
  
  // PWA/Install states
  const [installPromptEvent, setInstallPromptEvent] = React.useState(null);
  const [showInstallCard, setShowInstallCard] = React.useState(() => {
    const dismissed = sessionStorage.getItem('eadq_install_prompt_dismissed') === 'true';
    const isStandalone = window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone;
    const isMobile = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
    return !isStandalone && isMobile && !dismissed;
  });
  const [showIosInstructions, setShowIosInstructions] = React.useState(false);

  React.useEffect(() => {
    const handlePrompt = () => {
      setInstallPromptEvent(window.deferredPrompt);
    };
    window.addEventListener('beforeinstallprompt-triggered', handlePrompt);
    if (window.deferredPrompt) {
      setInstallPromptEvent(window.deferredPrompt);
    }
    return () => window.removeEventListener('beforeinstallprompt-triggered', handlePrompt);
  }, []);

  const handleInstallClick = async () => {
    if (installPromptEvent) {
      installPromptEvent.prompt();
      const { outcome } = await installPromptEvent.userChoice;
      if (outcome === 'accepted') {
        setInstallPromptEvent(null);
        window.deferredPrompt = null;
        setShowInstallCard(false);
      }
    } else {
      const isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
      if (isIOS) {
        setShowIosInstructions(true);
      } else {
        showDialogNotification("Instalación", "Para instalar, ve al menú de tu navegador y selecciona 'Instalar aplicación' o 'Agregar a la pantalla principal'.", "success");
      }
    }
  };

  const handleDismissInstall = () => {
    sessionStorage.setItem('eadq_install_prompt_dismissed', 'true');
    setShowInstallCard(false);
  };
  
  // Tab activa: 'agenda', 'servicios', 'ajustes'
  const [activeTab, setActiveTab] = React.useState('agenda');
  
  // Datos
  const [appointments, setAppointments] = React.useState([]);
  const [services, setServices] = React.useState([]);
  const [categories, setCategories] = React.useState([]);
  const [selectedDateStr, setSelectedDateStr] = React.useState(() => {
    const today = new Date();
    // Offset local para evitar diferencias de zona horaria
    const offset = today.getTimezoneOffset();
    const localToday = new Date(today.getTime() - (offset*60*1000));
    return localToday.toISOString().split('T')[0];
  });
  const [loading, setLoading] = React.useState(false);
  const [syncing, setSyncing] = React.useState(false);
  
  // Edición de Servicio
  const [editingService, setEditingService] = React.useState(null);
  const [svcPrice, setSvcPrice] = React.useState('');
  const [svcDuration, setSvcDuration] = React.useState('');
  const [svcShowHome, setSvcShowHome] = React.useState(false);
  
  // Edición de Notas de Cita
  const [editingNotesAppt, setEditingNotesAppt] = React.useState(null);
  const [apptNotes, setApptNotes] = React.useState('');
  const [savingNotes, setSavingNotes] = React.useState(false);

  // Alertas Push
  const [pushSupported, setPushSupported] = React.useState(false);
  const [pushActive, setPushActive] = React.useState(false);
  const [pushLoading, setPushLoading] = React.useState(false);

  // Configuración del Sitio / Apariencia
  const [darkMode, setDarkMode] = React.useState(() => localStorage.getItem('eadq_dark_mode') === 'true');
  const [selectedTheme, setSelectedTheme] = React.useState(() => localStorage.getItem('eadq_theme_type') || 'luxury');
  
  // Diálogos y notificaciones flotantes
  const [notification, setNotification] = React.useState({ show: false, title: '', message: '', type: 'success' });
  const notificationTimeoutRef = React.useRef(null);

  const showDialogNotification = (title, message, type = 'success') => {
    if (notificationTimeoutRef.current) {
      clearTimeout(notificationTimeoutRef.current);
    }
    setNotification({ show: true, title, message, type });
    notificationTimeoutRef.current = setTimeout(() => {
      setNotification(prev => ({ ...prev, show: false }));
    }, 4000);
  };

  // Auxiliar para peticiones autenticadas
  const fetchWithAuth = async (url, options = {}) => {
    const token = sessionStorage.getItem('eadq_admin_token');
    const headers = {
      'Content-Type': 'application/json',
      ...options.headers,
    };
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }
    const res = await fetch(url, { ...options, headers });
    if (res.status === 401 || res.status === 403) {
      sessionStorage.removeItem('eadq_admin_token');
      setAuthenticated(false);
      return;
    }
    if (!res.ok) {
      const err = await res.json().catch(() => ({}));
      throw new Error(err.error || 'Error en la petición.');
    }
    return res.json();
  };

  const handleLogin = async (e) => {
    e.preventDefault();
    setAuthLoading(true);
    setAuthError(false);
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username: 'fran', password })
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.error || 'Credenciales incorrectas.');
      }
      const data = await res.json();
      sessionStorage.setItem('eadq_admin_token', data.token);
      setAuthenticated(true);
      showDialogNotification("¡Bienvenida, Fran! 🌿", "Sesión iniciada correctamente.");
    } catch (err) {
      setAuthError(true);
      showDialogNotification("Error de Acceso", err.message, "error");
    } finally {
      setAuthLoading(false);
    }
  };

  const handleLogout = () => {
    setAuthenticated(false);
    sessionStorage.removeItem('eadq_admin_token');
    setPassword('');
    showDialogNotification("Sesión Cerrada", "Has salido del panel administrativo.");
  };

  // Cargar datos principales
  const loadData = async () => {
    if (!authenticated) return;
    setLoading(true);
    try {
      const [apptsData, svcsData, catsData] = await Promise.all([
        fetchWithAuth('/api/appointments'),
        fetchWithAuth('/api/services'),
        fetchWithAuth('/api/categories')
      ]);
      if (apptsData) setAppointments(apptsData);
      if (svcsData) setServices(svcsData);
      if (catsData) setCategories(catsData);
    } catch (err) {
      console.error(err);
      showDialogNotification("Error al cargar datos", err.message, "error");
    } finally {
      setLoading(false);
    }
  };

  // Verificar suscripción push
  const checkPushSubscription = async () => {
    if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
      setPushSupported(false);
      return;
    }
    setPushSupported(true);
    try {
      const reg = await navigator.serviceWorker.ready;
      const sub = await reg.pushManager.getSubscription();
      setPushActive(!!sub);
    } catch (err) {
      console.error('Error push:', err);
    }
  };

  const handleTogglePush = async () => {
    if (!pushSupported) return;
    setPushLoading(true);
    try {
      if (pushActive) {
        const reg = await navigator.serviceWorker.ready;
        const sub = await reg.pushManager.getSubscription();
        if (sub) {
          await sub.unsubscribe();
          try {
            await fetchWithAuth('/api/push/unregister', {
              method: 'POST',
              body: JSON.stringify({ endpoint: sub.endpoint })
            });
          } catch(err) {
            console.error(err);
          }
        }
        setPushActive(false);
        showDialogNotification("Notificaciones desactivadas", "Ya no recibirás alertas push en este celular.");
      } else {
        const permission = await Notification.requestPermission();
        if (permission !== 'granted') {
          showDialogNotification("Permiso denegado", "Debes activar las notificaciones en la configuración de tu celular.", "error");
          setPushLoading(false);
          return;
        }
        const keyData = await fetchWithAuth('/api/push/key');
        if (!keyData || !keyData.publicKey) {
          throw new Error("No se pudo obtener la llave pública.");
        }
        const reg = await navigator.serviceWorker.ready;
        
        const urlB64ToUint8Array = (base64String) => {
          const padding = '='.repeat((4 - base64String.length % 4) % 4);
          const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/');
          const rawData = window.atob(base64);
          const outputArray = new Uint8Array(rawData.length);
          for (let i = 0; i < rawData.length; ++i) {
            outputArray[i] = rawData.charCodeAt(i);
          }
          return outputArray;
        };

        const convertedKey = urlB64ToUint8Array(keyData.publicKey);
        const sub = await reg.pushManager.subscribe({
          userVisibleOnly: true,
          applicationServerKey: convertedKey
        });

        await fetchWithAuth('/api/push/register', {
          method: 'POST',
          body: JSON.stringify(sub)
        });
        setPushActive(true);
        showDialogNotification("¡Alertas Activas! 🌿", "Recibirás notificaciones al instante de nuevas citas.");
      }
    } catch(err) {
      console.error(err);
      showDialogNotification("Error de Configuración", err.message, "error");
    } finally {
      setPushLoading(false);
    }
  };

  const handleTestPush = async () => {
    try {
      showDialogNotification("Enviando...", "Enviando alerta de prueba...");
      await fetchWithAuth('/api/push/test', { method: 'POST' });
    } catch(err) {
      showDialogNotification("Error de Prueba", err.message, "error");
    }
  };

  const handleSyncCalendar = async () => {
    setSyncing(true);
    try {
      showDialogNotification("Sincronizando...", "Actualizando eventos con Google Calendar...");
      const syncRes = await fetchWithAuth('/api/appointments/sync', { method: 'POST' });
      await fetchWithAuth('/api/appointments/bulk-sync-calendar', { method: 'POST' });
      showDialogNotification("¡Sincronización Exitosa!", `Agregadas: ${syncRes.inserted}, Actualizadas: ${syncRes.updated}`);
      loadData();
    } catch(err) {
      showDialogNotification("Error de Sincronización", err.message, "error");
    } finally {
      setSyncing(false);
    }
  };

  // Modificar estado de cita
  const handleUpdateStatus = async (apptId, newStatus) => {
    try {
      showDialogNotification("Actualizando...", "Cambiando estado de la cita...");
      await fetchWithAuth(`/api/appointments/${apptId}/status`, {
        method: 'PUT',
        body: JSON.stringify({ status: newStatus })
      });
      showDialogNotification("Cita Actualizada", `El estado ha cambiado a: ${newStatus === 'confirmed' ? 'Confirmada' : newStatus === 'cancelled' ? 'Cancelada' : 'Completada'}`);
      
      // Sincronizar en segundo plano con Google Calendar
      fetchWithAuth('/api/appointments/bulk-sync-calendar', { method: 'POST' }).catch(console.error);
      
      loadData();
    } catch(err) {
      showDialogNotification("Error al actualizar", err.message, "error");
    }
  };

  // Guardar edición de servicio
  const handleSaveService = async (e) => {
    e.preventDefault();
    if (!editingService) return;
    try {
      showDialogNotification("Guardando...", "Actualizando datos del servicio...");
      await fetchWithAuth(`/api/services/${editingService.id}`, {
        method: 'PUT',
        body: JSON.stringify({
          name: editingService.name,
          price: svcPrice,
          duration: svcDuration,
          category_id: editingService.category_id,
          nomenclature: editingService.nomenclature,
          show_on_home: svcShowHome,
          home_order: editingService.home_order,
          needs_coordination: editingService.needs_coordination,
          description: editingService.description || editingService.desc,
          benefits: editingService.benefits,
          tag: editingService.tag,
          is_promo: editingService.is_promo
        })
      });
      showDialogNotification("Servicio Guardado", "Los precios y configuraciones han sido actualizados.");
      setEditingService(null);
      loadData();
    } catch (err) {
      showDialogNotification("Error al guardar", err.message, "error");
    }
  };

  // Guardar edición de notas
  const handleSaveNotes = async (e) => {
    e.preventDefault();
    if (!editingNotesAppt) return;
    setSavingNotes(true);
    try {
      await fetchWithAuth(`/api/appointments/${editingNotesAppt.id}/notes`, {
        method: 'PUT',
        body: JSON.stringify({ notes: apptNotes })
      });
      showDialogNotification("Notas Guardadas", "Se han registrado las anotaciones de la cita.");
      setEditingNotesAppt(null);
      loadData();
    } catch(err) {
      showDialogNotification("Error al guardar notas", err.message, "error");
    } finally {
      setSavingNotes(false);
    }
  };

  // Efectos de carga inicial
  React.useEffect(() => {
    if (authenticated) {
      loadData();
      checkPushSubscription();
    }
  }, [authenticated]);

  React.useEffect(() => {
    localStorage.setItem('eadq_dark_mode', darkMode);
  }, [darkMode]);

  React.useEffect(() => {
    localStorage.setItem('eadq_theme_type', selectedTheme);
  }, [selectedTheme]);

  // Generar los próximos 7 días en horizontal
  const getNext7Days = () => {
    const arr = [];
    const days = ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'];
    for (let i = 0; i < 7; i++) {
      const d = new Date();
      d.setDate(d.getDate() + i);
      arr.push({
        dateObj: d,
        dayName: days[d.getDay()],
        dayNum: d.getDate(),
        dateStr: d.toISOString().split('T')[0]
      });
    }
    return arr;
  };
  const weekDays = React.useMemo(getNext7Days, []);

  // Citas del día seleccionado
  const dayAppointments = React.useMemo(() => {
    return appointments.filter(a => a.date === selectedDateStr && a.status !== 'cancelled');
  }, [appointments, selectedDateStr]);

  // Renderizar la vista de Login
  if (!authenticated) {
    return (
      <div style={{
        minHeight: '100dvh',
        background: darkMode ? '#121212' : '#FAFAF8',
        color: darkMode ? '#fff' : '#1a1a1a',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '30px 20px',
        fontFamily: "'Outfit', sans-serif",
        transition: 'all 0.3s ease-in-out'
      }}>
        <div style={{ width: '100%', maxWidth: 360, textAlign: 'center' }}>
          <div style={{
            fontFamily: "'Cormorant Garamond', serif",
            fontSize: 36,
            fontWeight: 300,
            fontStyle: 'italic',
            color: '#88C9C1',
            marginBottom: 8
          }}>
            El Arte de Quererte
          </div>
          <div style={{
            fontFamily: "'Outfit', sans-serif",
            fontSize: 10,
            letterSpacing: 4,
            textTransform: 'uppercase',
            color: '#C9A96E',
            marginBottom: 44,
            fontWeight: 600
          }}>
            App de Administración
          </div>

          {showInstallCard && (
            <div style={{
              background: darkMode ? 'rgba(30, 30, 30, 0.9)' : '#fff',
              border: '1.5px solid #C9A96E',
              borderRadius: 20,
              padding: '20px 18px',
              marginBottom: 20,
              textAlign: 'left',
              position: 'relative',
              boxShadow: '0 8px 30px rgba(201, 169, 110, 0.15)',
              animation: 'fadeIn 0.3s ease-out'
            }}>
              <button 
                onClick={handleDismissInstall}
                type="button"
                style={{
                  position: 'absolute',
                  top: 12,
                  right: 12,
                  background: 'none',
                  border: 'none',
                  color: '#7a7a7a',
                  fontSize: 16,
                  cursor: 'pointer'
                }}
              >
                ✕
              </button>
              <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 10 }}>
                <div style={{
                  width: 36,
                  height: 36,
                  borderRadius: 10,
                  background: 'rgba(136, 201, 193, 0.15)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: 20
                }}>
                  📲
                </div>
                <div>
                  <h4 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 18, fontWeight: 700, color: darkMode ? '#fff' : '#1a1a1a', margin: 0 }}>
                    Instalar Aplicación
                  </h4>
                  <div style={{ fontSize: 9, color: '#C9A96E', letterSpacing: 1, textTransform: 'uppercase', fontWeight: 600, marginTop: 1 }}>El Arte de Quererte</div>
                </div>
              </div>
              <p style={{ fontSize: 12, color: '#7a7a7a', marginBottom: 14, lineHeight: '1.4' }}>
                Agrega un acceso directo en tu pantalla de inicio. Inicia más rápido y activa alertas al instante en tu celular.
              </p>
              
              {/iPhone|iPad|iPod/i.test(navigator.userAgent) ? (
                <div>
                  <button 
                    onClick={() => setShowIosInstructions(true)}
                    type="button"
                    style={{
                      width: '100%',
                      padding: '10px 14px',
                      borderRadius: 10,
                      background: '#88C9C1',
                      border: 'none',
                      color: '#1a1a1a',
                      fontSize: 12,
                      fontWeight: 700,
                      cursor: 'pointer'
                    }}
                  >
                    ¿Cómo Instalar en iPhone? 📤
                  </button>
                </div>
              ) : (
                <button 
                  onClick={handleInstallClick}
                  type="button"
                  style={{
                    width: '100%',
                    padding: '10px 14px',
                    borderRadius: 10,
                    background: '#88C9C1',
                    border: 'none',
                    color: '#1a1a1a',
                    fontSize: 12,
                    fontWeight: 700,
                    cursor: 'pointer'
                  }}
                >
                  Instalar Ahora 🌿
                </button>
              )}

              {showIosInstructions && (
                <div style={{
                  marginTop: 12,
                  padding: 12,
                  borderRadius: 10,
                  background: darkMode ? '#222' : '#f9f9f9',
                  border: `1px solid ${darkMode ? '#333' : '#eee'}`,
                  fontSize: 11.5,
                  color: darkMode ? '#ccc' : '#444',
                  lineHeight: '1.4'
                }}>
                  <div style={{ fontWeight: 700, marginBottom: 6, color: '#C9A96E' }}>Instrucciones para Safari:</div>
                  <div style={{ marginBottom: 4 }}>1. Presiona el botón **Compartir** 📤 en la barra inferior.</div>
                  <div style={{ marginBottom: 4 }}>2. Selecciona **"Agregar al Inicio"** 📲.</div>
                  <div>3. ¡Listo! Abre la app desde tu pantalla principal.</div>
                </div>
              )}
            </div>
          )}

          <form onSubmit={handleLogin} style={{
            background: darkMode ? 'rgba(30, 30, 30, 0.75)' : '#fff',
            padding: '32px 24px',
            borderRadius: 24,
            border: `1.5px solid ${darkMode ? 'rgba(255,255,255,0.06)' : 'rgba(201, 169, 110, 0.22)'}`,
            boxShadow: '0 10px 30px rgba(136, 201, 193, 0.04)',
            textAlign: 'left'
          }}>
            <h3 style={{
              fontFamily: "'Cormorant Garamond', serif",
              fontSize: 22,
              fontWeight: 600,
              marginBottom: 20,
              color: darkMode ? '#fff' : '#1a1a1a'
            }}>
              Ingreso Administradora
            </h3>

            <div style={{ marginBottom: 16 }}>
              <label style={{ fontSize: 11, letterSpacing: 1, textTransform: 'uppercase', color: '#7a7a7a', display: 'block', marginBottom: 6, fontWeight: 600 }}>Usuario</label>
              <input 
                type="text" 
                value="fran" 
                disabled 
                style={{
                  width: '100%',
                  padding: '12px 16px',
                  borderRadius: 12,
                  border: `1px solid ${darkMode ? '#333' : '#eee'}`,
                  background: darkMode ? '#1a1a1a' : '#f5f5f5',
                  color: '#777',
                  fontSize: 14,
                  outline: 'none'
                }}
              />
            </div>

            <div style={{ marginBottom: 24 }}>
              <label style={{ fontSize: 11, letterSpacing: 1, textTransform: 'uppercase', color: '#7a7a7a', display: 'block', marginBottom: 6, fontWeight: 600 }}>Contraseña</label>
              <input 
                type="password" 
                value={password}
                onChange={e => setPassword(e.target.value)}
                placeholder="Ingresa tu contraseña"
                required
                style={{
                  width: '100%',
                  padding: '12px 16px',
                  borderRadius: 12,
                  border: `1.5px solid ${darkMode ? 'rgba(255,255,255,0.15)' : 'rgba(201, 169, 110, 0.25)'}`,
                  background: darkMode ? '#222' : '#fff',
                  color: darkMode ? '#fff' : '#1a1a1a',
                  fontSize: 14,
                  outline: 'none',
                  boxSizing: 'border-box'
                }}
              />
            </div>

            <button 
              type="submit" 
              disabled={authLoading}
              style={{
                width: '100%',
                padding: '14px',
                borderRadius: 12,
                background: '#88C9C1',
                color: '#1a1a1a',
                border: 'none',
                fontFamily: "'Outfit', sans-serif",
                fontWeight: 700,
                fontSize: 12,
                letterSpacing: 2,
                textTransform: 'uppercase',
                cursor: 'pointer',
                boxShadow: '0 8px 20px rgba(136, 201, 193, 0.2)'
              }}
            >
              {authLoading ? 'Ingresando...' : 'Entrar a la App'}
            </button>
          </form>

          {!showInstallCard && !pushSupported && /iPhone|iPad|iPod/i.test(navigator.userAgent) && (
            <div style={{
              marginTop: 24,
              padding: '12px 16px',
              borderRadius: 14,
              background: 'rgba(136, 201, 193, 0.08)',
              border: '1px solid rgba(136, 201, 193, 0.15)',
              fontSize: 11.5,
              color: '#7a7a7a',
              textAlign: 'left'
            }}>
              💡 <strong>¿Usas iPhone?</strong> Agrega esta app a tu pantalla de inicio pulsando <strong>Compartir 📤</strong> en Safari y luego <strong>"Agregar al Inicio" 📲</strong>.
            </div>
          )}
        </div>
      </div>
    );
  }

  // Estilos de color comunes según el modo y tema
  const brandColor = '#88C9C1';
  const accentColor = '#C9A96E';
  const bgMain = darkMode ? '#121212' : '#FAFAF8';
  const textMain = darkMode ? '#ffffff' : '#1a1a1a';
  const borderLight = darkMode ? 'rgba(255,255,255,0.06)' : 'rgba(0, 0, 0, 0.05)';
  const cardBg = darkMode ? 'rgba(30, 30, 30, 0.75)' : '#ffffff';

  return (
    <div style={{
      minHeight: '100dvh',
      background: bgMain,
      color: textMain,
      fontFamily: "'Outfit', sans-serif",
      paddingBottom: 88, // Espacio para la barra de navegación
      display: 'flex',
      flexDirection: 'column',
      boxSizing: 'border-box'
    }}>
      {/* HEADER SUPERIOR MÓVIL */}
      <div style={{
        position: 'sticky',
        top: 0,
        zIndex: 99,
        background: darkMode ? 'rgba(18, 18, 18, 0.88)' : 'rgba(250, 250, 248, 0.88)',
        backdropFilter: 'blur(20px)',
        WebkitBackdropFilter: 'blur(20px)',
        borderBottom: `1px solid ${borderLight}`,
        padding: '14px 20px',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 60
      }}>
        <div>
          <span style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 20, fontStyle: 'italic', fontWeight: 600, color: textMain }}>
            El Arte de Quererte
          </span>
          <span style={{ fontSize: 9, textTransform: 'uppercase', letterSpacing: 2.5, color: accentColor, fontWeight: 700, marginLeft: 8 }}>
            App
          </span>
        </div>
        
        {/* Botón de Sincronización Rápida en Header */}
        <button 
          onClick={handleSyncCalendar} 
          disabled={syncing}
          style={{
            background: 'none',
            border: 'none',
            fontSize: 18,
            cursor: 'pointer',
            padding: 8,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            opacity: syncing ? 0.5 : 1,
            animation: syncing ? 'spin 1.2s infinite linear' : 'none'
          }}
          title="Sincronizar Calendario"
        >
          🔄
        </button>
      </div>

      {/* RENDERIZADO DE PESTAÑAS (TABS) */}
      <div style={{ flex: 1, padding: '16px 20px' }}>
        
        {/* --- PESTAÑA 1: AGENDA --- */}
        {activeTab === 'agenda' && (
          <div style={{ animation: 'fadeIn 0.3s ease-out' }}>
            <h2 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 28, fontStyle: 'italic', fontWeight: 600, marginBottom: 4, color: textMain }}>
              Agenda de Citas
            </h2>
            <p style={{ fontSize: 12, color: '#7a7a7a', marginBottom: 18 }}>Consulta y gestiona las horas de reservas para tu spa.</p>
            
            {/* Calendario horizontal rápido */}
            <div style={{
              display: 'flex',
              gap: 8,
              overflowX: 'auto',
              paddingBottom: 12,
              marginBottom: 16,
              scrollBehavior: 'smooth',
              scrollbarWidth: 'none'
            }} className="no-scrollbar">
              {weekDays.map((wd, i) => {
                const isActive = wd.dateStr === selectedDateStr;
                return (
                  <button
                    key={i}
                    onClick={() => setSelectedDateStr(wd.dateStr)}
                    style={{
                      flex: '0 0 54px',
                      height: 72,
                      borderRadius: 16,
                      background: isActive ? brandColor : (darkMode ? 'rgba(255,255,255,0.03)' : '#fff'),
                      border: `1.5px solid ${isActive ? brandColor : borderLight}`,
                      color: isActive ? '#1a1a1a' : textMain,
                      display: 'flex',
                      flexDirection: 'column',
                      alignItems: 'center',
                      justifyContent: 'center',
                      cursor: 'pointer',
                      gap: 4,
                      boxShadow: isActive ? '0 6px 14px rgba(136, 201, 193, 0.25)' : 'none',
                      transition: 'all 0.2s ease'
                    }}
                  >
                    <span style={{ fontSize: 9.5, letterSpacing: 0.5, textTransform: 'uppercase', opacity: isActive ? 0.9 : 0.6, fontWeight: 700 }}>
                      {wd.dayName}
                    </span>
                    <span style={{ fontSize: 18, fontWeight: 700, fontFamily: "'Outfit', sans-serif" }}>
                      {wd.dayNum}
                    </span>
                  </button>
                );
              })}
            </div>

            {/* Listado de Citas */}
            {loading ? (
              <div style={{ padding: '40px 0', textAlign: 'center', color: '#7a7a7a' }}>Cargando agenda...</div>
            ) : dayAppointments.length === 0 ? (
              <div style={{
                padding: '48px 20px',
                textAlign: 'center',
                background: cardBg,
                borderRadius: 20,
                border: `1.5px dashed ${borderLight}`,
                marginTop: 8
              }}>
                <div style={{ fontSize: 28, marginBottom: 8 }}>🌿</div>
                <h4 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 18, fontStyle: 'italic', fontWeight: 600, color: textMain }}>No hay citas agendadas</h4>
                <p style={{ fontSize: 11.5, color: '#7a7a7a', marginTop: 4 }}>Disfruta de este día libre o bloquea horas si lo necesitas.</p>
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                {dayAppointments.map((appt, idx) => {
                  return (
                    <div 
                      key={idx}
                      style={{
                        background: cardBg,
                        border: `1.5px solid ${borderLight}`,
                        borderRadius: 20,
                        padding: 16,
                        position: 'relative',
                        display: 'flex',
                        flexDirection: 'column',
                        gap: 12
                      }}
                    >
                      {/* Cabecera Cita (Hora y Estado) */}
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                          <span style={{ fontSize: 16, fontWeight: 700, color: accentColor }}>{appt.time}</span>
                          <span style={{
                            fontSize: 9,
                            fontWeight: 700,
                            letterSpacing: 1,
                            textTransform: 'uppercase',
                            background: appt.status === 'confirmed' ? 'rgba(136, 201, 193, 0.15)' : appt.status === 'completed' ? 'rgba(201, 169, 110, 0.15)' : 'rgba(244, 184, 193, 0.15)',
                            color: appt.status === 'confirmed' ? '#88C9C1' : appt.status === 'completed' ? '#C9A96E' : '#F4B8C1',
                            padding: '3px 8px',
                            borderRadius: 12
                          }}>
                            {appt.status === 'confirmed' ? 'Confirmada' : appt.status === 'completed' ? 'Completada' : 'Cancelada'}
                          </span>
                        </div>

                        {/* WhatsApp direct connection button */}
                        {appt.phone && (
                          <a 
                            href={`https://wa.me/${appt.phone.replace(/[^0-9]/g, '')}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            style={{
                              background: 'rgba(37, 211, 102, 0.12)',
                              color: '#25D366',
                              width: 32,
                              height: 32,
                              borderRadius: '50%',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              fontSize: 14,
                              textDecoration: 'none'
                            }}
                            title="Chatear por WhatsApp"
                          >
                            💬
                          </a>
                        )}
                      </div>

                      {/* Info del cliente */}
                      <div>
                        <h4 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 18, fontWeight: 600, color: textMain, margin: '0 0 2px' }}>
                          {appt.name}
                        </h4>
                        <p style={{ fontSize: 12, color: '#7a7a7a' }}>{appt.service_name || appt.serviceName}</p>
                        {appt.notes && (
                          <div style={{
                            background: darkMode ? 'rgba(255,255,255,0.02)' : 'rgba(0,0,0,0.02)',
                            borderLeft: `2.5px solid ${accentColor}`,
                            padding: '6px 10px',
                            fontSize: 11.5,
                            color: darkMode ? '#c0c0c0' : '#555',
                            marginTop: 8,
                            borderRadius: '0 8px 8px 0'
                          }}>
                            📝 {appt.notes}
                          </div>
                        )}
                      </div>

                      {/* Botones de acción rápidos */}
                      <div style={{ display: 'flex', gap: 8, borderTop: `1px solid ${borderLight}`, paddingTop: 12, marginTop: 4 }}>
                        <button 
                          onClick={() => {
                            setApptNotes(appt.notes || '');
                            setEditingNotesAppt(appt);
                          }}
                          style={{
                            flex: 1,
                            padding: '8px',
                            borderRadius: 10,
                            background: 'none',
                            border: `1.5px solid ${borderLight}`,
                            color: textMain,
                            fontSize: 11,
                            fontWeight: 600,
                            cursor: 'pointer'
                          }}
                        >
                          Anotar
                        </button>
                        
                        {appt.status !== 'completed' && (
                          <button 
                            onClick={() => handleUpdateStatus(appt.id, 'completed')}
                            style={{
                              flex: 1.2,
                              padding: '8px',
                              borderRadius: 10,
                              background: 'rgba(201, 169, 110, 0.15)',
                              border: 'none',
                              color: '#C9A96E',
                              fontSize: 11,
                              fontWeight: 700,
                              cursor: 'pointer'
                            }}
                          >
                            ✓ Completar
                          </button>
                        )}

                        <button 
                          onClick={() => {
                            if (confirm('¿Seguro que deseas cancelar esta cita?')) {
                              handleUpdateStatus(appt.id, 'cancelled');
                            }
                          }}
                          style={{
                            padding: '8px 12px',
                            borderRadius: 10,
                            background: 'rgba(244, 184, 193, 0.12)',
                            border: 'none',
                            color: '#F4B8C1',
                            fontSize: 11,
                            fontWeight: 600,
                            cursor: 'pointer'
                          }}
                        >
                          Cancelar
                        </button>
                      </div>

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

          </div>
        )}

        {/* --- PESTAÑA 2: SERVICIOS --- */}
        {activeTab === 'servicios' && (
          <div style={{ animation: 'fadeIn 0.3s ease-out' }}>
            <h2 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 28, fontStyle: 'italic', fontWeight: 600, marginBottom: 4, color: textMain }}>
              Servicios y Precios
            </h2>
            <p style={{ fontSize: 12, color: '#7a7a7a', marginBottom: 20 }}>Edita los valores, duración y visibilidad de tus tratamientos.</p>
            
            {loading ? (
              <div style={{ padding: '40px 0', textAlign: 'center', color: '#7a7a7a' }}>Cargando catálogo...</div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                {categories.map((cat, i) => {
                  const catServices = services.filter(s => String(s.category_id) === String(cat.id));
                  return (
                    <div key={i}>
                      <h3 style={{
                        fontFamily: "'Outfit', sans-serif",
                        fontSize: 12,
                        letterSpacing: 2,
                        textTransform: 'uppercase',
                        color: accentColor,
                        fontWeight: 700,
                        borderBottom: `1px solid ${borderLight}`,
                        paddingBottom: 6,
                        marginBottom: 10
                      }}>
                        {cat.name}
                      </h3>
                      
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                        {catServices.map((svc, idx) => (
                          <div 
                            key={idx}
                            onClick={() => {
                              setEditingService(svc);
                              setSvcPrice(svc.price);
                              setSvcDuration(svc.duration);
                              setSvcShowHome(svc.show_on_home || false);
                            }}
                            style={{
                              background: cardBg,
                              border: `1.5px solid ${borderLight}`,
                              borderRadius: 16,
                              padding: '14px 16px',
                              display: 'flex',
                              justifyContent: 'space-between',
                              alignItems: 'center',
                              cursor: 'pointer'
                            }}
                          >
                            <div style={{ flex: 1, marginRight: 12 }}>
                              <h4 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 17, fontWeight: 600, color: textMain, margin: 0 }}>
                                {svc.name}
                              </h4>
                              <span style={{ fontSize: 11, color: '#7a7a7a' }}>⏱️ {svc.duration}</span>
                              {svc.show_on_home && (
                                <span style={{ fontSize: 9, background: 'rgba(136, 201, 193, 0.12)', color: '#88C9C1', padding: '2px 6px', borderRadius: 8, marginLeft: 8, fontWeight: 700, textTransform: 'uppercase' }}>Home</span>
                              )}
                            </div>
                            <div style={{ textAlign: 'right' }}>
                              <div style={{ fontSize: 15, fontWeight: 700, color: brandColor }}>{svc.price}</div>
                              <span style={{ fontSize: 10, color: '#7a7a7a' }}>Toca para editar</span>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        )}

        {/* --- PESTAÑA 3: AJUSTES --- */}
        {activeTab === 'ajustes' && (
          <div style={{ animation: 'fadeIn 0.3s ease-out' }}>
            <h2 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 28, fontStyle: 'italic', fontWeight: 600, marginBottom: 4, color: textMain }}>
              Configuración
            </h2>
            <p style={{ fontSize: 12, color: '#7a7a7a', marginBottom: 24 }}>Administra tus credenciales, calendario y notificaciones push.</p>
            
            <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
              
              {/* Bloque: Sincronización Google Calendar */}
              <div style={{ background: cardBg, border: `1.5px solid ${borderLight}`, borderRadius: 24, padding: 20 }}>
                <h3 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 20, fontWeight: 600, color: textMain, marginBottom: 4 }}>
                  📅 Sincronización
                </h3>
                <p style={{ fontSize: 12, color: '#7a7a7a', marginBottom: 16 }}>Vincular en vivo las citas locales con tu Google Calendar.</p>
                <button 
                  onClick={handleSyncCalendar} 
                  disabled={syncing}
                  style={{
                    width: '100%',
                    padding: '12px',
                    borderRadius: 12,
                    background: 'rgba(136, 201, 193, 0.12)',
                    border: 'none',
                    color: '#88C9C1',
                    fontSize: 12,
                    fontWeight: 700,
                    textTransform: 'uppercase',
                    letterSpacing: 1,
                    cursor: 'pointer'
                  }}
                >
                  {syncing ? 'Sincronizando...' : 'Sincronizar Ahora'}
                </button>
              </div>

              {/* Bloque: Alertas Push Celular */}
              <div style={{ background: cardBg, border: `1.5px solid ${borderLight}`, borderRadius: 24, padding: 20 }}>
                <h3 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 20, fontWeight: 600, color: textMain, marginBottom: 4 }}>
                  🔔 Alertas en este Celular
                </h3>
                <p style={{ fontSize: 12, color: '#7a7a7a', marginBottom: 16 }}>Recibe notificaciones en tu pantalla de bloqueo al recibir citas.</p>
                
                {!pushSupported ? (
                  <div style={{ padding: 12, borderRadius: 12, background: 'rgba(244, 184, 193, 0.1)', border: '1px solid rgba(244, 184, 193, 0.2)', color: '#F4B8C1', fontSize: 11.5 }}>
                    ⚠️ Tu navegador o dispositivo no soporta Web Push de forma directa. Si usas iPhone, recuerda guardarlo como acceso directo en la Pantalla de Inicio de Safari.
                  </div>
                ) : (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: darkMode ? '#1a1a1a' : '#f9f9f9', padding: '10px 14px', borderRadius: 12 }}>
                      <div>
                        <div style={{ fontSize: 12.5, fontWeight: 600 }}>Estado del servicio</div>
                        <div style={{ fontSize: 11, color: pushActive ? '#88C9C1' : '#7a7a7a', marginTop: 1 }}>{pushActive ? '🟢 Activo en este celular' : '⚪ Inactivo'}</div>
                      </div>
                      <button 
                        onClick={handleTogglePush}
                        disabled={pushLoading}
                        style={{
                          background: pushActive ? '#F4B8C1' : '#88C9C1',
                          color: '#1a1a1a',
                          border: 'none',
                          padding: '6px 12px',
                          borderRadius: 8,
                          fontSize: 11,
                          fontWeight: 700,
                          cursor: 'pointer'
                        }}
                      >
                        {pushLoading ? '...' : pushActive ? 'Desactivar' : 'Activar'}
                      </button>
                    </div>

                    {pushActive && (
                      <button 
                        onClick={handleTestPush}
                        style={{
                          width: '100%',
                          padding: '10px',
                          background: 'none',
                          border: `1px solid ${borderLight}`,
                          borderRadius: 12,
                          color: textMain,
                          fontSize: 11,
                          fontWeight: 500,
                          cursor: 'pointer'
                        }}
                      >
                        🧪 Probar Alerta Push
                      </button>
                    )}
                  </div>
                )}
              </div>

              {/* Bloque: Instalar en Pantalla de Inicio (Sólo visible si no es Standalone) */}
              {!(window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone) && (
                <div style={{ background: cardBg, border: '1.5px solid #C9A96E', borderRadius: 24, padding: 20 }}>
                  <h3 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 20, fontWeight: 600, color: textMain, marginBottom: 4 }}>
                    📲 Instalar App de Administración
                  </h3>
                  <p style={{ fontSize: 12, color: '#7a7a7a', marginBottom: 16 }}>
                    Guarda esta aplicación en tu pantalla de inicio para acceder directamente con un toque y activar las alertas push locales.
                  </p>
                  
                  {/iPhone|iPad|iPod/i.test(navigator.userAgent) ? (
                    <div style={{
                      padding: 12,
                      borderRadius: 12,
                      background: darkMode ? '#1a1a1a' : '#f9f9f9',
                      border: `1px solid ${borderLight}`,
                      fontSize: 11.5,
                      color: textMain,
                      lineHeight: '1.4'
                    }}>
                      <div style={{ fontWeight: 700, marginBottom: 6, color: '#C9A96E' }}>Para iPhone (Safari):</div>
                      <div style={{ marginBottom: 4 }}>1. Toca el icono de compartir 📤 abajo en tu navegador.</div>
                      <div>2. Elige **"Agregar al Inicio"** 📲.</div>
                    </div>
                  ) : (
                    <button 
                      onClick={handleInstallClick}
                      style={{
                        width: '100%',
                        padding: '12px',
                        borderRadius: 12,
                        background: 'rgba(201, 169, 110, 0.12)',
                        border: 'none',
                        color: '#C9A96E',
                        fontSize: 12,
                        fontWeight: 700,
                        textTransform: 'uppercase',
                        letterSpacing: 1,
                        cursor: 'pointer'
                      }}
                    >
                      Instalar en este Celular
                    </button>
                  )}
                </div>
              )}

              {/* Bloque: Apariencia */}
              <div style={{ background: cardBg, border: `1.5px solid ${borderLight}`, borderRadius: 24, padding: 20 }}>
                <h3 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 20, fontWeight: 600, color: textMain, marginBottom: 12 }}>
                  🎨 Apariencia
                </h3>
                
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
                  <span style={{ fontSize: 13, color: '#7a7a7a' }}>Modo Oscuro</span>
                  <button 
                    onClick={() => setDarkMode(!darkMode)}
                    style={{
                      background: 'none',
                      border: 'none',
                      fontSize: 22,
                      cursor: 'pointer'
                    }}
                  >
                    {darkMode ? '🌙' : '☀️'}
                  </button>
                </div>

                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  <label style={{ fontSize: 11, color: '#7a7a7a', fontWeight: 600 }}>TEMA VISUAL</label>
                  <select 
                    value={selectedTheme}
                    onChange={e => setSelectedTheme(e.target.value)}
                    style={{
                      width: '100%',
                      padding: '12px 14px',
                      borderRadius: 12,
                      background: darkMode ? '#1a1a1a' : '#fff',
                      color: textMain,
                      border: `1.5px solid ${borderLight}`,
                      fontSize: 13,
                      outline: 'none'
                    }}
                  >
                    <option value="luxury">Luxury / Softness</option>
                    <option value="minimal">Minimalista</option>
                    <option value="glass">Glass</option>
                    <option value="neumorphism">Neumorphism</option>
                    <option value="bento">Bento</option>
                    <option value="claymorphism">Claymorphism</option>
                  </select>
                </div>
              </div>

              {/* Botón Cerrar Sesión */}
              <button 
                onClick={handleLogout}
                style={{
                  width: '100%',
                  padding: '15px',
                  borderRadius: 16,
                  background: 'rgba(244, 184, 193, 0.12)',
                  border: 'none',
                  color: '#F4B8C1',
                  fontFamily: "'Outfit', sans-serif",
                  fontWeight: 700,
                  fontSize: 12,
                  letterSpacing: 2,
                  textTransform: 'uppercase',
                  cursor: 'pointer',
                  marginTop: 8
                }}
              >
                Cerrar Sesión
              </button>

            </div>
          </div>
        )}

      </div>

      {/* --- MODAL EDICIÓN SERVICIO --- */}
      {editingService && (
        <div style={{
          position: 'fixed',
          inset: 0,
          background: 'rgba(0,0,0,0.5)',
          backdropFilter: 'blur(8px)',
          WebkitBackdropFilter: 'blur(8px)',
          display: 'flex',
          alignItems: 'flex-end',
          justifyContent: 'center',
          zIndex: 1000,
          animation: 'fadeIn 0.25s ease-out'
        }}>
          <div style={{
            background: darkMode ? '#1e1e1e' : '#fff',
            width: '100%',
            maxWidth: 480,
            borderRadius: '24px 24px 0 0',
            padding: '24px 20px 32px',
            boxShadow: '0 -10px 30px rgba(0,0,0,0.15)',
            borderTop: `1.5px solid ${borderLight}`,
            animation: 'slideUp 0.3s cubic-bezier(0.16, 1, 0.3, 1)'
          }}>
            <h3 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 22, fontWeight: 600, color: textMain, marginBottom: 4 }}>
              Editar Servicio
            </h3>
            <p style={{ fontSize: 12, color: '#7a7a7a', marginBottom: 20 }}>{editingService.name}</p>

            <form onSubmit={handleSaveService} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <div>
                <label style={{ fontSize: 11, color: '#7a7a7a', fontWeight: 600, display: 'block', marginBottom: 6 }}>PRECIO</label>
                <input 
                  type="text" 
                  value={svcPrice}
                  onChange={e => setSvcPrice(e.target.value)}
                  required
                  style={{
                    width: '100%',
                    padding: '12px 14px',
                    borderRadius: 12,
                    background: darkMode ? '#222' : '#fff',
                    color: textMain,
                    border: `1.5px solid ${borderLight}`,
                    fontSize: 13,
                    outline: 'none',
                    boxSizing: 'border-box'
                  }}
                />
              </div>

              <div>
                <label style={{ fontSize: 11, color: '#7a7a7a', fontWeight: 600, display: 'block', marginBottom: 6 }}>DURACIÓN</label>
                <input 
                  type="text" 
                  value={svcDuration}
                  onChange={e => setSvcDuration(e.target.value)}
                  required
                  style={{
                    width: '100%',
                    padding: '12px 14px',
                    borderRadius: 12,
                    background: darkMode ? '#222' : '#fff',
                    color: textMain,
                    border: `1.5px solid ${borderLight}`,
                    fontSize: 13,
                    outline: 'none',
                    boxSizing: 'border-box'
                  }}
                />
              </div>

              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', margin: '8px 0' }}>
                <span style={{ fontSize: 13, fontWeight: 600 }}>Mostrar en Inicio</span>
                <input 
                  type="checkbox" 
                  checked={svcShowHome} 
                  onChange={e => setSvcShowHome(e.target.checked)} 
                  style={{ width: 18, height: 18, accentColor: brandColor }}
                />
              </div>

              <div style={{ display: 'flex', gap: 10, marginTop: 12 }}>
                <button 
                  type="button" 
                  onClick={() => setEditingService(null)}
                  style={{
                    flex: 1,
                    padding: '12px',
                    borderRadius: 12,
                    background: 'none',
                    border: `1.5px solid ${borderLight}`,
                    color: textMain,
                    fontSize: 12,
                    fontWeight: 600,
                    cursor: 'pointer'
                  }}
                >
                  Cancelar
                </button>
                <button 
                  type="submit"
                  style={{
                    flex: 1.5,
                    padding: '12px',
                    borderRadius: 12,
                    background: brandColor,
                    border: 'none',
                    color: '#1a1a1a',
                    fontSize: 12,
                    fontWeight: 700,
                    cursor: 'pointer'
                  }}
                >
                  Guardar Cambios
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* --- MODAL EDICIÓN ANOTACIONES / NOTAS --- */}
      {editingNotesAppt && (
        <div style={{
          position: 'fixed',
          inset: 0,
          background: 'rgba(0,0,0,0.5)',
          backdropFilter: 'blur(8px)',
          WebkitBackdropFilter: 'blur(8px)',
          display: 'flex',
          alignItems: 'flex-end',
          justifyContent: 'center',
          zIndex: 1000,
          animation: 'fadeIn 0.25s ease-out'
        }}>
          <div style={{
            background: darkMode ? '#1e1e1e' : '#fff',
            width: '100%',
            maxWidth: 480,
            borderRadius: '24px 24px 0 0',
            padding: '24px 20px 32px',
            boxShadow: '0 -10px 30px rgba(0,0,0,0.15)',
            borderTop: `1.5px solid ${borderLight}`,
            animation: 'slideUp 0.3s cubic-bezier(0.16, 1, 0.3, 1)'
          }}>
            <h3 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 22, fontWeight: 600, color: textMain, marginBottom: 4 }}>
              Notas de la Cita
            </h3>
            <p style={{ fontSize: 12, color: '#7a7a7a', marginBottom: 20 }}>{editingNotesAppt.name} · {editingNotesAppt.time}</p>

            <form onSubmit={handleSaveNotes} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <div>
                <label style={{ fontSize: 11, color: '#7a7a7a', fontWeight: 600, display: 'block', marginBottom: 6 }}>ANOTACIONES</label>
                <textarea 
                  value={apptNotes}
                  onChange={e => setApptNotes(e.target.value)}
                  rows={4}
                  placeholder="Escribe observaciones de esta cita (ej. tipo de piel, dolores musculares, etc.)"
                  style={{
                    width: '100%',
                    padding: '12px 14px',
                    borderRadius: 12,
                    background: darkMode ? '#222' : '#fff',
                    color: textMain,
                    border: `1.5px solid ${borderLight}`,
                    fontSize: 13,
                    outline: 'none',
                    boxSizing: 'border-box',
                    resize: 'none',
                    fontFamily: 'inherit'
                  }}
                />
              </div>

              <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
                <button 
                  type="button" 
                  onClick={() => setEditingNotesAppt(null)}
                  style={{
                    flex: 1,
                    padding: '12px',
                    borderRadius: 12,
                    background: 'none',
                    border: `1.5px solid ${borderLight}`,
                    color: textMain,
                    fontSize: 12,
                    fontWeight: 600,
                    cursor: 'pointer'
                  }}
                >
                  Cancelar
                </button>
                <button 
                  type="submit"
                  disabled={savingNotes}
                  style={{
                    flex: 1.5,
                    padding: '12px',
                    borderRadius: 12,
                    background: brandColor,
                    border: 'none',
                    color: '#1a1a1a',
                    fontSize: 12,
                    fontWeight: 700,
                    cursor: 'pointer'
                  }}
                >
                  {savingNotes ? 'Guardando...' : 'Guardar Notas'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* --- BARRA DE NAVEGACIÓN INFERIOR (BOTTOM NAV) --- */}
      <div style={{
        position: 'fixed',
        bottom: 0,
        left: 0,
        right: 0,
        height: 74,
        background: darkMode ? 'rgba(26, 26, 26, 0.95)' : 'rgba(250, 250, 248, 0.95)',
        backdropFilter: 'blur(20px)',
        WebkitBackdropFilter: 'blur(20px)',
        borderTop: `1px solid ${borderLight}`,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-around',
        zIndex: 999
      }}>
        {/* Tab 1: Agenda */}
        <button 
          onClick={() => setActiveTab('agenda')}
          style={{
            background: 'none',
            border: 'none',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: 4,
            cursor: 'pointer',
            padding: '8px 16px',
            color: activeTab === 'agenda' ? brandColor : '#7a7a7a',
            transition: 'color 0.2s ease'
          }}
        >
          <span style={{ fontSize: 20 }}>📅</span>
          <span style={{ fontSize: 10, fontWeight: activeTab === 'agenda' ? 700 : 500, letterSpacing: 0.5 }}>Agenda</span>
        </button>

        {/* Tab 2: Servicios */}
        <button 
          onClick={() => setActiveTab('servicios')}
          style={{
            background: 'none',
            border: 'none',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: 4,
            cursor: 'pointer',
            padding: '8px 16px',
            color: activeTab === 'servicios' ? brandColor : '#7a7a7a',
            transition: 'color 0.2s ease'
          }}
        >
          <span style={{ fontSize: 20 }}>🌿</span>
          <span style={{ fontSize: 10, fontWeight: activeTab === 'servicios' ? 700 : 500, letterSpacing: 0.5 }}>Servicios</span>
        </button>

        {/* Tab 3: Ajustes */}
        <button 
          onClick={() => setActiveTab('ajustes')}
          style={{
            background: 'none',
            border: 'none',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: 4,
            cursor: 'pointer',
            padding: '8px 16px',
            color: activeTab === 'ajustes' ? brandColor : '#7a7a7a',
            transition: 'color 0.2s ease'
          }}
        >
          <span style={{ fontSize: 20 }}>⚙️</span>
          <span style={{ fontSize: 10, fontWeight: activeTab === 'ajustes' ? 700 : 500, letterSpacing: 0.5 }}>Ajustes</span>
        </button>
      </div>

      {/* STYLES DINÁMICOS COMPLEMENTARIOS PARA TRANSICIONES */}
      <style>{`
        @keyframes fadeIn {
          from { opacity: 0; transform: translateY(8px); }
          to { opacity: 1; transform: translateY(0); }
        }
        @keyframes slideUp {
          from { transform: translateY(100%); }
          to { transform: translateY(0); }
        }
        @keyframes spin {
          from { transform: rotate(0deg); }
          to { transform: rotate(360deg); }
        }
        .no-scrollbar::-webkit-scrollbar {
          display: none;
        }
        .no-scrollbar {
          -ms-overflow-style: none;
          scrollbar-width: none;
        }
        /* Dynamic notification toast styles */
        .lux-notification-toast {
          transition: all 0.45s cubic-bezier(0.16, 1, 0.3, 1);
        }
      `}</style>

      {/* Dynamic luxury notification toast dialog */}
      <div 
        className={`lux-notification-toast ${notification.show ? 'show' : ''}`}
        style={{
          position: 'fixed',
          bottom: 88, // Ajustado para estar encima del Bottom Nav
          left: 20,
          right: 20,
          zIndex: 10000,
          background: darkMode ? 'rgba(26, 26, 26, 0.95)' : 'rgba(250, 250, 248, 0.95)',
          border: `1.5px solid ${darkMode ? 'rgba(136, 201, 193, 0.3)' : 'rgba(201, 169, 110, 0.4)'}`,
          boxShadow: '0 10px 30px rgba(0,0,0,0.15)',
          borderRadius: 20,
          padding: '12px 18px',
          display: 'flex',
          alignItems: 'center',
          gap: 12,
          backdropFilter: 'blur(20px)',
          WebkitBackdropFilter: 'blur(20px)',
          transition: 'all 0.4s ease-in-out',
          opacity: notification.show ? 1 : 0,
          transform: notification.show ? 'translateY(0) scale(1)' : 'translateY(20px) scale(0.95)',
          pointerEvents: notification.show ? 'all' : 'none',
        }}
      >
        <div style={{
          width: 32,
          height: 32,
          borderRadius: '50%',
          background: notification.type === 'error' ? 'rgba(244, 184, 193, 0.15)' : 'rgba(136, 201, 193, 0.15)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: 15,
          flexShrink: 0
        }}>
          {notification.type === 'error' ? '⚠️' : '✨'}
        </div>
        <div style={{ flex: 1 }}>
          <h4 style={{
            fontFamily: "'Cormorant Garamond', serif",
            fontSize: 16,
            fontWeight: 700,
            fontStyle: 'italic',
            color: darkMode ? '#fff' : '#1a1a1a',
            margin: 0,
            lineHeight: 1.2
          }}>{notification.title}</h4>
          <p style={{
            fontFamily: "'Outfit', sans-serif",
            fontSize: 11,
            color: darkMode ? '#c0c0c0' : '#555',
            margin: '2px 0 0',
            lineHeight: 1.3
          }}>{notification.message}</p>
        </div>
      </div>

    </div>
  );
};

Object.assign(window, { AdminMobileApp });
