// Pau Fit — Auth (Login + Onboarding), Chat, Notificaciones, Admin

const { useState: useS4, useEffect: useE4, useRef: useR4 } = React;

// ═════════════════════════════════════════════════════════════
// AUTH HELPERS — Supabase real
// ═════════════════════════════════════════════════════════════
async function _pauLoginGoogle(nav) {
  const sb = window.__PAU_SUPABASE;
  if (!sb) { nav && nav.toast('Supabase no disponible', { icon: '⚠️' }); return; }
  try {
    // Sale del iframe y va a Google directamente para evitar X-Frame-Options
    const redirectTo = (window.location.origin || 'https://app.paufit.co') + '/prototype/auth-complete.html';
    const { data, error } = await sb.auth.signInWithOAuth({
      provider: 'google',
      options: { redirectTo, skipBrowserRedirect: true },
    });
    if (error) throw error;
    if (data?.url) {
      if (window.PauNative && window.PauNative.isNativeApp) {
        window.PauNative.openExternal(data.url);
      } else if (window.top && window.top !== window) {
        window.top.location.href = data.url;
      } else {
        window.location.href = data.url;
      }
    }
  } catch (e) {
    console.error('Google login error:', e);
    nav && nav.toast(e.message || 'No se pudo iniciar sesión', { icon: '⚠️' });
  }
}

async function _pauLoginApple(nav) {
  const sb = window.__PAU_SUPABASE;
  if (!sb) { nav && nav.toast('Supabase no disponible', { icon: '⚠️' }); return; }
  try {
    const redirectTo = (window.location.origin || 'https://app.paufit.co') + '/prototype/auth-complete.html';
    const { data, error } = await sb.auth.signInWithOAuth({
      provider: 'apple',
      options: { redirectTo, skipBrowserRedirect: true },
    });
    if (error) throw error;
    if (data?.url) {
      if (window.PauNative && window.PauNative.isNativeApp) {
        window.PauNative.openExternal(data.url);
      } else if (window.top && window.top !== window) {
        window.top.location.href = data.url;
      } else {
        window.location.href = data.url;
      }
    }
  } catch (e) {
    console.error('Apple login error:', e);
    nav && nav.toast(e.message || 'No se pudo iniciar sesión', { icon: '⚠️' });
  }
}

async function _pauLoginEmail(email, pass, mode, nav) {
  const sb = window.__PAU_SUPABASE;
  if (!sb) { nav && nav.toast('Supabase no disponible', { icon: '⚠️' }); return; }
  if (!email || !pass) {
    nav && nav.toast('Rellena email y contraseña', { icon: '⚠️' });
    return;
  }
  try {
    if (mode === 'signup') {
      const { error } = await sb.auth.signUp({ email, password: pass });
      if (error) throw error;
      nav && nav.toast('¡Cuenta creada! Revisa tu email 💗', { icon: '✓' });
    } else {
      const { error } = await sb.auth.signInWithPassword({ email, password: pass });
      if (error) throw error;
      nav && nav.toast('¡Hola de nuevo! 💗', { icon: '✓' });
    }
  } catch (e) {
    console.error('Email auth error:', e);
    nav && nav.toast(e.message || 'Error de autenticación', { icon: '⚠️' });
  }
}

// ═════════════════════════════════════════════════════════════
// LOGIN
// ═════════════════════════════════════════════════════════════
function LoginScreen({ theme, nav }) {
  const T = theme;
  const [mode, setMode] = useS4('login'); // login | signup
  const [email, setEmail] = useS4('');
  const [pass, setPass] = useS4('');
  const [loading, setLoading] = useS4(false);

  return (
    <div style={{
      paddingTop: 50, paddingBottom: 30,
      minHeight: '100%',
      background: `linear-gradient(180deg, ${T.subtle} 0%, ${T.bg} 60%)`,
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Logo */}
      <div style={{ padding: '20px 22px 0', textAlign: 'center' }}>
        <img src="/branding/logo.png" alt="Pau Fit" style={{
          width: 88, height: 88, objectFit: 'contain',
          filter: `drop-shadow(0 12px 28px ${T.accent}55)`,
        }}/>
        <div style={{ fontFamily: 'Poppins', fontSize: 28, fontWeight: 600, color: T.text, marginTop: 8, letterSpacing: -0.6 }}>Pau Fit</div>
        <div style={{ fontFamily: 'Poppins', fontSize: 13, color: T.muted, marginTop: 4, fontStyle: 'italic' }}>#YoSiemprePuedo 💗</div>
      </div>

      <div style={{ padding: '32px 22px 0', flex: 1 }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 20, fontWeight: 600, color: T.text, letterSpacing: -0.3 }}>
          {mode === 'login' ? 'Hola otra vez 💗' : 'Crea tu cuenta'}
        </div>
        <div style={{ fontFamily: 'Poppins', fontSize: 13, color: T.muted, marginTop: 4, lineHeight: 1.4 }}>
          {mode === 'login' ? 'Continúa donde lo dejaste' : 'Empieza tu transformación hoy'}
        </div>

        {/* Social buttons — REALES (Supabase OAuth) */}
        <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <SocialBtn dark icon={<AppleGlyph/>} label="Continuar con Apple" T={T} onClick={() => _pauLoginApple(nav)}/>
          <SocialBtn icon={<GoogleGlyph/>} label="Continuar con Google" T={T} onClick={() => _pauLoginGoogle(nav)}/>
        </div>

        {/* Divider */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '22px 0' }}>
          <div style={{ flex: 1, height: 0.5, background: T.muted, opacity: 0.3 }}/>
          <span style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 500, letterSpacing: 0.4 }}>o con email</span>
          <div style={{ flex: 1, height: 0.5, background: T.muted, opacity: 0.3 }}/>
        </div>

        {/* Email + password */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="tu@email.com" type="email" style={{
            padding: '14px 16px', border: T.border, borderRadius: 20, background: T.card,
            fontFamily: 'Poppins', fontSize: 14, color: T.text, outline: 'none',
          }}/>
          <input value={pass} onChange={(e) => setPass(e.target.value)} placeholder="Contraseña" type="password" style={{
            padding: '14px 16px', border: T.border, borderRadius: 20, background: T.card,
            fontFamily: 'Poppins', fontSize: 14, color: T.text, outline: 'none',
          }}/>
        </div>

        {mode === 'login' && (
          <button onClick={async () => {
            if (!email) { nav.toast('Escribe tu email primero', { icon: '⚠️' }); return; }
            const sb = window.__PAU_SUPABASE;
            if (!sb) { nav.toast('Sin conexión', { icon: '⚠️' }); return; }
            const { error } = await sb.auth.resetPasswordForEmail(email, {
              redirectTo: (window.location.origin || 'https://app.paufit.co') + '/prototype/auth-complete.html',
            });
            if (error) nav.toast('Error: ' + error.message, { icon: '⚠️' });
            else nav.toast('Te enviamos un email para recuperar 💗', { icon: '✉️' });
          }} style={{
            marginTop: 10, alignSelf: 'flex-end',
            border: 'none', background: 'transparent', cursor: 'pointer',
            fontFamily: 'Poppins', fontSize: 12, fontWeight: 500, color: T.accent,
          }}>¿Olvidaste tu contraseña?</button>
        )}

        <button onClick={async () => {
          setLoading(true);
          await _pauLoginEmail(email, pass, mode, nav);
          setLoading(false);
        }} disabled={loading} style={{
          marginTop: 14, width: '100%', padding: '16px',
          border: 'none', borderRadius: 20, cursor: loading ? 'wait' : 'pointer',
          background: loading ? `${T.accent}99` : T.accent, color: '#fff',
          fontFamily: 'Poppins', fontSize: 15, fontWeight: 600, letterSpacing: -0.1,
          boxShadow: `0 6px 18px ${T.accent}40`,
        }}>{loading ? '…' : (mode === 'login' ? 'Entrar' : 'Crear cuenta')}</button>

        <div style={{ textAlign: 'center', marginTop: 18, fontFamily: 'Poppins', fontSize: 13, color: T.muted }}>
          {mode === 'login' ? '¿Aún no tienes cuenta?' : '¿Ya tienes cuenta?'}{' '}
          <button onClick={() => setMode(mode === 'login' ? 'signup' : 'login')} style={{
            border: 'none', background: 'transparent', cursor: 'pointer',
            fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: T.accent,
          }}>{mode === 'login' ? 'Crea una' : 'Entra aquí'}</button>
        </div>
      </div>

      <div style={{ padding: '0 22px', textAlign: 'center', fontFamily: 'Poppins', fontSize: 10, color: T.muted, lineHeight: 1.5 }}>
        Al continuar aceptas los términos y la política de privacidad de Pau Fit.
      </div>
    </div>
  );
}

function SocialBtn({ dark, icon, label, T, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', padding: '14px',
      border: dark ? 'none' : T.border,
      background: dark ? '#000' : T.card,
      color: dark ? '#fff' : T.text,
      borderRadius: 20, cursor: 'pointer',
      fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, letterSpacing: -0.1,
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
    }}>
      {icon}
      {label}
    </button>
  );
}
function AppleGlyph() {
  return <svg width="18" height="20" viewBox="0 0 18 20" fill="currentColor"><path d="M14.5 11c0-2 1.4-3 1.5-3 -.7-1-1.8-1.2-2.2-1.2-1-.1-1.9.6-2.4.6-.5 0-1.3-.6-2.2-.5-1.1 0-2.1.7-2.7 1.7-1.2 2-.3 5 .8 6.7.6.8 1.2 1.8 2.1 1.7.9 0 1.2-.5 2.2-.5 1 0 1.3.5 2.2.5.9 0 1.5-.9 2.1-1.7.5-.7.7-1.3.9-2 -1-.3-2.3-1.1-2.3-2.3zM12 4c.5-.6.9-1.4.8-2.3 -.7 0-1.6.5-2.1 1.1 -.5.6-.9 1.4-.8 2.2 .8.1 1.6-.4 2.1-1z"/></svg>;
}
function GoogleGlyph() {
  return <svg width="18" height="18" viewBox="0 0 18 18">
    <path fill="#4285F4" d="M17.6 9.2c0-.6 0-1.2-.1-1.7H9v3.3h4.8c-.2 1.1-.8 2-1.8 2.6v2.2h2.9c1.7-1.6 2.7-3.9 2.7-6.4z"/>
    <path fill="#34A853" d="M9 18c2.4 0 4.5-.8 6-2.2l-2.9-2.2c-.8.5-1.8.9-3.1.9-2.4 0-4.4-1.6-5.1-3.8H.9v2.3C2.4 16 5.4 18 9 18z"/>
    <path fill="#FBBC05" d="M3.9 10.7c-.2-.5-.3-1.1-.3-1.7s.1-1.2.3-1.7V5H.9C.3 6.2 0 7.6 0 9s.3 2.8.9 4l3-2.3z"/>
    <path fill="#EA4335" d="M9 3.6c1.3 0 2.5.5 3.4 1.4l2.6-2.6C13.5.9 11.4 0 9 0 5.4 0 2.4 2 .9 5l3 2.3C4.6 5.1 6.6 3.6 9 3.6z"/>
  </svg>;
}

// ═════════════════════════════════════════════════════════════
// ONBOARDING — 4 pasos
// ═════════════════════════════════════════════════════════════
// Lógica de recomendación basada en respuestas del onboarding
function recommendRetoFor(obj, days, level) {
  // Solo retos GRATIS para no bloquear con paywall en el primer contacto.
  if (obj === 'bienestar') return 'mindful-7';
  if (obj === 'tonificar') return 'cintura-bee';
  if (obj === 'quemar' && days <= 4) return 'mindful-7';
  if (obj === 'quemar') return 'transforma-14';
  if (obj === 'musculo') return 'transforma-14'; // GRATIS, los PRO los compra después
  return 'transforma-14';
}

function OnboardingScreen({ theme, nav, onDone }) {
  const T = theme;
  const [step, setStep] = useS4(0);
  const [name, setName] = useS4('');
  const [obj, setObj] = useS4(null);
  const [days, setDays] = useS4(null);
  const [level, setLevel] = useS4(null);
  const [saving, setSaving] = useS4(false);

  const steps = [
    { title: '¿Cómo te llamas?', sub: 'Para personalizarlo todo 💗' },
    { title: '¿Cuál es tu objetivo?', sub: 'Adaptaremos tu programa' },
    { title: '¿Tu nivel ahora mismo?', sub: 'Sé honesta, podrás cambiarlo' },
    { title: '¿Días por semana?', sub: 'Sé realista, sin presión' },
    { title: 'Tu programa ideal', sub: 'Basado en tus respuestas' },
  ];
  const total = steps.length;
  const currentValid = (
    (step === 0 && name.trim().length > 0) ||
    (step === 1 && obj) ||
    (step === 2 && level) ||
    (step === 3 && days) ||
    (step === 4)
  );

  // Reto recomendado (en step 4)
  const recRetoId = (obj && days) ? recommendRetoFor(obj, days, level) : null;
  const recReto = recRetoId ? RETOS.find(r => r.id === recRetoId) : null;

  async function finish() {
    setSaving(true);
    console.log('[onboarding] finish: empezando');
    // Timeout de seguridad — si después de 7s seguimos atascados, forzamos navegación
    const timeoutId = setTimeout(() => {
      console.warn('[onboarding] timeout 7s — forzando navegación');
      setSaving(false);
      if (onDone) onDone();
      else nav.tab('home');
    }, 7000);

    // Helper con timeout por operación
    const withTimeout = (promise, ms, label) => Promise.race([
      promise,
      new Promise((_, reject) => setTimeout(() => reject(new Error(label + ' timeout')), ms)),
    ]);

    // 1) Guardar perfil (best-effort, max 4s)
    try {
      const sb = window.__PAU_SUPABASE;
      if (sb) {
        const { data: { user } } = await withTimeout(sb.auth.getUser(), 3000, 'getUser');
        if (user) {
          const updates = {
            full_name: name.trim(),
            goal: obj,
            level,
            target_days_per_week: days,
          };
          await withTimeout(
            sb.from('profiles').update(updates).eq('id', user.id),
            4000, 'update profile'
          );
          window.__pauCache = window.__pauCache || {};
          window.__pauCache.profile = { ...(window.__pauCache.profile || {}), ...updates, email: user.email };
          console.log('[onboarding] perfil guardado');
        }
      }
    } catch (e) {
      console.warn('[onboarding] guardar perfil falló (continuamos):', e?.message || e);
    }

    // 2) Auto-unir al reto recomendado (best-effort, max 4s)
    try {
      if (recRetoId && window.PauUserRetos) {
        const res = await withTimeout(window.PauUserRetos.start(recRetoId), 4000, 'start reto');
        if (res?.row) {
          window.__pauCache.activeReto = res.row;
          window.dispatchEvent(new CustomEvent('pau:cache-updated'));
          console.log('[onboarding] reto unido:', recRetoId);
        }
      }
    } catch (e) {
      console.warn('[onboarding] auto-join reto falló (continuamos):', e?.message || e);
    }

    clearTimeout(timeoutId);
    setSaving(false);
    console.log('[onboarding] finish: completado, navegando home');
    if (onDone) onDone();
    else nav.tab('home');
  }

  function next() {
    if (step < total - 1) setStep(step + 1);
    else finish();
  }

  return (
    <div style={{ paddingTop: 50, paddingBottom: 30, minHeight: '100%', background: T.bg, display: 'flex', flexDirection: 'column' }}>
      {/* Progress */}
      <div style={{ padding: '12px 20px 0', display: 'flex', alignItems: 'center', gap: 10 }}>
        <button onClick={() => step > 0 ? setStep(step - 1) : nav.back()} style={{
          width: 32, height: 32, borderRadius: 999, border: 'none',
          background: T.card, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{Icon.back(T.text)}</button>
        <div style={{ flex: 1, height: 3, background: T.subtle, borderRadius: 999, overflow: 'hidden' }}>
          <div style={{ width: `${(step + 1) / total * 100}%`, height: '100%', background: T.accent, borderRadius: 999, transition: 'width 300ms ease' }}/>
        </div>
        <span style={{ fontFamily: 'Poppins', fontSize: 12, color: T.muted, fontWeight: 600 }}>{step + 1}/{total}</span>
      </div>

      <div style={{ padding: '32px 20px 0', flex: 1 }}>
        <div className="pf-display" style={{ fontSize: 30, fontWeight: 700, color: T.text, letterSpacing: -0.8, lineHeight: 1.1 }}>{steps[step].title}</div>
        <div style={{ fontSize: 13, color: T.muted, marginTop: 8, lineHeight: 1.45 }}>{steps[step].sub}</div>

        <div style={{ marginTop: 28 }}>
          {step === 0 && (
            <input autoFocus value={name} onChange={(e) => setName(e.target.value)} placeholder="Tu nombre" style={{
              width: '100%', padding: '16px',
              border: `1.5px solid ${name ? T.accent : T.muted + '40'}`,
              borderRadius: 20, background: T.card,
              fontFamily: 'Poppins', fontSize: 18, color: T.text, outline: 'none',
              fontWeight: 500,
            }}/>
          )}

          {/* Objetivo */}
          {step === 1 && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              {[
                { v: 'quemar', e: '🔥', t: 'Quemar grasa' },
                { v: 'tonificar', e: '✨', t: 'Tonificar' },
                { v: 'musculo', e: '💪🏻', t: 'Ganar músculo' },
                { v: 'bienestar', e: '🧘🏼‍♀️', t: 'Sentirme bien' },
              ].map(o => {
                const sel = obj === o.v;
                return (
                  <button key={o.v} onClick={() => setObj(o.v)} style={{
                    padding: '20px 14px',
                    border: sel ? `1.5px solid ${T.accent}` : T.border,
                    background: sel ? `${T.accent}10` : T.card,
                    borderRadius: 20, cursor: 'pointer', textAlign: 'left',
                    display: 'flex', flexDirection: 'column', gap: 8,
                  }}>
                    <span style={{ fontSize: 30 }}>{o.e}</span>
                    <span style={{ fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: T.text }}>{o.t}</span>
                  </button>
                );
              })}
            </div>
          )}

          {/* Nivel */}
          {step === 2 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {[
                { v: 'principiante', e: '🌱', t: 'Principiante', s: 'No entreno o muy poco' },
                { v: 'intermedio', e: '💪🏻', t: 'Intermedio', s: 'Entreno desde hace tiempo' },
                { v: 'avanzado', e: '🔥', t: 'Avanzado', s: 'Entreno regular e intenso' },
              ].map(o => {
                const sel = level === o.v;
                return (
                  <button key={o.v} onClick={() => setLevel(o.v)} style={{
                    padding: '16px 20px',
                    border: sel ? `1.5px solid ${T.accent}` : T.border,
                    background: sel ? `${T.accent}10` : T.card,
                    borderRadius: 20, cursor: 'pointer', textAlign: 'left',
                    display: 'flex', alignItems: 'center', gap: 14,
                  }}>
                    <span style={{ fontSize: 26 }}>{o.e}</span>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontFamily: 'Poppins', fontSize: 15, fontWeight: 600, color: T.text }}>{o.t}</div>
                      <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, marginTop: 1 }}>{o.s}</div>
                    </div>
                  </button>
                );
              })}
            </div>
          )}

          {/* Días por semana */}
          {step === 3 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {[
                { v: 3, t: '3 días', s: 'Suave · me estoy iniciando' },
                { v: 4, t: '4 días', s: 'Equilibrado' },
                { v: 5, t: '5 días', s: 'Constante · ideal' },
                { v: 6, t: '6 días', s: 'Intenso · ya estoy en ello' },
              ].map(o => {
                const sel = days === o.v;
                return (
                  <button key={o.v} onClick={() => setDays(o.v)} style={{
                    padding: '16px 20px',
                    border: sel ? `1.5px solid ${T.accent}` : T.border,
                    background: sel ? `${T.accent}10` : T.card,
                    borderRadius: 20, cursor: 'pointer', textAlign: 'left',
                    display: 'flex', alignItems: 'center', gap: 14,
                  }}>
                    <div style={{
                      width: 22, height: 22, borderRadius: 999, flexShrink: 0,
                      border: sel ? 'none' : `1.5px solid ${T.muted}50`,
                      background: sel ? T.accent : 'transparent',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>{sel && <div style={{ width: 8, height: 8, borderRadius: 999, background: '#fff' }}/>}</div>
                    <div>
                      <div style={{ fontFamily: 'Poppins', fontSize: 16, fontWeight: 600, color: T.text }}>{o.t}</div>
                      <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, marginTop: 1 }}>{o.s}</div>
                    </div>
                  </button>
                );
              })}
            </div>
          )}

          {/* Recomendación FINAL */}
          {step === 4 && recReto && (
            <div>
              <div style={{
                marginTop: 8, borderRadius: 20, overflow: 'hidden',
                background: '#000', position: 'relative',
                aspectRatio: '3 / 4',
                boxShadow: `0 12px 28px rgba(0,0,0,0.15)`,
              }}>
                {recReto.image && (
                  <img loading="lazy" src={recReto.image} alt={recReto.title} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }}/>
                )}
                <div style={{
                  position: 'absolute', inset: 0,
                  background: 'linear-gradient(180deg, rgba(0,0,0,0.3) 0%, transparent 40%, rgba(0,0,0,0.85) 100%)',
                }}/>
                <div style={{
                  position: 'absolute', top: 14, left: 14,
                  padding: '5px 10px', borderRadius: 6,
                  background: 'rgba(255,255,255,0.95)',
                  fontSize: 10, fontWeight: 800, color: recReto.deep || '#0E0A0C', letterSpacing: 1,
                }}>RECOMENDADO PARA TI</div>
                <div style={{ position: 'absolute', bottom: 18, left: 18, right: 18, color: '#fff' }}>
                  <div className="pf-display" style={{ fontSize: 26, fontWeight: 700, letterSpacing: -0.5, lineHeight: 1.1 }}>{recReto.title}</div>
                  <div style={{ fontSize: 12, marginTop: 6, opacity: 0.85 }}>
                    {recReto.days} días · {recReto.minPerDay} min/día · {recReto.intensity}
                  </div>
                </div>
              </div>

              <div style={{
                marginTop: 14, padding: '14px 16px',
                background: T.card, borderRadius: 20, border: T.border,
                display: 'flex', alignItems: 'center', gap: 10,
              }}>
                <span style={{ fontSize: 22 }}>💡</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12, fontWeight: 700, color: T.text }}>¿Por qué este reto?</div>
                  <div style={{ fontSize: 11, color: T.muted, marginTop: 2, lineHeight: 1.4 }}>
                    Encaja con tu objetivo de {obj === 'quemar' ? 'quemar grasa' : obj === 'tonificar' ? 'tonificar' : obj === 'musculo' ? 'ganar músculo' : 'bienestar'}
                    {' '}y nivel {level}.
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      <div style={{ padding: '0 20px' }}>
        <button onClick={next} disabled={!currentValid || saving} style={{
          width: '100%', padding: '16px',
          border: 'none', borderRadius: 20,
          cursor: (currentValid && !saving) ? 'pointer' : 'not-allowed',
          background: currentValid ? T.accent : T.subtle,
          color: currentValid ? '#fff' : T.muted,
          fontFamily: 'Poppins', fontSize: 15, fontWeight: 600, letterSpacing: -0.1,
          transition: 'all 200ms ease',
          boxShadow: currentValid ? `0 6px 18px ${T.accent}40` : 'none',
          opacity: saving ? 0.7 : 1,
        }}>
          {saving ? 'Guardando…' : step === total - 1 ? '¡Empezar mi reto! 💗' : 'Siguiente'}
        </button>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// CHAT — comunidad REAL (Supabase: community_messages + realtime)
// ═════════════════════════════════════════════════════════════
function _chatFmtTime(ts) {
  const d = new Date(ts);
  if (isNaN(d.getTime())) return '';
  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
}

// La tabla community_messages puede no existir aún (migración pendiente)
function _chatTableMissing(e) {
  if (!e) return false;
  const code = e.code || '';
  const msg = String(e.message || '');
  return code === 'PGRST205' || code === '42P01' || msg.includes('community_messages');
}

function ChatScreen({ theme, nav }) {
  const T = theme;
  const [input, setInput] = useS4('');
  const [msgs, setMsgs] = useS4([]);           // filas de community_messages, ascendente
  const [profiles, setProfiles] = useS4({});   // user_id -> { id, username, full_name, avatar_url }
  const [loading, setLoading] = useS4(true);
  const [sending, setSending] = useS4(false);
  const [tableMissing, setTableMissing] = useS4(false);
  const scrollRef = useR4(null);
  const profilesRef = useR4({});               // espejo síncrono de profiles (para callbacks)

  const cache = (typeof window !== 'undefined' && window.__pauCache) || {};
  const me = cache.profile || {};
  const isGodmode = cache.isGodmode === true;

  function mergeProfiles(list) {
    if (!list || !list.length) return;
    const map = { ...profilesRef.current };
    list.forEach(p => { if (p && p.id) map[p.id] = p; });
    profilesRef.current = map;
    setProfiles(map);
  }

  async function fetchProfile(userId) {
    const sb = window.__PAU_SUPABASE;
    if (!sb || !userId || profilesRef.current[userId]) return;
    try {
      const { data, error } = await sb.from('profiles')
        .select('id, username, full_name, avatar_url')
        .eq('id', userId).maybeSingle();
      if (error) throw error;
      if (data) mergeProfiles([data]);
    } catch (e) {
      // No bloquea el chat: el mensaje se muestra con nombre "Usuaria"
      console.warn('[chat] perfil', e);
    }
  }

  async function loadMessages() {
    const sb = window.__PAU_SUPABASE;
    if (!sb) { nav.toast('Sin conexión — no se pudo cargar el chat', { icon: '⚠️' }); setLoading(false); return; }
    try {
      const { data, error } = await sb.from('community_messages')
        .select('id, user_id, content, created_at')
        .order('created_at', { ascending: false })
        .limit(60);
      if (error) throw error;
      const rows = (data || []).slice().reverse(); // ascendente para render
      // UNA query para todos los perfiles que falten
      const ids = [...new Set(rows.map(r => r.user_id).filter(Boolean))]
        .filter(id => !profilesRef.current[id]);
      if (ids.length) {
        const { data: profs, error: pErr } = await sb.from('profiles')
          .select('id, username, full_name, avatar_url')
          .in('id', ids);
        if (pErr) console.warn('[chat] perfiles', pErr);
        if (profs) mergeProfiles(profs);
      }
      setMsgs(rows);
      setTableMissing(false);
    } catch (e) {
      if (_chatTableMissing(e)) {
        setTableMissing(true);
      } else {
        console.warn('[chat] cargar', e);
        nav.toast('No se pudieron cargar los mensajes: ' + (e?.message || 'error de conexión'), { icon: '⚠️' });
      }
    } finally {
      setLoading(false);
    }
  }

  // Carga inicial + tiempo real + recarga al recibir foco (respaldo)
  useE4(() => {
    loadMessages();
    const onFocus = () => loadMessages();
    window.addEventListener('focus', onFocus);
    const sb = window.__PAU_SUPABASE;
    let ch = null;
    if (sb) {
      ch = sb.channel('community-chat')
        .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'community_messages' }, (payload) => {
          const m = payload && payload.new;
          if (!m || !m.id) return;
          setMsgs(prev => prev.some(x => x.id === m.id) ? prev : [...prev, m]);
          if (m.user_id && !profilesRef.current[m.user_id]) fetchProfile(m.user_id);
        })
        .subscribe();
    }
    return () => {
      window.removeEventListener('focus', onFocus);
      if (sb && ch) { try { sb.removeChannel(ch); } catch (e) { console.warn('[chat] cleanup', e); } }
    };
  }, []);

  // Auto-scroll al fondo al cargar y al añadir mensajes — rAF para esperar al DOM
  useE4(() => {
    requestAnimationFrame(() => {
      const el = scrollRef.current;
      if (el) el.scrollTop = el.scrollHeight;
    });
  }, [msgs, loading]);

  async function send() {
    const text = input.trim();
    if (!text || sending) return;
    if (text.length > 500) { nav.toast('Máximo 500 caracteres', { icon: '✏️' }); return; }
    const sb = window.__PAU_SUPABASE;
    if (!sb) { nav.toast('Sin conexión — inténtalo de nuevo', { icon: '⚠️' }); return; }
    setSending(true);
    try {
      const { data: { user: u } } = await sb.auth.getUser();
      if (!u) {
        nav.toast('Tu sesión expiró — cierra sesión y vuelve a entrar', { icon: '🔒' });
        setSending(false);
        return;
      }
      const { data, error } = await sb.from('community_messages')
        .insert({ user_id: u.id, content: text })
        .select('id, user_id, content, created_at')
        .single();
      if (error) throw error;
      // Optimista al confirmar: añade local (realtime lo trae también; dedupe por id)
      if (data) setMsgs(prev => prev.some(x => x.id === data.id) ? prev : [...prev, data]);
      setInput('');
    } catch (e) {
      console.warn('[chat] enviar', e);
      if (_chatTableMissing(e)) {
        setTableMissing(true);
      } else {
        // Conservamos el texto escrito (no se limpia el input)
        nav.toast('No se pudo enviar: ' + (e?.message || 'inténtalo de nuevo'), { icon: '⚠️' });
      }
    } finally {
      setSending(false);
    }
  }

  async function removeMsg(m) {
    const sb = window.__PAU_SUPABASE;
    if (!sb) { nav.toast('Sin conexión — inténtalo de nuevo', { icon: '⚠️' }); return; }
    if (!window.confirm('¿Borrar este mensaje?')) return;
    try {
      const { error } = await sb.from('community_messages').delete().eq('id', m.id);
      if (error) throw error;
      setMsgs(prev => prev.filter(x => x.id !== m.id));
    } catch (e) {
      console.warn('[chat] borrar', e);
      nav.toast('No se pudo borrar: ' + (e?.message || 'inténtalo de nuevo'), { icon: '⚠️' });
    }
  }

  function displayName(userId) {
    const p = profiles[userId];
    if (p) {
      if (p.username) return p.username;
      const first = (p.full_name || '').trim().split(/\s+/)[0];
      if (first) return first;
    }
    return 'Usuaria';
  }

  const header = (
    <div style={{
      padding: '50px 18px 14px',
      background: T.card, borderBottom: T.border,
      display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0,
    }}>
      <button onClick={() => nav.back()} style={{
        width: 32, height: 32, borderRadius: 999, border: 'none',
        background: 'transparent', cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{Icon.back(T.text)}</button>
      <div style={{
        width: 40, height: 40, borderRadius: 999,
        background: `linear-gradient(135deg, ${T.accent}, ${T.accent}99)`,
        display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18,
      }}>💗</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: T.text }}>Chat de la comunidad</div>
        <div style={{ fontSize: 10, color: T.muted, marginTop: 1 }}>Comparte tu progreso y motiva a otras 💗</div>
      </div>
    </div>
  );

  // Tabla aún no desplegada → pantalla amable, sin input
  if (tableMissing) {
    return (
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', background: T.bg }}>
        {header}
        <div style={{
          flex: 1, display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center', gap: 10,
          padding: 30, textAlign: 'center',
        }}>
          <div style={{ fontSize: 46 }}>💬</div>
          <div style={{ fontSize: 15, fontWeight: 600, color: T.text }}>El chat estará listo muy pronto 💗</div>
          <div style={{ fontSize: 12, color: T.muted, lineHeight: 1.5 }}>Estamos preparando este espacio para la comunidad.</div>
        </div>
      </div>
    );
  }

  return (
    <div style={{
      position: 'absolute', inset: 0,
      display: 'flex', flexDirection: 'column', background: T.bg,
    }}>
      {header}

      {/* Mensajes (scroll propio) */}
      <div ref={scrollRef} style={{
        flex: 1, minHeight: 0, padding: '14px 14px 14px',
        display: 'flex', flexDirection: 'column', gap: 8,
        overflowY: 'auto', overflowX: 'hidden',
        WebkitOverflowScrolling: 'touch',
      }}>
        {loading && (
          <div style={{ alignSelf: 'center', marginTop: 20, fontSize: 12, color: T.muted }}>Cargando mensajes…</div>
        )}

        {!loading && msgs.length === 0 && (
          <div style={{
            flex: 1, display: 'flex', flexDirection: 'column',
            alignItems: 'center', justifyContent: 'center', gap: 8,
            padding: 30, textAlign: 'center',
          }}>
            <div style={{ fontSize: 46 }}>💬</div>
            <div style={{ fontSize: 14, fontWeight: 600, color: T.text }}>Sé la primera en saludar 💗</div>
          </div>
        )}

        {msgs.map(m => {
          const mine = me.id && m.user_id === me.id;
          if (mine) {
            return (
              <div key={m.id} style={{ alignSelf: 'flex-end', maxWidth: '78%', display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
                <div style={{
                  padding: '10px 14px', background: T.accent, color: '#fff',
                  borderRadius: 20, fontSize: 13, lineHeight: 1.4,
                  wordBreak: 'break-word', whiteSpace: 'pre-wrap',
                }}>{m.content}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 2 }}>
                  <span style={{ fontSize: 9, color: T.muted }}>{_chatFmtTime(m.created_at)}</span>
                  <button onClick={() => removeMsg(m)} title="Borrar mensaje" aria-label="Borrar mensaje" style={{
                    border: 'none', background: 'transparent', cursor: 'pointer',
                    color: T.muted, fontSize: 13, lineHeight: 1, padding: '0 2px',
                  }}>×</button>
                </div>
              </div>
            );
          }
          const p = profiles[m.user_id];
          const name = displayName(m.user_id);
          const initial = (name.trim()[0] || 'U').toUpperCase();
          return (
            <div key={m.id} style={{ display: 'flex', gap: 8, alignItems: 'flex-end', alignSelf: 'flex-start', maxWidth: '85%' }}>
              <div style={{
                width: 28, height: 28, borderRadius: 999, flexShrink: 0, overflow: 'hidden',
                background: `linear-gradient(135deg, ${T.accent}, ${T.accent}99)`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 11, fontWeight: 700, color: '#fff',
              }}>
                {p && p.avatar_url
                  ? <img src={p.avatar_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                  : initial}
              </div>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2, paddingLeft: 4 }}>
                  <span style={{ fontSize: 10, fontWeight: 600, color: T.text }}>{name}</span>
                  <span style={{ fontSize: 9, color: T.muted }}>{_chatFmtTime(m.created_at)}</span>
                  {isGodmode && (
                    <button onClick={() => removeMsg(m)} title="Borrar mensaje" aria-label="Borrar mensaje" style={{
                      border: 'none', background: 'transparent', cursor: 'pointer',
                      color: T.muted, fontSize: 13, lineHeight: 1, padding: '0 2px',
                    }}>×</button>
                  )}
                </div>
                <div style={{
                  padding: '10px 14px', background: T.card, color: T.text,
                  borderRadius: 20, border: T.border, fontSize: 13, lineHeight: 1.4,
                  wordBreak: 'break-word', whiteSpace: 'pre-wrap',
                }}>{m.content}</div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Input fijo abajo */}
      <div style={{
        padding: '10px 14px 30px', background: T.bg,
        borderTop: T.border, display: 'flex', alignItems: 'center', gap: 8,
        flexShrink: 0,
      }}>
        <input value={input} onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && send()}
          maxLength={500}
          placeholder="Escribe a la comunidad…" style={{
          flex: 1, padding: '10px 16px', border: T.border, borderRadius: 999,
          background: T.card, fontSize: 14, color: T.text, outline: 'none',
        }}/>
        <button onClick={send} disabled={sending} aria-label="Enviar" style={{
          width: 38, height: 38, borderRadius: 999, border: 'none',
          background: T.accent, cursor: sending ? 'default' : 'pointer',
          opacity: sending ? 0.6 : 1,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="#fff"><path d="M2 8l12-6-4 14-2-6-6-2z"/></svg>
        </button>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// NOTIFICACIONES — settings + preview
// ═════════════════════════════════════════════════════════════
function NotificacionesScreen({ theme, nav }) {
  const T = theme;
  // Cargar preferencias REALES desde localStorage
  const defaultPrefs = { workout: true, streak: true, retos: false, comunidad: true, motivation: true };
  const [prefs, setPrefs] = useS4(defaultPrefs);
  const [time, setTime] = useS4('18:30');
  const [permission, setPermission] = useS4('default');

  useE4(() => {
    try {
      const saved = JSON.parse(localStorage.getItem('paufit-notif-prefs') || 'null');
      if (saved) setPrefs({ ...defaultPrefs, ...saved });
      const savedTime = localStorage.getItem('paufit-notif-time');
      if (savedTime) setTime(savedTime);
      if (typeof Notification !== 'undefined') setPermission(Notification.permission);
    } catch {}
  }, []);

  function toggle(k) {
    setPrefs(p => {
      const next = { ...p, [k]: !p[k] };
      try { localStorage.setItem('paufit-notif-prefs', JSON.stringify(next)); } catch {}
      return next;
    });
  }
  function setTimeAndSave(v) {
    setTime(v);
    try { localStorage.setItem('paufit-notif-time', v); } catch {}
  }
  async function requestPermission() {
    if (typeof Notification === 'undefined') {
      nav.toast('Tu navegador no soporta notificaciones', { icon: '⚠️' });
      return;
    }
    if (Notification.permission === 'denied') {
      nav.toast('Permisos bloqueados. Cambia desde ajustes del navegador.', { icon: '🔒' });
      return;
    }
    try {
      const p = await Notification.requestPermission();
      setPermission(p);
      if (p === 'granted') {
        nav.toast('Notificaciones activadas 💗', { icon: '🔔' });
        // Mostrar notif de bienvenida
        new Notification('Pau Fit', {
          body: '¡Te avisaremos para que no rompas tu racha! 💗',
          icon: '/branding/logo.png',
          badge: '/branding/logo.png',
        });
      } else {
        nav.toast('Permiso denegado', { icon: '⚠️' });
      }
    } catch (e) {
      nav.toast('Error: ' + e.message, { icon: '⚠️' });
    }
  }

  return (
    <div style={{ paddingBottom: 110 }}>
      <div style={{
        padding: '12px 20px 4px',
      }}>
        <BackBtn onClick={() => nav.back()}/>
        <div className="pf-display" style={{ marginTop: 14, fontSize: 38, fontWeight: 800, color: T.text, letterSpacing: -1.4, lineHeight: 0.95 }}>Notificaciones</div>
        <div className="pf-eyebrow" style={{ color: T.muted, marginTop: 10 }}>Personaliza tus recordatorios</div>
      </div>

      {/* Activar/Estado del permiso */}
      <div style={{ padding: '20px 20px 0' }}>
        {permission === 'granted' ? (
          <div style={{
            padding: '14px 16px', borderRadius: 20,
            background: 'rgba(168,197,160,0.18)',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <span style={{ fontSize: 24 }}>✅</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: T.text }}>Notificaciones activadas</div>
              <div style={{ fontSize: 11, color: T.muted, marginTop: 2 }}>Recibirás recordatorios según tu configuración</div>
            </div>
          </div>
        ) : permission === 'denied' ? (
          <div style={{
            padding: '14px 16px', borderRadius: 20,
            background: 'rgba(214, 54, 54, 0.10)',
            border: '1.5px solid rgba(214, 54, 54, 0.25)',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <span style={{ fontSize: 24 }}>🔒</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: '#D63636' }}>Permisos bloqueados</div>
              <div style={{ fontSize: 11, color: T.muted, marginTop: 2 }}>Cambia desde ajustes del navegador/sistema</div>
            </div>
          </div>
        ) : (
          <button onClick={requestPermission} style={{
            width: '100%', padding: '16px 18px',
            border: 'none', borderRadius: 20, cursor: 'pointer',
            background: T.accent, color: '#fff',
            display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left',
            fontFamily: 'inherit', boxShadow: `0 6px 18px ${T.accent}40`,
          }}>
            <span style={{ fontSize: 24 }}>🔔</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700 }}>Activar notificaciones</div>
              <div style={{ fontSize: 11, opacity: 0.85, marginTop: 2 }}>Te avisaremos para que no rompas tu racha</div>
            </div>
            <span style={{ fontSize: 14, fontWeight: 700 }}>→</span>
          </button>
        )}
      </div>

      {/* Preview iOS-style */}
      <div style={{ padding: '28px 20px 10px' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5,  }}>Cómo se ven en tu pantalla</div>
      </div>
      <div style={{ margin: '0 20px', padding: '14px 16px', background: 'rgba(0,0,0,0.04)', borderRadius: 20, backdropFilter: 'blur(8px)' }}>
        {[
          { t: 'Pau Fit', emoji: '💗', title: 'Día 5 te espera', body: 'Pauu, llevas 12 días 🔥 No rompas la racha hoy.' , when: '18:30' },
          { t: 'Pau Fit', emoji: '🔥', title: 'Tu racha en peligro', body: 'Te quedan 2 horas para entrenar y mantener tus 12 días.' , when: '20:00' },
          { t: 'Pau Fit', emoji: '✨', title: 'María comentó tu testimonio', body: '"¡Qué pasada, también lo voy a probar!"' , when: 'ayer' },
        ].map((n, i) => (
          <div key={i} style={{
            background: 'rgba(255,255,255,0.7)', backdropFilter: 'blur(20px)',
            borderRadius: 20, padding: '10px 14px', marginBottom: i < 2 ? 8 : 0,
            border: '0.5px solid rgba(255,255,255,0.6)',
            display: 'flex', gap: 10, alignItems: 'flex-start',
          }}>
            <div style={{
              width: 32, height: 32, borderRadius: 7, flexShrink: 0,
              background: T.accent, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16,
            }}>{n.emoji}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
                <span style={{ fontFamily: 'Poppins', fontSize: 11, fontWeight: 700, color: '#2D2A26' }}>{n.t}</span>
                <span style={{ fontFamily: 'Poppins', fontSize: 10, color: 'rgba(45,42,38,0.55)' }}>{n.when}</span>
              </div>
              <div style={{ fontFamily: 'Poppins', fontSize: 12, fontWeight: 600, color: '#2D2A26', marginTop: 1 }}>{n.title}</div>
              <div style={{ fontFamily: 'Poppins', fontSize: 11, color: 'rgba(45,42,38,0.7)', marginTop: 1, lineHeight: 1.3 }}>{n.body}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Settings */}
      <div style={{ padding: '28px 20px 10px' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5,  }}>Qué quieres recibir</div>
      </div>
      <div style={{ margin: '0 20px', background: T.card, borderRadius: 20, overflow: 'hidden', border: T.border }}>
        {[
          { k: 'workout',   e: '💪🏻', t: 'Recordatorio de entreno', s: 'A tu hora elegida' },
          { k: 'streak',    e: '🔥', t: 'Racha en peligro',         s: 'Cuando te queden pocas horas' },
          { k: 'retos',     e: '✨', t: 'Nuevos retos y rutinas',   s: 'Cuando Pau publica' },
          { k: 'comunidad', e: '💬', t: 'Actividad en comunidad',   s: 'Comentarios, likes, mensajes' },
          { k: 'motivation',e: '💗', t: 'Mensaje motivacional',     s: 'Una frase de Pau por la mañana' },
        ].map((o, i, arr) => (
          <div key={o.k} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '14px 16px',
            borderBottom: i < arr.length-1 ? (T.dark ? '0.5px solid rgba(255,255,255,0.06)' : '0.5px solid rgba(0,0,0,0.05)') : 'none',
          }}>
            <span style={{ fontSize: 20 }}>{o.e}</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'Poppins', fontSize: 14, fontWeight: 500, color: T.text }}>{o.t}</div>
              <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, marginTop: 1 }}>{o.s}</div>
            </div>
            <button onClick={() => toggle(o.k)} style={{
              width: 51, height: 31, borderRadius: 999, border: 'none', cursor: 'pointer', padding: 0,
              background: prefs[o.k] ? T.accent : 'rgba(0,0,0,0.12)', position: 'relative',
              transition: 'background 200ms ease',
            }}>
              <div style={{
                position: 'absolute', top: 3, left: prefs[o.k] ? 21 : 3,
                width: 20, height: 20, borderRadius: 999, background: '#fff',
                transition: 'left 200ms ease', boxShadow: '0 1px 3px rgba(0,0,0,0.15)',
              }}/>
            </button>
          </div>
        ))}
      </div>

      {/* Time picker */}
      <div style={{ padding: '28px 20px 10px' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5,  }}>Hora preferida</div>
      </div>
      <div style={{
        margin: '0 20px', padding: '16px 20px',
        background: T.card, borderRadius: 20, border: T.border,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 14, color: T.text, fontWeight: 500 }}>Recordatorio diario</div>
        <input type="time" value={time} onChange={(e) => setTimeAndSave(e.target.value)} style={{
          padding: '8px 14px', borderRadius: 999, background: T.subtle, border: 'none',
          fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, color: T.text, letterSpacing: -0.2,
          outline: 'none',
        }}/>
      </div>

      {/* Test notif (cuando ya hay permiso) — mensaje cercano sin piropos */}
      {permission === 'granted' && (
        <div style={{ padding: '20px 20px 0' }}>
          <button onClick={() => {
            const cache = (typeof window !== 'undefined' && window.__pauCache) || {};
            const streakDays = (cache.stats && cache.stats.streak) || 0;
            const activeReto = cache.activeReto;
            const day = activeReto ? ((activeReto.current_day || 1)) : null;
            const body = (window.PauFriend
              ? (streakDays > 1 ? window.PauFriend.streak(streakDays)
                 : window.PauFriend.daily({ day: day || 1 }))
              : 'Pasa por la app un momento');
            new Notification('Pau Fit', {
              body,
              icon: '/branding/logo.png',
              badge: '/branding/logo.png',
            });
          }} style={{
            width: '100%', padding: '12px 16px',
            border: T.border, borderRadius: 20, cursor: 'pointer',
            background: T.card, color: T.text,
            fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
          }}>🔔 Enviar notificación de prueba</button>
        </div>
      )}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// ADMIN — solo para Pau (datos REALES desde Supabase)
// ═════════════════════════════════════════════════════════════
function AdminScreen({ theme, nav }) {
  const T = theme;
  const [tab, setTab] = useS4('testimonios');
  const [pending, setPending] = useS4([]);
  const [kpis, setKpis] = useS4({ users: '—', premium: '—', today: '—' });

  // Cargar KPIs reales
  useE4(() => {
    const sb = window.__PAU_SUPABASE;
    if (!sb) return;
    (async () => {
      try {
        const { count: totalUsers } = await sb.from('profiles').select('*', { count: 'exact', head: true });
        const { count: premium } = await sb.from('profiles').select('*', { count: 'exact', head: true }).eq('is_premium', true);
        setKpis({ users: String(totalUsers || 0), premium: String(premium || 0), today: '—' });
      } catch {}
    })();
  }, []);

  function decide(id, action) {
    setPending(p => p.filter(t => t.id !== id));
  }

  return (
    <div style={{ paddingBottom: 110 }}>
      <div style={{
        background: 'linear-gradient(160deg, #2D2A26, #3A332C)',
        padding: '12px 20px 24px',
        borderBottomLeftRadius: 32, borderBottomRightRadius: 32,
        color: '#fff',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <button onClick={() => nav.back()} style={{
            width: 36, height: 36, borderRadius: 999, border: 'none',
            background: 'rgba(255,255,255,0.12)', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>{Icon.back('#fff')}</button>
          <span style={{
            padding: '4px 10px', borderRadius: 6, background: '#C9956B', color: '#2D2A26',
            fontFamily: 'Poppins', fontSize: 9, fontWeight: 700, letterSpacing: 0.6,
          }}>👑 ADMIN · SOLO PAU</span>
        </div>
        <div style={{ marginTop: 14, fontFamily: 'Poppins', fontSize: 12, color: 'rgba(245,230,200,0.6)', fontWeight: 500, letterSpacing: 0.5,  }}>Panel de control</div>
        <div style={{ fontFamily: 'Poppins', fontSize: 26, fontWeight: 600, color: '#F5E6C8', marginTop: 4, letterSpacing: -0.5 }}>Pau Fit · Admin</div>

        {/* KPIs reales desde Supabase */}
        <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
          <KPI v={kpis.users} l="usuarias"/>
          <KPI v={kpis.premium} l="premium" gold/>
          <KPI v={kpis.today} l="hoy"/>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 8, padding: '18px 22px 4px', overflowX: 'auto' }} className="hide-scroll">
        {[
          { id: 'testimonios', l: `Pendientes · ${pending.length}` },
          { id: 'stats', l: 'Stats' },
          { id: 'retos', l: 'Retos' },
        ].map(s => (
          <Pill key={s.id} active={tab === s.id} onClick={() => setTab(s.id)} dark={T.dark} color={T.accent}>{s.l}</Pill>
        ))}
      </div>

      {tab === 'testimonios' && (
        <div style={{ padding: '14px 20px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
          {pending.length === 0 ? (
            <div style={{ padding: 30, textAlign: 'center', background: T.card, borderRadius: 20, border: T.border }}>
              <div style={{ fontSize: 32 }}>✓</div>
              <div style={{ fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, color: T.text, marginTop: 8 }}>Cola vacía</div>
              <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, marginTop: 2 }}>Bien hecho, Pau 💗</div>
            </div>
          ) : pending.map(t => (
            <div key={t.id} style={{
              padding: '14px 16px', background: T.card, borderRadius: 20, border: T.border,
              position: 'relative', overflow: 'hidden',
            }}>
              {t.suspect && (
                <div style={{
                  position: 'absolute', top: 0, right: 0, padding: '3px 10px 3px 12px',
                  background: '#D14C7A', color: '#fff',
                  fontFamily: 'Poppins', fontSize: 8, fontWeight: 700, letterSpacing: 0.6,
                  borderBottomLeftRadius: 10,
                }}>⚠ REVISAR</div>
              )}
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 999,
                  background: `linear-gradient(135deg, ${T.accent}, ${T.accent}99)`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: 'Poppins', fontSize: 12, fontWeight: 700, color: '#fff',
                }}>{t.initials}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: T.text }}>{t.user}</div>
                  <div style={{ fontFamily: 'Poppins', fontSize: 10, color: T.muted, marginTop: 1 }}>{t.target} · {t.date}</div>
                </div>
                <span style={{ fontFamily: 'Poppins', fontSize: 10, color: t.recommends ? '#5C7A56' : T.muted, fontWeight: 600 }}>
                  {t.recommends ? '💗 Recomienda' : '🤔 No recomienda'}
                </span>
              </div>
              <div style={{ marginTop: 10, fontFamily: 'Poppins', fontSize: 13, color: T.text, lineHeight: 1.45 }}>"{t.text}"</div>
              {t.flag && (
                <div style={{
                  marginTop: 8, padding: '6px 10px', background: 'rgba(209,76,122,0.1)', borderRadius: 8,
                  fontFamily: 'Poppins', fontSize: 11, color: '#D14C7A', fontWeight: 500,
                }}>⚠ {t.flag}</div>
              )}
              <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
                <button onClick={() => decide(t.id, 'reject')} style={{
                  flex: 1, padding: '10px', border: T.border, background: T.bg,
                  borderRadius: 10, cursor: 'pointer',
                  fontFamily: 'Poppins', fontSize: 12, fontWeight: 600, color: T.muted,
                }}>Rechazar</button>
                <button onClick={() => decide(t.id, 'approve')} style={{
                  flex: 1.6, padding: '10px', border: 'none', background: '#A8C5A0',
                  borderRadius: 10, cursor: 'pointer',
                  fontFamily: 'Poppins', fontSize: 12, fontWeight: 600, color: '#2D2A26',
                }}>✓ Aprobar</button>
              </div>
            </div>
          ))}
        </div>
      )}

      {tab === 'stats' && (
        <div style={{ padding: '14px 20px 0', display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5,  }}>Por reto · esta semana</div>
          {RETOS.map(r => (
            <div key={r.id} style={{
              padding: '14px 16px', background: T.card, borderRadius: 20, border: T.border,
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <div style={{
                width: 40, height: 40, borderRadius: 14, flexShrink: 0,
                background: r.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22,
              }}>{r.emoji}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: T.text }}>{r.title}</div>
                <div style={{ fontFamily: 'Poppins', fontSize: 10, color: T.muted, marginTop: 1 }}>
                  {(r.joined || 0).toLocaleString()} unidas · {(r.doing || 0).toLocaleString()} activas · {(r.completed_count || 0).toLocaleString()} completadas
                </div>
              </div>
              <div style={{
                width: 50, textAlign: 'right',
                fontFamily: 'Poppins', fontSize: 14, fontWeight: 700, color: r.color, letterSpacing: -0.3,
              }}>{r.joined ? Math.round((r.completed_count || 0) / r.joined * 100) : 0}%</div>
            </div>
          ))}
        </div>
      )}

      {tab === 'retos' && (
        <div style={{ padding: '14px 20px 0' }}>
          <button onClick={() => {
            const url = (window.location.origin || 'https://app.paufit.co') + '/admin/retos';
            if (window.PauNative?.isNativeApp) window.PauNative.openExternal(url);
            else if (window.top && window.top !== window) window.top.location.href = url;
            else window.location.href = url;
          }} style={{
            width: '100%', padding: '14px', border: `1.5px dashed ${T.muted}80`,
            background: 'transparent', borderRadius: 20, cursor: 'pointer',
            fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: T.text,
          }}>＋ Crear nuevo reto · panel admin →</button>
          <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
            {RETOS.map(r => (
              <div key={r.id} style={{
                padding: '12px 14px', background: T.card, borderRadius: 20, border: T.border,
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <span style={{ fontSize: 26 }}>{r.emoji}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: T.text }}>{r.title}</div>
                  <div style={{ fontFamily: 'Poppins', fontSize: 10, color: T.muted }}>{r.days} días · {r.tag}</div>
                </div>
                <button onClick={() => {
                  const url = (window.location.origin || 'https://app.paufit.co') + '/admin/retos/' + r.id;
                  if (window.PauNative?.isNativeApp) window.PauNative.openExternal(url);
                  else if (window.top && window.top !== window) window.top.location.href = url;
                  else window.location.href = url;
                }} style={{
                  padding: '6px 12px', border: T.border, background: T.bg,
                  borderRadius: 999, cursor: 'pointer',
                  fontFamily: 'Poppins', fontSize: 11, fontWeight: 600, color: T.text,
                }}>Editar</button>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function KPI({ v, l, gold }) {
  return (
    <div style={{
      padding: '12px',
      background: 'rgba(255,255,255,0.06)', borderRadius: 14,
      border: `0.5px solid ${gold ? 'rgba(201,149,107,0.25)' : 'rgba(245,230,200,0.1)'}`,
    }}>
      <div style={{ fontFamily: 'Poppins', fontSize: 20, fontWeight: 700, color: gold ? '#C9956B' : '#F5E6C8', letterSpacing: -0.4 }}>{v}</div>
      <div style={{ fontFamily: 'Poppins', fontSize: 9, color: 'rgba(245,230,200,0.55)', marginTop: 2, fontWeight: 500, letterSpacing: 0.5,  }}>{l}</div>
    </div>
  );
}

Object.assign(window, { LoginScreen, OnboardingScreen, ChatScreen, NotificacionesScreen, AdminScreen, AjustesScreen, EditarPerfilScreen });

// ═════════════════════════════════════════════════════════════
// EDITAR PERFIL
// ═════════════════════════════════════════════════════════════
function EditarPerfilScreen({ theme, nav }) {
  const T = theme;
  // Cargar datos REALES del cache (vienen de Supabase profiles)
  const cache = (typeof window !== 'undefined' && window.__pauCache) || {};
  const profile = cache.profile || {};

  const [name, setName] = useS4(profile.full_name || '');
  const [user, setUser] = useS4(profile.username || '');
  const [bio, setBio] = useS4(profile.bio || '');
  const [email] = useS4(profile.email || '');
  const [phone, setPhone] = useS4(profile.phone || '');
  const [birth, setBirth] = useS4(profile.birth_date || '');
  const [gender, setGender] = useS4(profile.gender || 'mujer');
  const [obj, setObj] = useS4(profile.goal || 'tonificar');
  const [days, setDays] = useS4(profile.target_days_per_week || 5);
  const [height, setHeight] = useS4(profile.height_cm || '');
  const [weight, setWeight] = useS4(profile.weight_kg || '');
  const [isPublic, setIsPublic] = useS4(profile.is_public !== false); // default true
  const [avatarUrl, setAvatarUrl] = useS4(profile.avatar_url || null);
  const [uploadingAvatar, setUploadingAvatar] = useS4(false);
  const [saving, setSaving] = useS4(false);
  const avatarFileInputRef = React.useRef(null);

  async function handleAvatarFile(e) {
    const file = e.target.files && e.target.files[0];
    e.target.value = ''; // permitir reseleccionar mismo archivo
    if (!file) return;
    const sb = window.__PAU_SUPABASE;
    if (!sb) { nav.toast('Sin conexión', { icon: '⚠️' }); return; }
    if (file.size > 5 * 1024 * 1024) {
      nav.toast('Foto muy grande (max 5MB)', { icon: '⚠️' });
      return;
    }
    setUploadingAvatar(true);
    try {
      const { data: { user: u } } = await sb.auth.getUser();
      if (!u) { nav.toast('Inicia sesión', { icon: '⚠️' }); setUploadingAvatar(false); return; }
      const ext = (file.name.split('.').pop() || 'jpg').toLowerCase();
      // Path estable por usuario (sobreescribe la anterior)
      const path = `${u.id}/avatar.${ext}`;
      const { error: upErr } = await sb.storage.from('avatars').upload(path, file, {
        cacheControl: '3600', upsert: true, contentType: file.type,
      });
      if (upErr) {
        // Si el bucket "avatars" no existe, intentamos con "progress-photos" como fallback temporal
        if (/bucket/i.test(upErr.message)) {
          const fallbackPath = `${u.id}/avatar-${Date.now()}.${ext}`;
          const { error: fbErr } = await sb.storage.from('progress-photos').upload(fallbackPath, file, {
            cacheControl: '3600', upsert: false, contentType: file.type,
          });
          if (fbErr) throw fbErr;
          const { data: urlData } = sb.storage.from('progress-photos').getPublicUrl(fallbackPath);
          const newUrl = urlData?.publicUrl;
          setAvatarUrl(newUrl);
          await sb.from('profiles').update({ avatar_url: newUrl }).eq('id', u.id);
          window.__pauCache.profile = { ...window.__pauCache.profile, avatar_url: newUrl };
          window.dispatchEvent(new CustomEvent('pau:cache-updated'));
          nav.toast('Foto actualizada 💗', { icon: '📸' });
          setUploadingAvatar(false);
          return;
        }
        throw upErr;
      }
      const { data: urlData } = sb.storage.from('avatars').getPublicUrl(path);
      const newUrl = (urlData?.publicUrl || '') + (urlData?.publicUrl ? `?v=${Date.now()}` : '');
      setAvatarUrl(newUrl);
      await sb.from('profiles').update({ avatar_url: newUrl }).eq('id', u.id);
      window.__pauCache.profile = { ...window.__pauCache.profile, avatar_url: newUrl };
      window.dispatchEvent(new CustomEvent('pau:cache-updated'));
      nav.toast('Foto actualizada 💗', { icon: '📸' });
    } catch (err) {
      console.warn('[avatar-upload]', err);
      nav.toast('Error: ' + (err?.message || 'no se pudo subir la foto'), { icon: '⚠️' });
    } finally {
      setUploadingAvatar(false);
    }
  }

  async function save() {
    const sb = window.__PAU_SUPABASE;
    if (!sb) { nav.toast('Sin conexión', { icon: '⚠️' }); return; }
    setSaving(true);
    try {
      const { data: { user: u } } = await sb.auth.getUser();
      if (!u) { nav.toast('Inicia sesión', { icon: '⚠️' }); setSaving(false); return; }

      // USERNAME: límite 2 cambios cada 14 días + único en DB.
      const currentUsername = (profile.username || '').toLowerCase();
      const newUsername = (user || '').toLowerCase();
      let usernameChanges = profile.username_changes;
      try {
        if (typeof usernameChanges === 'string') usernameChanges = JSON.parse(usernameChanges);
      } catch {}
      if (!Array.isArray(usernameChanges)) usernameChanges = [];
      if (newUsername && newUsername !== currentUsername) {
        // Contar cambios en los últimos 14 días
        const cutoff = Date.now() - 14 * 86400000;
        const recentChanges = usernameChanges.filter(t => {
          const ms = new Date(t).getTime();
          return ms > cutoff;
        });
        if (recentChanges.length >= 2) {
          const oldestRecent = Math.min(...recentChanges.map(t => new Date(t).getTime()));
          const nextChangeDate = new Date(oldestRecent + 14 * 86400000);
          nav.toast(`Solo puedes cambiar tu nombre de usuario 2 veces cada 14 días. Próximo cambio: ${nextChangeDate.toLocaleDateString('es', { day: 'numeric', month: 'short' })}`, { icon: '⏰' });
          setSaving(false);
          return;
        }
        // Verificar que el username no esté ya en uso (unique constraint hace lo mismo, pero damos error legible)
        const { data: existing } = await sb.from('profiles')
          .select('id').eq('username', newUsername).neq('id', u.id).maybeSingle();
        if (existing) {
          nav.toast('Ese nombre de usuario ya está en uso. Prueba otro.', { icon: '🚫' });
          setSaving(false);
          return;
        }
        // Añadir al historial
        usernameChanges = [...usernameChanges, new Date().toISOString()];
        // Limitar historial a últimos 30 cambios (no crecer infinito)
        if (usernameChanges.length > 30) usernameChanges = usernameChanges.slice(-30);
      }

      const updates = {
        full_name: name || null,
        username: user || null,
        bio: bio || null,
        phone: phone || null,
        birth_date: birth || null,
        gender: gender || null,
        goal: obj || null,
        target_days_per_week: days || null,
        height_cm: height ? Number(height) : null,
        weight_kg: weight ? Number(weight) : null,
        is_public: isPublic,
        avatar_url: avatarUrl || null,
        username_changes: usernameChanges,
      };
      const { error } = await sb.from('profiles').update(updates).eq('id', u.id);
      if (error) {
        // 23505 = unique violation en Postgres
        if (error.code === '23505' || /duplicate|unique/i.test(error.message)) {
          nav.toast('Ese nombre de usuario ya está en uso.', { icon: '🚫' });
        } else {
          nav.toast('Error: ' + error.message, { icon: '⚠️' });
        }
        setSaving(false); return;
      }
      // refrescar cache
      window.__pauCache.profile = { ...profile, ...updates, email: u.email };
      window.dispatchEvent(new CustomEvent('pau:cache-updated'));
      nav.toast('Perfil actualizado 💗', { icon: '✓' });
      setTimeout(() => nav.back(), 600);
    } catch (e) {
      nav.toast('Error: ' + (e.message || e), { icon: '⚠️' });
      setSaving(false);
    }
  }

  return (
    <div style={{ paddingBottom: 110 }}>
      <div style={{
        background: T.subtle, padding: '12px 20px 30px',
        borderBottomLeftRadius: 32, borderBottomRightRadius: 32,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <BackBtn onClick={() => nav.back()}/>
          <button onClick={save} style={{
            padding: '8px 16px', border: 'none', borderRadius: 999, cursor: 'pointer',
            background: T.accent, color: '#fff',
            fontFamily: 'Poppins', fontSize: 12, fontWeight: 600,
          }}>Guardar</button>
        </div>

        {/* Avatar */}
        <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10 }}>
          <div style={{ position: 'relative' }}>
            <button
              onClick={() => avatarFileInputRef.current?.click()}
              disabled={uploadingAvatar}
              style={{
                width: 96, height: 96, borderRadius: 999, border: 'none',
                background: avatarUrl ? '#fff' : `linear-gradient(135deg, ${T.accent}, ${T.accent}99)`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: 'Poppins', fontSize: 32, fontWeight: 600, color: '#fff', letterSpacing: -0.5,
                boxShadow: `0 8px 24px ${T.accent}40`,
                cursor: uploadingAvatar ? 'wait' : 'pointer',
                overflow: 'hidden', padding: 0,
              }}>
              {avatarUrl
                ? <img src={avatarUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                : (name?.slice(0, 2).toUpperCase() || <img src="/branding/logo.png" alt="" style={{ width: 48, height: 48, objectFit: 'contain' }}/>)
              }
            </button>
            <button
              onClick={() => avatarFileInputRef.current?.click()}
              disabled={uploadingAvatar}
              style={{
                position: 'absolute', bottom: -2, right: -2,
                width: 32, height: 32, borderRadius: 999, border: `2px solid ${T.subtle}`,
                background: T.text, color: T.bg,
                cursor: uploadingAvatar ? 'wait' : 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14,
              }}>{uploadingAvatar ? '⏳' : '📷'}</button>
            <input
              ref={avatarFileInputRef}
              type="file"
              accept="image/*"
              style={{ display: 'none' }}
              onChange={handleAvatarFile}
            />
          </div>
          <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 500 }}>
            {uploadingAvatar ? 'Subiendo…' : 'Toca para cambiar foto'}
          </div>
        </div>
      </div>

      {/* Public info */}
      <Section title="Información pública" T={T}>
        <Field label="Nombre" T={T}>
          <input value={name} onChange={(e) => setName(e.target.value)} style={inputStyle(T)}/>
        </Field>
        <Field label="@usuario" T={T}>
          <input value={user} onChange={(e) => setUser(e.target.value.toLowerCase().replace(/\s/g, ''))} style={inputStyle(T)}/>
          {(() => {
            let changes = profile.username_changes;
            try { if (typeof changes === 'string') changes = JSON.parse(changes); } catch {}
            if (!Array.isArray(changes)) changes = [];
            const cutoff = Date.now() - 14 * 86400000;
            const recent = changes.filter(t => new Date(t).getTime() > cutoff);
            const left = Math.max(0, 2 - recent.length);
            return (
              <div style={{ fontFamily: 'Poppins', fontSize: 10, color: T.muted, marginTop: 4, lineHeight: 1.35 }}>
                Único en la app. Puedes cambiarlo {left} {left === 1 ? 'vez' : 'veces'} más en los próximos 14 días.
              </div>
            );
          })()}
        </Field>
        <Field label="Bio" T={T}>
          <textarea value={bio} onChange={(e) => setBio(e.target.value)} maxLength={120}
            style={{ ...inputStyle(T), minHeight: 60, resize: 'none' }}/>
          <div style={{ fontFamily: 'Poppins', fontSize: 10, color: T.muted, textAlign: 'right', marginTop: 4 }}>{bio.length}/120</div>
        </Field>
      </Section>

      {/* Cuenta */}
      <Section title="Cuenta" T={T}>
        <Field label="Email" T={T}>
          <input value={email} disabled style={{ ...inputStyle(T), opacity: 0.55, cursor: 'not-allowed' }}/>
          <div style={{ fontFamily: 'Poppins', fontSize: 10, color: T.muted, marginTop: 4 }}>El email no se puede cambiar</div>
        </Field>
        <Field label="Teléfono (opcional)" T={T}>
          <input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+34 600 000 000" style={inputStyle(T)}/>
        </Field>
        <Field label="Fecha de nacimiento" T={T}>
          <input type="date" value={birth} onChange={(e) => setBirth(e.target.value)} style={inputStyle(T)}/>
        </Field>
      </Section>

      {/* Personal */}
      <Section title="Datos personales" T={T}>
        <Field label="Género" T={T}>
          <div style={{ display: 'flex', gap: 6 }}>
            {[
              { v: 'mujer', l: 'Mujer' },
              { v: 'hombre', l: 'Hombre' },
              { v: 'otro', l: 'Otro' },
              { v: 'noContestar', l: 'Prefiero no decirlo' },
            ].map(o => (
              <button key={o.v} onClick={() => setGender(o.v)} style={{
                flex: 1, padding: '10px 4px', cursor: 'pointer',
                border: gender === o.v ? `1.5px solid ${T.accent}` : T.border,
                background: gender === o.v ? `${T.accent}10` : T.card,
                borderRadius: 10,
                fontFamily: 'Poppins', fontSize: 10, fontWeight: 600, color: gender === o.v ? T.accent : T.text,
              }}>{o.l}</button>
            ))}
          </div>
        </Field>
        <Field label="Altura" T={T}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 6,
            padding: '0 12px', background: T.card, border: T.border, borderRadius: 14,
          }}>
            <input type="number" value={height} onChange={(e) => setHeight(e.target.value)} style={{
              flex: 1, padding: '12px 0', border: 'none', background: 'transparent',
              fontFamily: 'Poppins', fontSize: 14, color: T.text, outline: 'none',
            }} placeholder="—"/>
            <span style={{ fontFamily: 'Poppins', fontSize: 13, color: T.muted, fontWeight: 500 }}>cm</span>
          </div>
        </Field>
        <Field label="Peso" T={T}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 6,
            padding: '0 12px', background: T.card, border: T.border, borderRadius: 14,
          }}>
            <input type="number" step="0.1" value={weight} onChange={(e) => setWeight(e.target.value)} style={{
              flex: 1, padding: '12px 0', border: 'none', background: 'transparent',
              fontFamily: 'Poppins', fontSize: 14, color: T.text, outline: 'none',
            }} placeholder="—"/>
            <span style={{ fontFamily: 'Poppins', fontSize: 13, color: T.muted, fontWeight: 500 }}>kg</span>
          </div>
        </Field>
      </Section>

      {/* PRIVACIDAD */}
      <Section title="Privacidad" T={T}>
        <div style={{
          padding: '14px 16px', background: T.card, borderRadius: 14, border: T.border,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <span style={{ fontSize: 22 }}>{isPublic ? '👥' : '🔒'}</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'Poppins', fontSize: 13, fontWeight: 700, color: T.text }}>
              {isPublic ? 'Cuenta pública' : 'Cuenta privada'}
            </div>
            <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, marginTop: 2, lineHeight: 1.4 }}>
              {isPublic
                ? 'Tu nombre aparece en el Ranking público'
                : 'Tu nombre aparece como "Anónima" en el Ranking'}
            </div>
          </div>
          <button onClick={() => setIsPublic(!isPublic)} style={{
            width: 50, height: 28, borderRadius: 999, border: 'none', cursor: 'pointer',
            background: isPublic ? T.accent : 'rgba(0,0,0,0.15)', position: 'relative',
            transition: 'background 200ms ease',
          }}>
            <div style={{
              position: 'absolute', top: 3, left: isPublic ? 25 : 3,
              width: 22, height: 22, borderRadius: 999, background: '#fff',
              transition: 'left 200ms ease', boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
            }}/>
          </button>
        </div>
      </Section>

      {/* REHACER TEST INICIAL */}
      <Section title="Recomendaciones" T={T}>
        <button onClick={() => { nav.go('onboarding'); }} style={{
          width: '100%', padding: '14px 16px',
          background: T.card, border: T.border, borderRadius: 14, cursor: 'pointer',
          display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left',
          fontFamily: 'inherit',
        }}>
          <span style={{ fontSize: 22 }}>🎯</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'Poppins', fontSize: 13, fontWeight: 700, color: T.text }}>
              Rehacer test inicial
            </div>
            <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, marginTop: 2 }}>
              Redefine tus objetivos y obtén nueva recomendación
            </div>
          </div>
          {Icon.chevR(T.muted, 8)}
        </button>
      </Section>

      {/* Objetivo */}
      <Section title="Tu objetivo de entreno" T={T}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {[
            { v: 'quemar', e: '🔥', t: 'Quemar grasa' },
            { v: 'tonificar', e: '✨', t: 'Tonificar' },
            { v: 'musculo', e: '💪🏻', t: 'Ganar músculo' },
            { v: 'bienestar', e: '🧘🏼‍♀️', t: 'Sentirme bien' },
          ].map(o => {
            const sel = obj === o.v;
            return (
              <button key={o.v} onClick={() => setObj(o.v)} style={{
                padding: '14px 12px',
                border: sel ? `1.5px solid ${T.accent}` : T.border,
                background: sel ? `${T.accent}10` : T.card,
                borderRadius: 20, cursor: 'pointer', textAlign: 'left',
                display: 'flex', alignItems: 'center', gap: 10,
              }}>
                <span style={{ fontSize: 22 }}>{o.e}</span>
                <span style={{ fontFamily: 'Poppins', fontSize: 12, fontWeight: 600, color: sel ? T.accent : T.text }}>{o.t}</span>
              </button>
            );
          })}
        </div>
        <Field label="Días por semana" T={T} top={14}>
          <div style={{ display: 'flex', gap: 6 }}>
            {[3, 4, 5, 6, 7].map(d => (
              <button key={d} onClick={() => setDays(d)} style={{
                flex: 1, padding: '10px 4px', cursor: 'pointer',
                border: days === d ? `1.5px solid ${T.accent}` : T.border,
                background: days === d ? `${T.accent}10` : T.card,
                borderRadius: 10,
                fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: days === d ? T.accent : T.text,
              }}>{d}</button>
            ))}
          </div>
        </Field>
      </Section>

      {/* Danger zone */}
      <div style={{ padding: '28px 20px 10px' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5,  }}>Zona peligrosa</div>
      </div>
      <div style={{ margin: '0 20px', background: T.card, borderRadius: 20, overflow: 'hidden', border: T.border }}>
        <button onClick={async () => {
          const sb = window.__PAU_SUPABASE;
          if (!sb) { nav.toast('Sin conexión', { icon: '⚠️' }); return; }
          nav.toast('Preparando tu archivo…', { icon: '📦' });
          try {
            const { data: { user: u } } = await sb.auth.getUser();
            if (!u) { nav.toast('Inicia sesión', { icon: '🔒' }); return; }
            // Recolectar TODOS los datos del usuario
            const [profileRes, retosRes, plansRes, dayCompRes, mealsRes, measRes] = await Promise.all([
              sb.from('profiles').select('*').eq('id', u.id).maybeSingle(),
              sb.from('user_retos').select('*').eq('user_id', u.id),
              sb.from('user_planes').select('*').eq('user_id', u.id),
              sb.from('day_completions').select('*').eq('user_id', u.id),
              sb.from('meal_logs').select('*').eq('user_id', u.id),
              sb.from('measurements').select('*').eq('user_id', u.id),
            ]);
            const exportData = {
              exportedAt: new Date().toISOString(),
              user: { id: u.id, email: u.email },
              profile: profileRes.data || null,
              userRetos: retosRes.data || [],
              userPlanes: plansRes.data || [],
              dayCompletions: dayCompRes.data || [],
              mealLogs: mealsRes.data || [],
              measurements: measRes.data || [],
            };
            const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `paufit-mis-datos-${new Date().toISOString().slice(0,10)}.json`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            setTimeout(() => URL.revokeObjectURL(url), 2000);
            nav.toast('Archivo descargado 💗', { icon: '✓' });
          } catch (e) {
            nav.toast('Error: ' + (e?.message || e), { icon: '⚠️' });
          }
        }} style={{
          width: '100%', display: 'flex', alignItems: 'center', gap: 12,
          padding: '14px 16px', border: 'none', background: 'transparent', cursor: 'pointer', textAlign: 'left',
          borderBottom: T.dark ? '0.5px solid rgba(255,255,255,0.06)' : '0.5px solid rgba(0,0,0,0.05)',
        }}>
          <span style={{ fontSize: 18 }}>📦</span>
          <span style={{ flex: 1, fontFamily: 'Poppins', fontSize: 14, fontWeight: 500, color: T.text }}>Exportar mis datos</span>
          {Icon.chevR(T.muted, 8)}
        </button>
        <button onClick={async () => {
          const confirm1 = window.confirm('¿Eliminar tu cuenta?\n\nSe borrarán TUS retos, fotos, medidas, comidas y todos tus datos PARA SIEMPRE.\n\nEsta acción NO se puede deshacer.');
          if (!confirm1) return;
          const confirm2 = window.prompt('Escribe "ELIMINAR" para confirmar:');
          if (confirm2 !== 'ELIMINAR') { nav.toast('Cancelado', { icon: '✓' }); return; }
          const sb = window.__PAU_SUPABASE;
          if (!sb) { nav.toast('Sin conexión', { icon: '⚠️' }); return; }
          try {
            nav.toast('Eliminando tus datos…', { icon: '⏳' });
            const { data: { user: u } } = await sb.auth.getUser();
            if (!u) { nav.toast('Inicia sesión', { icon: '🔒' }); return; }
            // Borrar datos de las tablas (el order respeta FKs)
            await sb.from('day_completions').delete().eq('user_id', u.id);
            await sb.from('meal_logs').delete().eq('user_id', u.id);
            await sb.from('measurements').delete().eq('user_id', u.id);
            await sb.from('user_retos').delete().eq('user_id', u.id);
            await sb.from('user_planes').delete().eq('user_id', u.id);
            // Borrar fotos de progreso
            try {
              const { data: photos } = await sb.storage.from('progress-photos').list(u.id);
              if (photos?.length) {
                await sb.storage.from('progress-photos').remove(photos.map(p => `${u.id}/${p.name}`));
              }
            } catch {}
            // Marcar profile como eliminado (para que un trigger lo limpie luego, o borrarlo si las RLS lo permiten)
            await sb.from('profiles').delete().eq('id', u.id);
            // Logout
            await sb.auth.signOut();
            nav.toast('Cuenta eliminada 💗 Hasta pronto', { icon: '👋' });
            setTimeout(() => window.location.reload(), 1500);
          } catch (e) {
            nav.toast('Error: ' + (e?.message || e) + '. Escribe a hello@paufit.co.', { icon: '⚠️' });
          }
        }} style={{
          width: '100%', display: 'flex', alignItems: 'center', gap: 12,
          padding: '14px 16px', border: 'none', background: 'transparent', cursor: 'pointer', textAlign: 'left',
        }}>
          <span style={{ fontSize: 18 }}>🗑️</span>
          <span style={{ flex: 1, fontFamily: 'Poppins', fontSize: 14, fontWeight: 500, color: '#D14C7A' }}>Eliminar cuenta</span>
          {Icon.chevR(T.muted, 8)}
        </button>
      </div>
    </div>
  );
}

function Section({ title, T, children }) {
  return (
    <>
      <div style={{ padding: '24px 22px 12px' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5,  }}>{title}</div>
      </div>
      <div style={{ margin: '0 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {children}
      </div>
    </>
  );
}

function Field({ label, T, children, top = 0 }) {
  return (
    <div style={{ marginTop: top }}>
      <label style={{ fontFamily: 'Poppins', fontSize: 11, fontWeight: 600, color: T.muted, letterSpacing: 0.3, display: 'block', marginBottom: 6 }}>{label}</label>
      {children}
    </div>
  );
}

function inputStyle(T) {
  return {
    width: '100%', padding: '12px 14px',
    border: T.border, borderRadius: 14, background: T.card,
    fontFamily: 'Poppins', fontSize: 14, color: T.text, outline: 'none',
    boxSizing: 'border-box',
  };
}

// ═════════════════════════════════════════════════════════════
// AJUSTES — palette picker (premium feature), idioma, unidades
// ═════════════════════════════════════════════════════════════
// Switch iOS pixel-perfect — usado en toda la pantalla de ajustes
function IOSSwitch({ on, onChange, accent }) {
  return (
    <button onClick={onChange} aria-pressed={on} style={{
      width: 51, height: 31, borderRadius: 999,
      border: 'none', outline: 'none', cursor: 'pointer', padding: 0,
      background: on ? accent : 'rgba(120,120,128,0.16)',
      position: 'relative', flexShrink: 0,
      transition: 'background-color 280ms cubic-bezier(.4,0,.2,1)',
      WebkitTapHighlightColor: 'transparent',
    }}>
      <div style={{
        position: 'absolute', top: 2, left: on ? 22 : 2,
        width: 27, height: 27, borderRadius: 999, background: '#fff',
        transition: 'left 280ms cubic-bezier(.4,0,.2,1), transform 280ms cubic-bezier(.4,0,.2,1)',
        boxShadow: '0 3px 1px rgba(0,0,0,0.06), 0 3px 8px rgba(0,0,0,0.15), 0 0 0 0.5px rgba(0,0,0,0.04)',
      }}/>
    </button>
  );
}

function AjustesScreen({ theme, nav, tweaks, setTweak }) {
  const T = theme;
  const isPremium = tweaks.isPremium;

  function pickPalette(p) {
    if (!p.free && !isPremium) {
      nav.go('paywall');
      return;
    }
    setTweak('palette', p.id);
    nav.toast(`Tema ${p.name} activado 💗`, { icon: '🎨' });
  }

  return (
    <div style={{ paddingBottom: 110 }}>
      <div style={{ padding: '12px 20px 4px' }}>
        <BackBtn onClick={() => nav.back()}/>
        <div className="pf-display" style={{ marginTop: 14, fontSize: 38, fontWeight: 800, color: T.text, letterSpacing: -1.4, lineHeight: 0.95 }}>
          Ajustes
        </div>
      </div>

      {/* APARIENCIA */}
      <div style={{ padding: '28px 20px 10px' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 700, letterSpacing: 0.6,  }}>
          Apariencia
        </div>
      </div>

      <div style={{ padding: '0 20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {PALETTE_META.map(p => {
          const sel = tweaks.palette === p.id;
          const locked = !p.free && !isPremium;
          return (
            <button key={p.id} onClick={() => pickPalette(p)} style={{
              padding: 14, cursor: 'pointer', textAlign: 'left',
              background: T.card,
              border: sel ? `1.5px solid ${T.accent}` : T.border,
              borderRadius: 20, position: 'relative', overflow: 'hidden',
              opacity: locked ? 0.7 : 1,
              transition: 'all 200ms ease',
            }}>
              {/* swatches strip */}
              <div style={{ display: 'flex', gap: 4, marginBottom: 10 }}>
                {p.swatches.map((c, i) => (
                  <div key={i} style={{
                    flex: 1, height: 28, borderRadius: 8, background: c,
                    border: c === '#FFFFFF' || c.startsWith('#FD') || c.startsWith('#FC') || c.startsWith('#F0') ? `0.5px solid ${T.muted}30` : 'none',
                  }}/>
                ))}
              </div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div>
                  <div style={{ fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: T.text }}>{p.name}</div>
                  <div style={{ fontFamily: 'Poppins', fontSize: 10, color: T.muted, marginTop: 1 }}>{p.hint}</div>
                </div>
                {sel ? (
                  <div style={{
                    width: 24, height: 24, borderRadius: 999, background: T.accent,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>{Icon.check('#fff', 14)}</div>
                ) : locked ? (
                  <div style={{
                    width: 24, height: 24, borderRadius: 999, background: '#2D2A26',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>{Icon.lock('#F5E6C8', 11)}</div>
                ) : null}
              </div>
            </button>
          );
        })}
      </div>

      {/* Modo oscuro */}
      <div style={{ height: 28 }}/>
      <div style={{ margin: '0 20px', background: T.card, borderRadius: 20, overflow: 'hidden', border: T.border }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
          borderBottom: T.dark ? '0.5px solid rgba(255,255,255,0.06)' : '0.5px solid rgba(0,0,0,0.05)',
        }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'Poppins', fontSize: 15, fontWeight: 500, color: T.text }}>Modo oscuro</div>
          </div>
          <IOSSwitch on={tweaks.darkMode} onChange={() => setTweak('darkMode', !tweaks.darkMode)} accent={T.accent}/>
        </div>
        {/* FLEX WEEKEND — racha no rompe en fines de semana */}
        {(() => {
          const [flex, setFlex] = useS4(false);
          useE4(() => {
            try { setFlex(localStorage.getItem('paufit-flex-weekend') === '1'); } catch {}
          }, []);
          function toggle() {
            const next = !flex;
            setFlex(next);
            try { localStorage.setItem('paufit-flex-weekend', next ? '1' : '0'); } catch {}
            nav.toast(next ? 'Fines de semana flexibles 🌴' : 'Racha estricta activa 🔥', { icon: '✓' });
          }
          return (
            <div style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
            }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'Poppins', fontSize: 15, fontWeight: 500, color: T.text }}>Fines de semana flexibles</div>
              </div>
              <IOSSwitch on={flex} onChange={toggle} accent={T.accent}/>
            </div>
          );
        })()}
      </div>

      {/* COMIDAS — info nutricional */}
      <div style={{ padding: '28px 20px 10px' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 700, letterSpacing: 0.6,  }}>Nutrición visible</div>
      </div>
      <div style={{ margin: '0 20px', background: T.card, borderRadius: 20, overflow: 'hidden', border: T.border }}>
        {(() => {
          const DEFAULTS = { kcal: true, protein: true, carbs: true, fat: true };
          const [prefs, setPrefs] = useS4(DEFAULTS);
          useE4(() => {
            try {
              const raw = localStorage.getItem('paufit-macros-prefs');
              if (raw) {
                setPrefs({ ...DEFAULTS, ...JSON.parse(raw) });
                return;
              }
              // Migrar legacy
              const legacy = localStorage.getItem('paufit-show-macros');
              if (legacy !== null) {
                const all = legacy === '1';
                setPrefs({ kcal: all, protein: all, carbs: all, fat: all });
              }
            } catch {}
          }, []);
          function toggleKey(k) {
            const next = { ...prefs, [k]: !prefs[k] };
            setPrefs(next);
            try { localStorage.setItem('paufit-macros-prefs', JSON.stringify(next)); } catch {}
            window.dispatchEvent(new CustomEvent('pau:settings-updated'));
          }
          const items = [
            { k: 'kcal', e: '🔥', t: 'Calorías' },
            { k: 'protein', e: '💪', t: 'Proteína' },
            { k: 'carbs', e: '🌾', t: 'Carbs' },
            { k: 'fat', e: '🥑', t: 'Grasas' },
          ];
          return items.map((it, idx) => (
            <div key={it.k} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
              borderTop: idx === 0 ? 'none' : (T.dark ? '0.5px solid rgba(255,255,255,0.06)' : '0.5px solid rgba(0,0,0,0.05)'),
            }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'Poppins', fontSize: 15, fontWeight: 500, color: T.text }}>{it.t}</div>
              </div>
              <IOSSwitch on={prefs[it.k]} onChange={() => toggleKey(it.k)} accent={T.accent}/>
            </div>
          ));
        })()}
      </div>

      {/* Cuenta */}
      <div style={{ padding: '28px 20px 10px' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5,  }}>Cuenta</div>
      </div>
      <div style={{ margin: '0 20px', background: T.card, borderRadius: 20, overflow: 'hidden', border: T.border }}>
        {(() => {
          const cache = (typeof window !== 'undefined' && window.__pauCache) || {};
          const profile = cache.profile || {};
          const displayName = profile.full_name || profile.username || 'Tu perfil';
          const email = profile.email || '';
          // Leer valores reales de localStorage para mostrar detalle
          let unidadW = 'kg', unidadL = 'cm', idioma = 'Español';
          try {
            if (localStorage.getItem('paufit-unit-weight') === 'lb') unidadW = 'lb';
            if (localStorage.getItem('paufit-unit-length') === 'in') unidadL = 'in';
            const lang = localStorage.getItem('paufit-lang');
            if (lang === 'en') idioma = 'English';
            else if (lang === 'pt') idioma = 'Português';
          } catch {}
          return [
            { e: '✏️', t: 'Editar perfil', detail: email || displayName, kind: 'editarPerfil' },
            { e: '🔒', t: 'Privacidad', kind: 'privacidad' },
            { e: '⚖️', t: 'Unidades', detail: `${unidadW} · ${unidadL}`, kind: 'unidades' },
            { e: '🌐', t: 'Idioma', detail: idioma, kind: 'idioma' },
          ];
        })().map((o, i, arr) => (
          <div key={i} onClick={() => {
            if (o.kind === 'editarPerfil') return nav.go('editarPerfil');
            if (o.kind === 'privacidad') {
              const url = 'https://paufit.co/privacy';
              if (window.PauNative && window.PauNative.isNativeApp) window.PauNative.openExternal(url);
              else window.open(url, '_blank', 'noopener');
              return;
            }
            if (o.kind === 'unidades') {
              // Action sheet de unidades
              if (nav.openModal) nav.openModal(
                <UnidadesSheet T={T} onClose={() => nav.closeModal()} onSave={(w, l) => {
                  try {
                    localStorage.setItem('paufit-unit-weight', w);
                    localStorage.setItem('paufit-unit-length', l);
                  } catch {}
                  nav.closeModal();
                  nav.toast(`Unidades: ${w} · ${l} 💗`, { icon: '⚖️' });
                  setTimeout(() => window.location.reload(), 600);
                }}/>
              );
              return;
            }
            if (o.kind === 'idioma') {
              // Action sheet de idioma
              if (nav.openModal) nav.openModal(
                <IdiomaSheet T={T} onClose={() => nav.closeModal()} onSave={(lang) => {
                  try { localStorage.setItem('paufit-lang', lang); } catch {}
                  nav.closeModal();
                  const labels = { es: 'Español', en: 'English', pt: 'Português' };
                  nav.toast(`Idioma: ${labels[lang]} 💗`, { icon: '🌐' });
                  setTimeout(() => window.location.reload(), 600);
                }}/>
              );
              return;
            }
          }} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '14px 16px', cursor: 'pointer',
            borderBottom: i < arr.length-1 ? (T.dark ? '0.5px solid rgba(255,255,255,0.06)' : '0.5px solid rgba(0,0,0,0.05)') : 'none',
          }}>
            <span style={{ flex: 1, fontFamily: 'Poppins', fontSize: 14, fontWeight: 500, color: T.text }}>{o.t}</span>
            {o.detail && <span style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted }}>{o.detail}</span>}
            {Icon.chevR(T.muted, 8)}
          </div>
        ))}
      </div>

      <div style={{ textAlign: 'center', padding: '24px 0 8px', fontFamily: 'Poppins', fontSize: 10, color: T.muted, letterSpacing: 0.4 }}>
        Pau Fit · v1.0.0
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// UnidadesSheet — action sheet para elegir kg/lb + cm/in
// ─────────────────────────────────────────────────────────────
function UnidadesSheet({ T, onClose, onSave }) {
  const [w, setW] = useS4('kg');
  const [l, setL] = useS4('cm');
  useE4(() => {
    try {
      if (localStorage.getItem('paufit-unit-weight') === 'lb') setW('lb');
      if (localStorage.getItem('paufit-unit-length') === 'in') setL('in');
    } catch {}
  }, []);
  function row(label, value, opts, set) {
    return (
      <div style={{ marginTop: 14 }}>
        <div style={{ fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.3,  marginBottom: 8 }}>{label}</div>
        <div style={{ display: 'flex', gap: 8 }}>
          {opts.map(o => (
            <button key={o.v} onClick={() => set(o.v)} style={{
              flex: 1, padding: '12px', borderRadius: 14, cursor: 'pointer',
              border: value === o.v ? `1.5px solid ${T.accent}` : T.border,
              background: value === o.v ? `${T.accent}15` : T.card,
              color: T.text, fontFamily: 'Poppins', fontSize: 13, fontWeight: 600,
            }}>{o.label}</button>
          ))}
        </div>
      </div>
    );
  }
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 9999,
      background: 'rgba(0,0,0,0.6)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 480, background: T.card,
        borderTopLeftRadius: 24, borderTopRightRadius: 24, padding: '20px 22px 28px',
      }}>
        <div className="pf-eyebrow" style={{ color: T.muted }}>Ajustes</div>
        <div className="pf-display" style={{ fontSize: 20, fontWeight: 600, color: T.text, letterSpacing: -0.3, marginTop: 4 }}>
          Unidades
        </div>
        {row('Peso', w, [{ v: 'kg', label: 'Kilos (kg)' }, { v: 'lb', label: 'Libras (lb)' }], setW)}
        {row('Longitud', l, [{ v: 'cm', label: 'Centímetros (cm)' }, { v: 'in', label: 'Pulgadas (in)' }], setL)}
        <button onClick={() => onSave(w, l)} style={{
          marginTop: 24, width: '100%', padding: '14px',
          border: 'none', borderRadius: 20, cursor: 'pointer',
          background: T.accent, color: '#fff',
          fontFamily: 'Poppins', fontSize: 14, fontWeight: 600,
          boxShadow: `0 6px 18px ${T.accent}40`,
        }}>Guardar</button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// IdiomaSheet — action sheet para elegir idioma
// ─────────────────────────────────────────────────────────────
function IdiomaSheet({ T, onClose, onSave }) {
  const [lang, setLang] = useS4('es');
  useE4(() => {
    try {
      const cur = localStorage.getItem('paufit-lang');
      if (cur === 'en' || cur === 'pt') setLang(cur);
    } catch {}
  }, []);
  const langs = [
    { id: 'es', flag: '🇪🇸', name: 'Español', desc: 'Idioma actual' },
    { id: 'en', flag: '🇬🇧', name: 'English', desc: 'Beta · algunas zonas en español' },
    { id: 'pt', flag: '🇵🇹', name: 'Português', desc: 'Beta · algunas zonas en español' },
  ];
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 9999,
      background: 'rgba(0,0,0,0.6)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 480, background: T.card,
        borderTopLeftRadius: 24, borderTopRightRadius: 24, padding: '20px 22px 28px',
      }}>
        <div className="pf-eyebrow" style={{ color: T.muted }}>Ajustes</div>
        <div className="pf-display" style={{ fontSize: 20, fontWeight: 600, color: T.text, letterSpacing: -0.3, marginTop: 4 }}>
          Idioma
        </div>
        <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
          {langs.map(o => (
            <button key={o.id} onClick={() => setLang(o.id)} style={{
              padding: '14px 16px', borderRadius: 20, cursor: 'pointer',
              border: lang === o.id ? `1.5px solid ${T.accent}` : T.border,
              background: lang === o.id ? `${T.accent}15` : T.card,
              color: T.text, textAlign: 'left', fontFamily: 'inherit',
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <span style={{ fontSize: 24 }}>{o.flag}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 700 }}>{o.name}</div>
                <div style={{ fontSize: 11, color: T.muted, marginTop: 2 }}>{o.desc}</div>
              </div>
              {lang === o.id && <span style={{ color: T.accent, fontSize: 18 }}>✓</span>}
            </button>
          ))}
        </div>
        <button onClick={() => onSave(lang)} style={{
          marginTop: 24, width: '100%', padding: '14px',
          border: 'none', borderRadius: 20, cursor: 'pointer',
          background: T.accent, color: '#fff',
          fontFamily: 'Poppins', fontSize: 14, fontWeight: 600,
          boxShadow: `0 6px 18px ${T.accent}40`,
        }}>Guardar</button>
      </div>
    </div>
  );
}
