// ============================
// LELUSA — Settings Page
// src/pages/settings-page.jsx
// ============================

// Componentes a nivel de MÓDULO (identidad estable). Definidos dentro de
// SettingsPage, se recreaban en cada render y remontaban los inputs que
// envuelven, robándoles el foco al escribir.
function SettingCard({ title, subtitle, children }) {
  const isMobile = window.LelusaGestures.useIsMobile();
  const cardStyle = {
    background: 'var(--card)',
    border: '1px solid var(--border)',
    borderRadius: '18px',
    padding: isMobile ? '18px' : '22px',
    boxShadow: '0 10px 30px rgba(58,42,32,0.05)',
  };
  return (
    <section style={cardStyle}>
      <div style={{ marginBottom: 16 }}>
        <h3 style={{ margin: '0 0 5px', fontSize: 16, color: 'var(--text)', fontWeight: 800 }}>{title}</h3>
        {subtitle && <p style={{ margin: 0, fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.5 }}>{subtitle}</p>}
      </div>
      {children}
    </section>
  );
}

function ToggleRow({ title, text, checked, onChange }) {
  return (
    <label style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 14, padding: '12px 0', borderBottom: '1px solid var(--border)', cursor: 'pointer' }}>
      <span>
        <span style={{ display: 'block', fontSize: 13, fontWeight: 800, color: 'var(--text)' }}>{title}</span>
        {text && <span style={{ display: 'block', fontSize: 12, color: 'var(--muted)', marginTop: 3, lineHeight: 1.4 }}>{text}</span>}
      </span>
      <input type="checkbox" checked={Boolean(checked)} onChange={event => onChange(event.target.checked)} />
    </label>
  );
}

function SettingsPage() {
  const { t } = window.ReactI18next.useTranslation();
  const data = window.LelusaStore.useBusinessData();
  const systemSettings = window.LelusaStore.useSystemSettings();
  const cfg = window.LELUSA_SUPABASE || {};
  const pushCfg = window.LELUSA_PUSH || {};
  const { navigate } = React.useContext(window.AppContext);
  const notificationState = window.LelusaNotifications?.useNotifications?.() || { items: [], prefs: {}, permission: 'unsupported', supported: false };
  const pwaState = window.LelusaPWA?.usePwaState?.() || { supported: false, installable: false, installed: false };

  const [settings, setSettings] = React.useState(systemSettings);
  const [activeSection, setActiveSection] = React.useState('general');
  const [url, setUrl] = React.useState(cfg.url || '');
  const [anonKey, setAnonKey] = React.useState(cfg.anonKey || '');
  const [vapidPublicKey, setVapidPublicKey] = React.useState(pushCfg.vapidPublicKey || '');
  const [message, setMessage] = React.useState('');
  const [busy, setBusy] = React.useState(false);

  React.useEffect(() => setSettings(systemSettings), [systemSettings]);

  const session = (() => {
    try { return JSON.parse(localStorage.getItem('lelusa.admin.session.v1') || 'null'); }
    catch (error) { return null; }
  })();
  const canSend = Boolean(session && (session.role === 'owner' || (session.permissions || []).includes('notify')));

  const NOTIFICATION_CATEGORIES = [
    ['cotizacion', 'Cotizaciones'], ['evento', 'Eventos'], ['gasto', 'Gastos'],
    ['pago', 'Pagos'], ['inventario', 'Inventario'], ['postres', 'Postres'],
    ['reporte', 'Reportes'], ['equipo', 'Equipo'], ['manual', 'Anuncios'],
  ];
  const [mutedCategories, setMutedCategories] = React.useState(
    () => (window.LelusaNotifications?.readPrefs?.().mutedCategories) || {}
  );

  const updateSection = (section, patch) => {
    setSettings(current => ({
      ...current,
      [section]: { ...(current[section] || {}), ...patch },
    }));
  };

  const saveSystem = (event) => {
    event.preventDefault();
    window.LelusaStore.writeSystemSettings(settings);
    setMessage('Configuración del sistema guardada.');
  };

  const resetSystem = () => {
    const next = window.LelusaStore.resetSystemSettings();
    setSettings(next);
    setMessage('Configuración restaurada a los valores base.');
  };

  const saveRemote = async (event) => {
    event.preventDefault();
    setBusy(true);
    setMessage('Conectando con Supabase...');
    await window.LelusaStore.setRemoteCredentials(url, anonKey);
    setBusy(false);
    setMessage(window.LelusaStore.isRemoteConfigured() ? 'Supabase configurado. Datos sincronizados.' : 'Faltan credenciales.');
  };

  const refresh = async () => {
    setBusy(true);
    setMessage('Recargando datos desde Supabase...');
    await window.LelusaStore.refreshFromRemote();
    setBusy(false);
    setMessage('Datos recargados desde Supabase.');
  };

  const savePush = () => {
    localStorage.setItem('lelusa.push.vapidPublicKey', vapidPublicKey.trim());
    window.LELUSA_PUSH = { ...(window.LELUSA_PUSH || {}), vapidPublicKey: vapidPublicKey.trim() };
    setMessage('Clave publica VAPID guardada. Ya puedes activar alertas PWA desde Notificaciones.');
  };

  const toggleCategory = (category) => {
    const next = { ...mutedCategories, [category]: !mutedCategories[category] };
    setMutedCategories(next);
    window.LelusaNotifications?.updatePrefs?.({ mutedCategories: next });
  };

  const requestPermission = async () => {
    const result = await window.LelusaNotifications.requestBrowserPermission();
    setMessage(result.ok ? t('admin_notif_enabled_device') : result.reason);
  };

  const installPwa = async () => {
    const result = await window.LelusaPWA.install();
    setMessage(result.ok ? t('admin_notif_app_installed') : result.reason || t('admin_notif_install_failed'));
  };

  const enablePwaNotifications = async () => {
    const result = await window.LelusaNotifications.subscribePushDevice();
    if (result.ok && result.localOnly) {
      setMessage(result.reason);
    } else if (result.ok) {
      setMessage(result.remoteSaved ? t('admin_notif_pwa_push_subscribed') : t('admin_notif_pwa_active'));
    } else {
      setMessage(result.reason);
    }
  };

  const inputStyle = ADMIN_INPUT_STYLE;
  const textAreaStyle = { ...inputStyle, resize: 'vertical', minHeight: 82 };
  const tabs = [
    ['general', 'General'], ['landing', 'Landing'], ['ventas', 'Ventas'],
    ['admin', 'Admin'], ['integraciones', 'Integraciones'], ['notificaciones', 'Notificaciones'],
  ];
  const realtimeLabel = {
    connected: t('admin_notif_rt_connected'),
    connecting: t('admin_notif_rt_connecting'),
    reconnecting: t('admin_notif_rt_reconnecting'),
    closed: t('admin_notif_rt_closed'),
    unsupported: t('admin_notif_rt_unsupported'),
    error: t('admin_notif_rt_error'),
    idle: t('admin_notif_rt_idle'),
  }[notificationState.realtimeStatus || 'idle'];
  const statRows = [
    ['Modo de datos', data.isRemoteConfigured ? 'Supabase' : 'Local'],
    ['Decoraciones', data.designs.length],
    ['Assets', data.assets.length],
    ['Postres', (data.desserts || []).length],
    ['Equipo', (data.teamMembers || []).length],
    ['Cotizaciones', data.quotes.length],
    ['Eventos', data.events.length],
  ];

  return (
    <AdminLayout title="Configuración" subtitle="Centro de control para landing, ventas, panel e integraciones">
      <form onSubmit={saveSystem} style={{ display: 'grid', gap: 18 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {tabs.map(([key, label]) => (
              <button key={key} type="button" onClick={() => setActiveSection(key)}
                style={{ border: '1px solid var(--border)', borderRadius: 999, background: activeSection === key ? 'var(--text)' : 'var(--card)', color: activeSection === key ? 'var(--bg)' : 'var(--muted)', padding: '8px 13px', fontSize: 12, fontWeight: 800, cursor: 'pointer' }}>
                {label}
              </button>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <Btn type="submit">Guardar sistema</Btn>
            <Btn type="button" variant="ghost" onClick={resetSystem}>Restaurar base</Btn>
          </div>
        </div>

        {message && <div style={{ padding: '12px 14px', borderRadius: '12px', background: 'var(--accent-light)', color: 'var(--muted)', fontSize: '13px' }}>{message}</div>}
        {data.error && <div style={{ padding: '12px 14px', borderRadius: '12px', background: '#FFE0E0', color: '#C83A3A', fontSize: '13px' }}>{data.error}</div>}

        {activeSection === 'general' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 0.9fr', gap: 18 }} className="dash-grid">
            <SettingCard title="Marca y contacto" subtitle="Estos datos alimentan navbar, footer, WhatsApp y encabezados del sitio.">
              <AdminFormSection title="Identidad" columns={2}>
                <AdminField label="Nombre del negocio"><input value={settings.brand.businessName} onChange={e => updateSection('brand', { businessName: e.target.value })} style={inputStyle} /></AdminField>
                <AdminField label="Submarca"><input value={settings.brand.tagline} onChange={e => updateSection('brand', { tagline: e.target.value })} style={inputStyle} /></AdminField>
                <AdminFileField label="Logo" value={settings.brand.logo} onChange={value => updateSection('brand', { logo: value })} full />
              </AdminFormSection>
              <AdminFormSection title="Contacto público" columns={2}>
                <AdminField label="Teléfono visible"><input value={settings.brand.phoneLabel} onChange={e => updateSection('brand', { phoneLabel: e.target.value })} style={inputStyle} /></AdminField>
                <AdminField label="Teléfono enlace"><input value={settings.brand.phoneHref} onChange={e => updateSection('brand', { phoneHref: e.target.value })} style={inputStyle} /></AdminField>
                <AdminField label="WhatsApp URL"><input value={settings.brand.whatsappUrl} onChange={e => updateSection('brand', { whatsappUrl: e.target.value })} style={inputStyle} /></AdminField>
                <AdminField label="Correo"><input type="email" value={settings.brand.email} onChange={e => updateSection('brand', { email: e.target.value })} style={inputStyle} /></AdminField>
                <AdminField label="Ubicación" full><input value={settings.brand.location} onChange={e => updateSection('brand', { location: e.target.value })} style={inputStyle} /></AdminField>
              </AdminFormSection>
            </SettingCard>

            <SettingCard title="Estado del sistema" subtitle="Lectura rápida de datos y módulos cargados.">
              {statRows.map(([label, value]) => (
                <div key={label} style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0', borderBottom: '1px solid var(--border)', fontSize: 13 }}>
                  <span style={{ color: 'var(--muted)' }}>{label}</span>
                  <strong style={{ color: 'var(--text)' }}>{value}</strong>
                </div>
              ))}
              <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginTop: 16 }}>
                <Btn type="button" variant="ghost" onClick={() => navigate('home')}>Ver landing</Btn>
                <Btn type="button" variant="ghost" onClick={() => navigate('admin-email')}>Correos</Btn>
              </div>
            </SettingCard>
          </div>
        )}

        {activeSection === 'landing' && (
          <SettingCard title="Landing pública" subtitle="Textos e imagen principal que verá la clienta.">
            <AdminFormSection title="Hero" columns={2}>
              <AdminField label="Título principal"><input value={settings.landing.heroTitlePrefix || ''} placeholder={t('hero_title_1')} onChange={e => updateSection('landing', { heroTitlePrefix: e.target.value })} style={inputStyle} /></AdminField>
              <AdminField label="Frase destacada"><input value={settings.landing.heroTitleAccent || ''} placeholder={t('hero_title_2')} onChange={e => updateSection('landing', { heroTitleAccent: e.target.value })} style={inputStyle} /></AdminField>
              <AdminField label="Descripción" full><textarea value={settings.landing.heroDescription || ''} placeholder={t('hero_desc')} onChange={e => updateSection('landing', { heroDescription: e.target.value })} style={textAreaStyle} /></AdminField>
              <AdminFileField label="Imagen hero desktop" value={settings.landing.heroImage} onChange={value => updateSection('landing', { heroImage: value })} />
              <AdminFileField label="Imagen hero móvil" value={settings.landing.heroMobileImage} onChange={value => updateSection('landing', { heroMobileImage: value })} />
              <AdminField label="Video hero" full><input value={settings.landing.heroVideo} onChange={e => updateSection('landing', { heroVideo: e.target.value })} style={inputStyle} /></AdminField>
            </AdminFormSection>
            <AdminFormSection title="Imágenes por sección" columns={2}>
              <AdminFileField label="Imagen colecciones / catálogo" value={settings.landing.collectionImage} onChange={value => updateSection('landing', { collectionImage: value })} />
              <AdminFileField label="Imagen nosotras / booking" value={settings.landing.aboutImage} onChange={value => updateSection('landing', { aboutImage: value })} />
              <AdminFileField label="Imagen CTA final" value={settings.landing.ctaImage} onChange={value => updateSection('landing', { ctaImage: value })} />
            </AdminFormSection>
            <AdminFormSection title="Secciones" columns={2}>
              <AdminField label="Título Nosotras"><input value={settings.landing.aboutTitle || ''} placeholder={`${t('about_title_1')} ${t('about_title_2')}`} onChange={e => updateSection('landing', { aboutTitle: e.target.value })} style={inputStyle} /></AdminField>
              <AdminField label="Título Booking"><input value={settings.landing.bookingTitle || ''} placeholder={t('book_title')} onChange={e => updateSection('landing', { bookingTitle: e.target.value })} style={inputStyle} /></AdminField>
              <AdminField label="Texto Nosotras" full><textarea value={settings.landing.aboutDescription || ''} placeholder={t('about_desc')} onChange={e => updateSection('landing', { aboutDescription: e.target.value })} style={textAreaStyle} /></AdminField>
              <AdminField label="Texto Booking" full><textarea value={settings.landing.bookingDescription || ''} placeholder={t('book_desc')} onChange={e => updateSection('landing', { bookingDescription: e.target.value })} style={textAreaStyle} /></AdminField>
              <AdminField label="Título CTA"><input value={settings.landing.ctaTitle || ''} placeholder={t('cta_title')} onChange={e => updateSection('landing', { ctaTitle: e.target.value })} style={inputStyle} /></AdminField>
              <AdminField label="Texto CTA"><input value={settings.landing.ctaDescription || ''} placeholder={t('cta_desc')} onChange={e => updateSection('landing', { ctaDescription: e.target.value })} style={inputStyle} /></AdminField>
            </AdminFormSection>
          </SettingCard>
        )}

        {activeSection === 'ventas' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }} className="dash-grid">
            <SettingCard title="Cotizaciones" subtitle="Reglas base para solicitudes y propuestas.">
              <AdminFormSection title="Cliente" columns={2}>
                <AdminField label="Tiempo de respuesta (horas)"><input type="number" min="1" value={settings.quoting.responseTimeHours} onChange={e => updateSection('quoting', { responseTimeHours: Number(e.target.value || 0) })} style={inputStyle} /></AdminField>
                <AdminField label="Contacto por defecto">
                  <select value={settings.quoting.defaultContactPreference} onChange={e => updateSection('quoting', { defaultContactPreference: e.target.value })} style={inputStyle}>
                    <option>WhatsApp</option><option>Email</option><option>Teléfono</option>
                  </select>
                </AdminField>
                <ToggleRow title="Requerir teléfono" checked={settings.quoting.requirePhone} onChange={value => updateSection('quoting', { requirePhone: value })} />
                <ToggleRow title="Requerir correo" checked={settings.quoting.requireEmail} onChange={value => updateSection('quoting', { requireEmail: value })} />
              </AdminFormSection>
            </SettingCard>

            <SettingCard title="Operación" subtitle="Valores usados como referencia para calendario e inventario.">
              <AdminFormSection title="Negocio" columns={2}>
                <AdminField label="Moneda"><input value={settings.operations.currency} onChange={e => updateSection('operations', { currency: e.target.value })} style={inputStyle} /></AdminField>
                <AdminField label="Zona horaria"><input value={settings.operations.timezone} onChange={e => updateSection('operations', { timezone: e.target.value })} style={inputStyle} /></AdminField>
                <AdminField label="Duración evento (horas)"><input type="number" min="1" value={settings.operations.eventDefaultDurationHours} onChange={e => updateSection('operations', { eventDefaultDurationHours: Number(e.target.value || 0) })} style={inputStyle} /></AdminField>
                <AdminField label="Alerta stock bajo"><input type="number" min="0" value={settings.operations.lowStockThreshold} onChange={e => updateSection('operations', { lowStockThreshold: Number(e.target.value || 0) })} style={inputStyle} /></AdminField>
                <AdminField label="Anticipo sugerido (%)"><input type="number" min="0" value={settings.quoting.minimumDepositPercent} onChange={e => updateSection('quoting', { minimumDepositPercent: Number(e.target.value || 0) })} style={inputStyle} /></AdminField>
                <AdminField label="Impuesto (%)"><input type="number" min="0" value={settings.quoting.taxPercent} onChange={e => updateSection('quoting', { taxPercent: Number(e.target.value || 0) })} style={inputStyle} /></AdminField>
              </AdminFormSection>
            </SettingCard>
          </div>
        )}

        {activeSection === 'admin' && (
          <SettingCard title="Panel de administrador" subtitle="Activa o apaga módulos visibles del panel sin borrar datos.">
            <AdminField label="Subtítulo del dashboard" full><input value={settings.admin.dashboardSubtitle} onChange={e => updateSection('admin', { dashboardSubtitle: e.target.value })} style={inputStyle} /></AdminField>
            <div style={{ marginTop: 14 }}>
              <ToggleRow title="Módulo de finanzas" checked={settings.admin.showFinance} onChange={value => updateSection('admin', { showFinance: value })} />
              <ToggleRow title="Módulo de inventario" checked={settings.admin.showInventory} onChange={value => updateSection('admin', { showInventory: value })} />
              <ToggleRow title="Módulo de correos" checked={settings.admin.showEmail} onChange={value => updateSection('admin', { showEmail: value })} />
              <ToggleRow title="Módulo de postres" checked={settings.admin.showDesserts} onChange={value => updateSection('admin', { showDesserts: value })} />
              <ToggleRow title="Herramienta Postera" checked={settings.admin.showPostera} onChange={value => updateSection('admin', { showPostera: value })} />
            </div>
          </SettingCard>
        )}

        {activeSection === 'integraciones' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }} className="dash-grid">
            <SettingCard title="Supabase" subtitle="URL y publishable/anon key. Nunca uses service role key en navegador.">
              <div>
                <AdminField label="Project URL"><input value={url} onChange={e => setUrl(e.target.value)} placeholder="https://xxxxx.supabase.co" style={inputStyle} /></AdminField>
                <div style={{ height: 12 }} />
                <AdminField label="Publishable key"><textarea value={anonKey} onChange={e => setAnonKey(e.target.value)} rows={4} placeholder="eyJhbGciOi..." style={textAreaStyle} /></AdminField>
                <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginTop: 14 }}>
                  <Btn type="button" disabled={busy} onClick={saveRemote}>Guardar conexión</Btn>
                  <Btn type="button" variant="ghost" disabled={busy || !window.LelusaStore.isRemoteConfigured()} onClick={refresh}>Recargar</Btn>
                </div>
                <p style={{ margin: '14px 0 0', fontSize: 12, color: 'var(--muted)', lineHeight: 1.5 }}>Primero ejecuta `supabase/setup.sql` en el SQL Editor del proyecto.</p>
              </div>
            </SettingCard>

            <SettingCard title="Canales externos" subtitle="Estado de sistemas que viven fuera del navegador.">
              <ToggleRow title="Catálogo público" checked={settings.features.publicCatalog} onChange={value => updateSection('features', { publicCatalog: value })} />
              <ToggleRow title="Cotizaciones personalizadas" checked={settings.features.customQuotes} onChange={value => updateSection('features', { customQuotes: value })} />
              <ToggleRow title="Postres" checked={settings.features.desserts} onChange={value => updateSection('features', { desserts: value })} />
              <ToggleRow title="Correos a clientes" checked={settings.features.clientEmails} onChange={value => updateSection('features', { clientEmails: value })} />
              <ToggleRow title="Correos internos" checked={settings.features.internalEmails} onChange={value => updateSection('features', { internalEmails: value })} />
              <div style={{ marginTop: 14 }}>
                <Btn type="button" variant="ghost" onClick={() => navigate('admin-email')}>Abrir configuración de correos</Btn>
              </div>
            </SettingCard>
          </div>
        )}

        {activeSection === 'notificaciones' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }} className="dash-grid">
            <SettingCard title="Notificaciones del dispositivo" subtitle="Instalación, permisos y alertas para este navegador o móvil.">
              <div style={{ display: 'grid', gap: 10 }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '10px 0', borderBottom: '1px solid var(--border)' }}>
                  <span>
                    <span style={{ display: 'block', fontSize: 13, fontWeight: 800, color: 'var(--text)' }}>{t('admin_notif_realtime_alerts')}</span>
                    <span style={{ display: 'block', fontSize: 12, color: 'var(--muted)', marginTop: 3 }}>{realtimeLabel}</span>
                  </span>
                  <span style={{ border: '1px solid var(--border)', background: notificationState.realtimeStatus === 'connected' ? '#DCF5E6' : 'var(--bg-soft)', color: notificationState.realtimeStatus === 'connected' ? '#2A8A50' : 'var(--muted)', borderRadius: 999, padding: '6px 10px', fontSize: 11, fontWeight: 900 }}>SSE</span>
                </div>

                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '10px 0', borderBottom: '1px solid var(--border)' }}>
                  <span>
                    <span style={{ display: 'block', fontSize: 13, fontWeight: 800, color: 'var(--text)' }}>{t('admin_notif_browser_alerts')}</span>
                    <span style={{ display: 'block', fontSize: 12, color: 'var(--muted)', marginTop: 3 }}>{notificationState.permission === 'granted' ? t('admin_notif_active') : t('admin_notif_activate')}</span>
                  </span>
                  <Btn type="button" size="sm" variant={notificationState.permission === 'granted' ? 'ghost' : 'primary'} disabled={!notificationState.supported || notificationState.permission === 'granted'} onClick={requestPermission}>
                    {notificationState.permission === 'granted' ? t('admin_notif_active') : t('admin_notif_activate')}
                  </Btn>
                </div>

                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '10px 0', borderBottom: '1px solid var(--border)' }}>
                  <span>
                    <span style={{ display: 'block', fontSize: 13, fontWeight: 800, color: 'var(--text)' }}>{t('admin_notif_mobile_app')}</span>
                    <span style={{ display: 'block', fontSize: 12, color: 'var(--muted)', marginTop: 3 }}>{pwaState.installed ? t('admin_notif_installed') : t('admin_notif_install')}</span>
                  </span>
                  <Btn type="button" size="sm" variant={pwaState.installed ? 'ghost' : 'primary'} disabled={!pwaState.installable || pwaState.installed} onClick={installPwa}>
                    {pwaState.installed ? t('admin_notif_installed') : t('admin_notif_install')}
                  </Btn>
                </div>

                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '10px 0' }}>
                  <span>
                    <span style={{ display: 'block', fontSize: 13, fontWeight: 800, color: 'var(--text)' }}>{t('admin_notif_pwa_alerts')}</span>
                    <span style={{ display: 'block', fontSize: 12, color: 'var(--muted)', marginTop: 3 }}>{notificationState.prefs?.pushReady ? t('admin_notif_push_active') : notificationState.prefs?.pwaDeviceEnabled ? t('admin_notif_active') : t('admin_notif_activate')}</span>
                  </span>
                  <Btn type="button" size="sm" variant={notificationState.prefs?.pwaDeviceEnabled ? 'ghost' : 'primary'} disabled={!notificationState.pushSupported && !notificationState.supported} onClick={enablePwaNotifications}>
                    {notificationState.prefs?.pushReady ? t('admin_notif_push_active') : notificationState.prefs?.pwaDeviceEnabled ? t('admin_notif_active') : t('admin_notif_activate')}
                  </Btn>
                </div>
              </div>
              <p style={{ margin: '14px 0 0', fontSize: 12, color: 'var(--muted)', lineHeight: 1.5 }}>{t('admin_notif_pwa_help')}</p>
              {notificationState.prefs?.pushSetupMessage && <p style={{ margin: '8px 0 0', fontSize: 12, color: 'var(--primary)', fontWeight: 700, lineHeight: 1.45 }}>{notificationState.prefs.pushSetupMessage}</p>}
            </SettingCard>

            <SettingCard title="Web Push PWA" subtitle="La clave privada se configura como secreto de Supabase.">
              <AdminField label="VAPID public key" full>
                <textarea value={vapidPublicKey} onChange={e => setVapidPublicKey(e.target.value)} rows={3} placeholder="B..." style={textAreaStyle} />
              </AdminField>
              <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginTop: 12 }}>
                <Btn type="button" onClick={savePush}>Guardar Web Push</Btn>
              </div>
            </SettingCard>

            <SettingCard title="Categorías de notificación" subtitle="Preferencias de este usuario/dispositivo. El historial se conserva.">
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: 8 }}>
                {NOTIFICATION_CATEGORIES.map(([category, label]) => (
                  <label key={category} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px', borderRadius: 12, border: '1px solid var(--border)', background: 'var(--bg-soft)', fontSize: 12, fontWeight: 700, cursor: 'pointer' }}>
                    <input type="checkbox" checked={!mutedCategories[category]} onChange={() => toggleCategory(category)} />
                    {label}
                  </label>
                ))}
              </div>
              {canSend && (
                <div style={{ marginTop: 16 }}>
                  <Btn type="button" onClick={() => navigate('admin-send-notification')}>Enviar notificación al equipo</Btn>
                </div>
              )}
            </SettingCard>
          </div>
        )}
      </form>
    </AdminLayout>
  );
}

Object.assign(window, { SettingsPage });
