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

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

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

  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' }}>
        <div style={{
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          width: 72, height: 72, borderRadius: 24, background: T.accent,
          fontFamily: 'Poppins', fontSize: 40, fontWeight: 800, fontStyle: 'italic',
          color: '#fff', letterSpacing: -1, boxShadow: `0 12px 28px ${T.accent}55`,
        }}>p</div>
        <div style={{ fontFamily: 'Poppins', fontSize: 28, fontWeight: 600, color: T.text, marginTop: 14, 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 */}
        <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 10 }}>
          <SocialBtn dark icon={<AppleGlyph/>} label="Continuar con Apple" T={T}/>
          <SocialBtn icon={<GoogleGlyph/>} label="Continuar con Google" T={T}/>
        </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: 14, 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: 14, background: T.card,
            fontFamily: 'Poppins', fontSize: 14, color: T.text, outline: 'none',
          }}/>
        </div>

        {mode === 'login' && (
          <button onClick={() => nav.toast('Te enviamos un email 💗', { 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={() => mode === 'signup' ? nav.go('onboarding') : nav.back()} style={{
          marginTop: 14, width: '100%', padding: '16px',
          border: 'none', borderRadius: 14, cursor: 'pointer',
          background: T.accent, color: '#fff',
          fontFamily: 'Poppins', fontSize: 15, fontWeight: 600, letterSpacing: -0.1,
          boxShadow: `0 6px 18px ${T.accent}40`,
        }}>{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 }) {
  return (
    <button onClick={() => window.__pauNav && (window.__pauNav.toast('Sesión iniciada 💗', { icon: '✓' }), window.__pauNav.back())} style={{
      width: '100%', padding: '14px',
      border: dark ? 'none' : T.border,
      background: dark ? '#000' : T.card,
      color: dark ? '#fff' : T.text,
      borderRadius: 14, 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
// ═════════════════════════════════════════════════════════════
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 [notif, setNotif] = useS4(null);

  const steps = [
    { title: '¿Cómo te llamas?', sub: 'Para personalizarlo todo 💗' },
    { title: '¿Cuál es tu objetivo?', sub: 'Adaptaremos tus retos' },
    { title: '¿Cuántos días por semana?', sub: 'Sé realista, sin presión' },
    { title: 'Última cosa…', sub: 'Recordatorios opcionales' },
  ];
  const total = steps.length;
  const currentValid = (
    (step === 0 && name.trim().length > 0) ||
    (step === 1 && obj) ||
    (step === 2 && days) ||
    (step === 3 && notif !== null)
  );

  function next() {
    if (step < total - 1) setStep(step + 1);
    else (onDone || (() => nav.tab('home')))();
  }

  return (
    <div style={{ paddingTop: 50, paddingBottom: 30, minHeight: '100%', background: T.bg, display: 'flex', flexDirection: 'column' }}>
      {/* Progress */}
      <div style={{ padding: '12px 22px 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 22px 0', flex: 1 }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 26, fontWeight: 600, color: T.text, letterSpacing: -0.5, lineHeight: 1.2 }}>{steps[step].title}</div>
        <div style={{ fontFamily: 'Poppins', fontSize: 13, color: T.muted, marginTop: 6 }}>{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: 14, background: T.card,
              fontFamily: 'Poppins', fontSize: 18, color: T.text, outline: 'none',
              fontWeight: 500,
            }}/>
          )}
          {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: 18, 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>
          )}
          {step === 2 && (
            <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 18px',
                    border: sel ? `1.5px solid ${T.accent}` : T.border,
                    background: sel ? `${T.accent}10` : T.card,
                    borderRadius: 14, 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>
          )}
          {step === 3 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div style={{ padding: '20px 18px', background: T.card, borderRadius: 18, border: T.border }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                  <span style={{ fontSize: 32 }}>🔔</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, color: T.text }}>Recordatorios diarios</div>
                    <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, marginTop: 2, lineHeight: 1.4 }}>Te avisamos a tu hora para no romper la racha</div>
                  </div>
                </div>
              </div>
              <button onClick={() => setNotif(true)} style={{
                padding: '14px',
                border: notif === true ? `1.5px solid ${T.accent}` : T.border,
                background: notif === true ? `${T.accent}10` : T.card,
                borderRadius: 14, cursor: 'pointer',
                fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, color: T.text,
              }}>💗 Sí, actívalas</button>
              <button onClick={() => setNotif(false)} style={{
                padding: '14px',
                border: notif === false ? `1.5px solid ${T.accent}` : T.border,
                background: notif === false ? `${T.accent}10` : T.card,
                borderRadius: 14, cursor: 'pointer',
                fontFamily: 'Poppins', fontSize: 14, fontWeight: 500, color: T.muted,
              }}>Ahora no</button>
            </div>
          )}
        </div>
      </div>

      <div style={{ padding: '0 22px' }}>
        <button onClick={next} disabled={!currentValid} style={{
          width: '100%', padding: '16px',
          border: 'none', borderRadius: 14,
          cursor: currentValid ? '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',
        }}>{step === total - 1 ? '¡Empezar! 💗' : 'Siguiente'}</button>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// CHAT — comunidad grupal
// ═════════════════════════════════════════════════════════════
const CHAT_MESSAGES = [
  { id: 1, user: 'María',  initials: 'M', text: '¡Buenos días chicas! ¿Quién está haciendo el día 5 hoy? 💗', time: '8:42', mine: false, color: '#D14C7A' },
  { id: 2, user: 'Lucía',  initials: 'L', text: 'Yoooo!! ya estoy estirando. ¡Vamos!', time: '8:45', mine: false, color: '#C2649A' },
  { id: 3, user: 'Pauu',   initials: 'P', text: 'Aquí también 💪🏻 acabo de terminar el cardio', time: '8:46', mine: true,  color: null },
  { id: 4, user: 'Ana',    initials: 'A', text: 'Chicas alguna receta sana para post-entreno??', time: '9:02', mine: false, color: '#E07A9C' },
  { id: 5, user: 'María',  initials: 'M', text: 'El pre-entreno de Pau funciona también de post! Yogur + banana + miel 🥣', time: '9:03', mine: false, color: '#D14C7A' },
  { id: 6, user: 'Sofía',  initials: 'S', text: 'Día 12 hoy del cintura de avispa 🐝 y ya se nota muchísimo', time: '9:10', mine: false, color: '#B070A8' },
  { id: 7, user: 'Carla',  initials: 'C', text: 'Felicidades Sofí ✨✨', time: '9:11', mine: false, color: '#D9477E' },
  { id: 8, user: 'Pau',    initials: 'PA', text: 'Qué energía tenéis chicas 💗 hoy subo nueva rutina a las 7pm, atentas', time: '9:14', mine: false, color: '#C9956B', staff: true },
];

function ChatScreen({ theme, nav }) {
  const T = theme;
  const [input, setInput] = useS4('');
  const [msgs, setMsgs] = useS4(CHAT_MESSAGES);
  const [typing, setTyping] = useS4(null);
  const scrollRef = useR4(null);

  // Auto-scroll on new messages / typing — use rAF so DOM has updated
  useE4(() => {
    requestAnimationFrame(() => {
      const el = scrollRef.current;
      if (el) el.scrollTop = el.scrollHeight;
    });
  }, [msgs, typing]);

  const RESPONDERS = [
    { user: 'María',  initials: 'M', color: '#D14C7A', replies: ['Jajaja sí 😂', '¡Vamos!', 'Total 💗', 'Eres una crack'] },
    { user: 'Lucía',  initials: 'L', color: '#C2649A', replies: ['Yo también 🔥', '💗💗💗', 'Qué buena energía', '+1'] },
    { user: 'Ana',    initials: 'A', color: '#E07A9C', replies: ['¡Apuntado!', 'Gracias chicas 💖', 'Lo voy a probar', 'Qué motivación'] },
    { user: 'Carla',  initials: 'C', color: '#D9477E', replies: ['Sí sí sí 🙌🏻', 'Ole tú', 'Vamosss', '💪🏻💪🏻'] },
  ];

  function send() {
    if (!input.trim()) return;
    const myText = input;
    setMsgs(m => [...m, {
      id: Date.now(), user: 'Pauu', initials: 'P', text: myText,
      time: timeNow(), mine: true,
    }]);
    setInput('');
    // Simulate a reply
    const responder = RESPONDERS[Math.floor(Math.random() * RESPONDERS.length)];
    setTimeout(() => setTyping(responder), 600);
    setTimeout(() => {
      setTyping(null);
      const reply = responder.replies[Math.floor(Math.random() * responder.replies.length)];
      setMsgs(m => [...m, {
        id: Date.now() + 1, user: responder.user, initials: responder.initials,
        text: reply, time: timeNow(), mine: false, color: responder.color,
      }]);
    }, 1800 + Math.random() * 1200);
  }

  return (
    <div style={{
      position: 'absolute', inset: 0,
      display: 'flex', flexDirection: 'column', background: T.bg,
    }}>
      {/* Header (fixed) */}
      <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={{ fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, color: T.text }}>Comunidad Pau Fit</div>
          <div style={{ fontFamily: 'Poppins', fontSize: 10, color: T.muted, marginTop: 1 }}>
            <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: 999, background: '#A8C5A0', marginRight: 4 }}/>
            287 en línea · 14,283 miembros
          </div>
        </div>
      </div>

      {/* Messages (scrollable middle) */}
      <div ref={scrollRef} style={{
        flex: 1, minHeight: 0, padding: '14px 14px 14px',
        display: 'flex', flexDirection: 'column', gap: 8,
        overflowY: 'auto', overflowX: 'hidden',
        WebkitOverflowScrolling: 'touch',
      }}>
        <div style={{
          alignSelf: 'center', padding: '6px 12px', borderRadius: 999,
          background: T.subtle, fontFamily: 'Poppins', fontSize: 10, color: T.muted, fontWeight: 500, letterSpacing: 0.3,
          marginBottom: 6,
        }}>Hoy</div>

        {msgs.map(m => <ChatBubble key={m.id} m={m} T={T}/>)}

        {/* Typing indicator */}
        {typing && (
          <div style={{ display: 'flex', gap: 8, alignItems: 'flex-end', maxWidth: '85%' }}>
            <div style={{
              width: 30, height: 30, borderRadius: 999, flexShrink: 0,
              background: `linear-gradient(135deg, ${typing.color}, ${typing.color}99)`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'Poppins', fontSize: 11, fontWeight: 700, color: '#fff',
            }}>{typing.initials}</div>
            <div style={{
              padding: '10px 14px', background: T.card,
              borderRadius: 18, borderBottomLeftRadius: 4,
              border: T.border, display: 'flex', gap: 4, alignItems: 'center',
            }}>
              <Dot delay={0} color={T.muted}/>
              <Dot delay={150} color={T.muted}/>
              <Dot delay={300} color={T.muted}/>
            </div>
          </div>
        )}
      </div>

      {/* Input (fixed bottom) */}
      <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()}
          placeholder="Escribe a la comunidad…" style={{
          flex: 1, padding: '10px 16px', border: T.border, borderRadius: 999,
          background: T.card, fontFamily: 'Poppins', fontSize: 14, color: T.text, outline: 'none',
        }}/>
        <button onClick={send} style={{
          width: 38, height: 38, borderRadius: 999, border: 'none',
          background: T.accent, cursor: 'pointer',
          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>
  );
}

function timeNow() {
  const d = new Date();
  return `${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
}

function Dot({ delay, color }) {
  return (
    <span style={{
      width: 6, height: 6, borderRadius: 999, background: color,
      animation: `pulse 1.2s ease-in-out ${delay}ms infinite`,
    }}/>
  );
}

function ChatBubble({ m, T }) {
  if (m.mine) {
    return (
      <div style={{ alignSelf: 'flex-end', maxWidth: '78%', display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
        <div style={{
          padding: '10px 14px', background: T.accent, color: '#fff',
          borderRadius: 18, borderBottomRightRadius: 4,
          fontFamily: 'Poppins', fontSize: 13, lineHeight: 1.4,
        }}>{m.text}</div>
        <div style={{ fontFamily: 'Poppins', fontSize: 9, color: T.muted, marginTop: 2 }}>{m.time}</div>
      </div>
    );
  }
  return (
    <div style={{ display: 'flex', gap: 8, alignItems: 'flex-end', maxWidth: '85%' }}>
      <div style={{
        width: 30, height: 30, borderRadius: 999, flexShrink: 0,
        background: `linear-gradient(135deg, ${m.color}, ${m.color}99)`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: 'Poppins', fontSize: 11, fontWeight: 700, color: '#fff',
      }}>{m.initials}</div>
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2, paddingLeft: 4 }}>
          <span style={{ fontFamily: 'Poppins', fontSize: 10, fontWeight: 600, color: T.text }}>{m.user}</span>
          {m.staff && (
            <span style={{
              padding: '1px 5px', borderRadius: 5, background: '#C9956B',
              fontFamily: 'Poppins', fontSize: 7, fontWeight: 700, color: '#2D2A26', letterSpacing: 0.4,
            }}>STAFF</span>
          )}
          <span style={{ fontFamily: 'Poppins', fontSize: 9, color: T.muted }}>{m.time}</span>
        </div>
        <div style={{
          padding: '10px 14px', background: T.card, color: T.text,
          borderRadius: 18, borderBottomLeftRadius: 4,
          fontFamily: 'Poppins', fontSize: 13, lineHeight: 1.4,
          border: T.border,
        }}>{m.text}</div>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// NOTIFICACIONES — settings + preview
// ═════════════════════════════════════════════════════════════
function NotificacionesScreen({ theme, nav }) {
  const T = theme;
  const [prefs, setPrefs] = useS4({
    workout: true, streak: true, retos: false, comunidad: true, motivation: true,
  });
  function toggle(k) { setPrefs(p => ({ ...p, [k]: !p[k] })); }

  return (
    <div style={{ paddingBottom: 110 }}>
      <div style={{
        background: T.subtle, padding: '12px 22px 24px',
        borderBottomLeftRadius: 32, borderBottomRightRadius: 32,
      }}>
        <BackBtn onClick={() => nav.back()}/>
        <div style={{ marginTop: 14, fontFamily: 'Poppins', fontSize: 26, fontWeight: 600, color: T.text, letterSpacing: -0.5 }}>Notificaciones</div>
        <div style={{ fontFamily: 'Poppins', fontSize: 12, color: T.muted, marginTop: 4 }}>Personaliza tus recordatorios</div>
      </div>

      {/* Preview iOS-style */}
      <div style={{ padding: '20px 22px 8px' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>Cómo se ven en tu pantalla</div>
      </div>
      <div style={{ margin: '0 18px', 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: 16, 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: '24px 22px 8px' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>Qué quieres recibir</div>
      </div>
      <div style={{ margin: '0 18px', background: T.card, borderRadius: 18, 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: 44, height: 26, borderRadius: 999, border: 'none', cursor: 'pointer',
              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: '24px 22px 8px' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>Hora preferida</div>
      </div>
      <div style={{
        margin: '0 18px', padding: '16px 18px',
        background: T.card, borderRadius: 18, border: T.border,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 14, color: T.text, fontWeight: 500 }}>Recordatorio diario</div>
        <div style={{
          padding: '8px 14px', borderRadius: 999, background: T.subtle,
          fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, color: T.text, letterSpacing: -0.2,
        }}>18:30</div>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// ADMIN — solo para Pau (mockup del panel)
// ═════════════════════════════════════════════════════════════
const PENDING_TESTIMONIES = [
  { id: 'pt1', user: 'Lola',  initials: 'L', text: 'No me sirvió. Demasiado fácil.', date: 'hace 2 h', target: 'Cintura de avispa', recommends: false, suspect: true },
  { id: 'pt2', user: 'Vega',  initials: 'V', text: 'Hice solo 3 días, supongo que está ok.', date: 'hace 5 h', target: 'Glúteos PRO', recommends: true, suspect: false },
  { id: 'pt3', user: 'Naia',  initials: 'N', text: 'COMPRA EN MI WEB!! www.spam-spam.com', date: 'hace 1 d', target: 'Transforma tu cuerpo', recommends: true, suspect: true, flag: 'enlace sospechoso' },
];

function AdminScreen({ theme, nav }) {
  const T = theme;
  const [tab, setTab] = useS4('testimonios');
  const [pending, setPending] = useS4(PENDING_TESTIMONIES);

  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 22px 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, textTransform: 'uppercase' }}>Panel de control</div>
        <div style={{ fontFamily: 'Poppins', fontSize: 26, fontWeight: 600, color: '#F5E6C8', marginTop: 4, letterSpacing: -0.5 }}>Pau Fit · Admin</div>

        {/* KPIs */}
        <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
          <KPI v="14,283" l="usuarias"/>
          <KPI v="2,104" l="premium" gold/>
          <KPI v="247€" 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 18px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
          {pending.length === 0 ? (
            <div style={{ padding: 30, textAlign: 'center', background: T.card, borderRadius: 16, 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: 16, 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 18px 0', display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>Por reto · esta semana</div>
          {RETOS.map(r => (
            <div key={r.id} style={{
              padding: '14px 16px', background: T.card, borderRadius: 16, border: T.border,
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <div style={{
                width: 40, height: 40, borderRadius: 12, 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.toLocaleString()} unidas · {r.doing.toLocaleString()} activas · {r.completed_count.toLocaleString()} completadas
                </div>
              </div>
              <div style={{
                width: 50, textAlign: 'right',
                fontFamily: 'Poppins', fontSize: 14, fontWeight: 700, color: r.color, letterSpacing: -0.3,
              }}>{Math.round(r.completed_count / r.joined * 100)}%</div>
            </div>
          ))}
        </div>
      )}

      {tab === 'retos' && (
        <div style={{ padding: '14px 18px 0' }}>
          <button onClick={() => nav.toast('Editor de retos · próximamente', { icon: '✏️' })} style={{
            width: '100%', padding: '14px', border: `1.5px dashed ${T.muted}80`,
            background: 'transparent', borderRadius: 14, cursor: 'pointer',
            fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: T.text,
          }}>＋ Crear nuevo reto</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: 14, 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={() => nav.toast(`Editando ${r.title}`, { icon: '✏️' })} 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: 12,
      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, textTransform: 'uppercase' }}>{l}</div>
    </div>
  );
}

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

// ═════════════════════════════════════════════════════════════
// EDITAR PERFIL
// ═════════════════════════════════════════════════════════════
function EditarPerfilScreen({ theme, nav }) {
  const T = theme;
  const [name, setName] = useS4(STATS.name);
  const [user, setUser] = useS4('pauu');
  const [bio, setBio] = useS4('Constancia con cariño 💗 #YoSiemprePuedo');
  const [email] = useS4('pauu@email.com');
  const [phone, setPhone] = useS4('');
  const [birth, setBirth] = useS4('1998-03-12');
  const [gender, setGender] = useS4('mujer');
  const [obj, setObj] = useS4('tonificar');
  const [days, setDays] = useS4(5);
  const [height, setHeight] = useS4(165);
  const [hasAvatar, setHasAvatar] = useS4(false);

  function save() {
    nav.toast('Perfil actualizado 💗', { icon: '✓' });
    setTimeout(() => nav.back(), 600);
  }

  return (
    <div style={{ paddingBottom: 110 }}>
      <div style={{
        background: T.subtle, padding: '12px 22px 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' }}>
            <div style={{
              width: 96, height: 96, borderRadius: 999,
              background: hasAvatar
                ? `linear-gradient(135deg, ${T.accent}40, ${T.subtle})`
                : `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`,
            }}>
              {hasAvatar ? <span style={{ fontSize: 40 }}>📸</span> : name.slice(0, 2).toUpperCase()}
            </div>
            <button onClick={() => setHasAvatar(!hasAvatar)} 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: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14,
            }}>📷</button>
          </div>
          <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 500 }}>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)}/>
        </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: 12,
          }}>
            <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',
            }}/>
            <span style={{ fontFamily: 'Poppins', fontSize: 13, color: T.muted, fontWeight: 500 }}>cm</span>
          </div>
        </Field>
      </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: 14, 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: '24px 22px 8px' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>Zona peligrosa</div>
      </div>
      <div style={{ margin: '0 18px', background: T.card, borderRadius: 18, overflow: 'hidden', border: T.border }}>
        <button onClick={() => nav.toast('Exportando datos…', { 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>
        </button>
        <button onClick={() => nav.toast('Esta acción no se puede deshacer', { 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>
        </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, textTransform: 'uppercase' }}>{title}</div>
      </div>
      <div style={{ margin: '0 18px', 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: 12, background: T.card,
    fontFamily: 'Poppins', fontSize: 14, color: T.text, outline: 'none',
    boxSizing: 'border-box',
  };
}

// ═════════════════════════════════════════════════════════════
// AJUSTES — palette picker (premium feature), idioma, unidades
// ═════════════════════════════════════════════════════════════
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={{
        background: T.subtle, padding: '12px 22px 24px',
        borderBottomLeftRadius: 32, borderBottomRightRadius: 32,
      }}>
        <BackBtn onClick={() => nav.back()}/>
        <div style={{ marginTop: 14, fontFamily: 'Poppins', fontSize: 26, fontWeight: 600, color: T.text, letterSpacing: -0.5 }}>Ajustes</div>
        <div style={{ fontFamily: 'Poppins', fontSize: 12, color: T.muted, marginTop: 4 }}>Personaliza tu Pau Fit</div>
      </div>

      {/* Tema visual */}
      <div style={{ padding: '24px 22px 8px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>Tema visual</span>
          {!isPremium && (
            <span style={{
              padding: '2px 6px', borderRadius: 5, background: '#2D2A26', color: '#F5E6C8',
              fontFamily: 'Poppins', fontSize: 8, fontWeight: 700, letterSpacing: 0.5,
            }}>PREMIUM</span>
          )}
        </div>
        <div style={{ fontFamily: 'Poppins', fontSize: 12, color: T.muted, marginTop: 4, lineHeight: 1.4 }}>
          Cambia los colores de tu app a tu gusto.{!isPremium && ' Hazte premium para desbloquear todos los temas.'}
        </div>
      </div>

      <div style={{ padding: '12px 18px 0', 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: 18, 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={{ padding: '24px 22px 8px' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>Apariencia</div>
      </div>
      <div style={{ margin: '0 18px', background: T.card, borderRadius: 18, overflow: 'hidden', border: T.border }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
        }}>
          <span style={{ fontSize: 20 }}>🌙</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'Poppins', fontSize: 14, fontWeight: 500, color: T.text }}>Modo oscuro</div>
            <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, marginTop: 1 }}>Más cómodo de noche</div>
          </div>
          <button onClick={() => setTweak('darkMode', !tweaks.darkMode)} style={{
            width: 44, height: 26, borderRadius: 999, border: 'none', cursor: 'pointer',
            background: tweaks.darkMode ? T.accent : 'rgba(0,0,0,0.12)', position: 'relative',
            transition: 'background 200ms ease',
          }}>
            <div style={{
              position: 'absolute', top: 3, left: tweaks.darkMode ? 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>

      {/* Cuenta */}
      <div style={{ padding: '24px 22px 8px' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>Cuenta</div>
      </div>
      <div style={{ margin: '0 18px', background: T.card, borderRadius: 18, overflow: 'hidden', border: T.border }}>
        {[
          { e: '✏️', t: 'Editar perfil', detail: 'Pauu · pauu@email.com', kind: 'editarPerfil' },
          { e: '🔒', t: 'Privacidad' },
          { e: '⚖️', t: 'Unidades', detail: 'kg · cm' },
          { e: '🌐', t: 'Idioma', detail: 'Español' },
        ].map((o, i, arr) => (
          <div key={i} onClick={() => o.kind ? nav.go(o.kind) : nav.toast(`${o.t}: próximamente`, { icon: '⏳' })} 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={{ fontSize: 18 }}>{o.e}</span>
            <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>
  );
}
