// Onboarding / Login flow — splash → login/signup → (cartão se signup) → personalização

const OnboardingFlow = ({ onComplete }) => {
  const [step, setStep] = React.useState(0);
  const [authedUser, setAuthedUser] = React.useState(null);
  const [paymentMethod, setPaymentMethod] = React.useState(null);

  return (
    <>
      {step === 0 && <SplashScreen onNext={() => setStep(1)} />}
      {step === 1 && (
        <LoginScreen
          onSignin={(user) => { setAuthedUser(user); setStep(3); }}
          onSignup={(user) => { setAuthedUser(user); setStep(2); }}
        />
      )}
      {step === 2 && (
        <CardSetupScreen
          onBack={() => setStep(1)}
          onSubmit={(card) => { setPaymentMethod(card); setStep(3); }}
        />
      )}
      {step === 3 && (
        <PersonalizationScreen onDone={(profile) =>
          onComplete({ user: authedUser, profile, paymentMethod })
        } />
      )}
    </>
  );
};

// ── Splash ─────────────────────────────────────────────────
const SplashScreen = ({ onNext }) => (
  <div style={{
    position: 'absolute', inset: 0, display: 'flex',
    flexDirection: 'column', justifyContent: 'space-between',
    padding: '70px 28px 50px',
    background: `
      radial-gradient(800px 400px at 50% 20%, rgba(177,151,252,0.22), transparent 60%),
      radial-gradient(600px 300px at 80% 90%, rgba(255,143,177,0.14), transparent 60%),
      ${CDV.bg}`,
  }}>
    <StatusBar />
    <div style={{ display: 'flex', flexDirection: 'column', gap: 28, alignItems: 'flex-start', flex: 1, justifyContent: 'center', marginTop: -40 }}>
      <div style={{ animation: 'float 4s ease-in-out infinite' }}>
        <BrandLogo size={92} animated />
      </div>
      <div>
        <div style={{ fontFamily: fontDisplay, fontSize: 52, lineHeight: 1, color: CDV.text, letterSpacing: -1, fontWeight: 400 }}>
          Central<br/><i style={{
            backgroundImage: 'linear-gradient(135deg, #C9B5FF 0%, #9D7AFF 45%, #FF8FB1 100%)',
            WebkitBackgroundClip: 'text', backgroundClip: 'text',
            WebkitTextFillColor: 'transparent', color: 'transparent',
          }}>da Vida</i>
        </div>
        <div style={{ fontSize: 17, color: CDV.textDim, marginTop: 18, lineHeight: 1.45, maxWidth: 320 }}>
          Sua rotina, finanças, hábitos e metas — guiados por inteligência artificial.
          Tudo num só lugar.
        </div>
      </div>
    </div>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      <button onClick={onNext} style={{
        height: 56, borderRadius: 18, border: 'none',
        background: CDV.text, color: '#000', fontWeight: 600, fontSize: 16,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      }}>
        Começar a jornada <Icon name="arrowRight" size={18} />
      </button>
      <div style={{ textAlign: 'center', fontSize: 12, color: CDV.textMuted, marginTop: 6 }}>
        3 dias grátis · Sem cobrança até confirmação
      </div>
    </div>
    <HomeIndicator light />
  </div>
);

// ── Login / Signup ──────────────────────────────────────────
const LoginScreen = ({ onSignin, onSignup, onLogin }) => {
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [confirmPassword, setConfirmPassword] = React.useState('');
  const [mode, setMode] = React.useState('signin'); // 'signin' | 'signup'
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [info, setInfo] = React.useState('');

  const configured = window.Auth && window.Auth.isConfigured();

  const handle = async (fn, isSignup) => {
    setError(''); setInfo(''); setLoading(true);
    try {
      const user = await fn();
      if (user) {
        // Compat: se onLogin existir (chamada antiga), usa ele
        if (typeof onLogin === 'function') onLogin(user);
        else if (isSignup && typeof onSignup === 'function') onSignup(user);
        else if (typeof onSignin === 'function') onSignin(user);
      }
    } catch (e) {
      setError(e && e.message ? e.message : 'Falha na autenticação');
    } finally {
      setLoading(false);
    }
  };

  const onApple = () => handle(() => window.Auth.signInWithProvider('apple'));
  const onGoogle = () => handle(() => window.Auth.signInWithProvider('google'));
  const onEmail = () => {
    if (mode === 'signup') {
      if (!name.trim()) return setError('Como devo te chamar? Preencha seu nome');
      if (!email || !password) return setError('Preencha todos os campos');
      if (password.length < 6) return setError('Senha precisa ter ao menos 6 caracteres');
      if (password !== confirmPassword) return setError('As senhas não conferem');
    } else {
      if (!email || !password) return setError('Preencha e-mail e senha');
    }
    handle(() => mode === 'signup'
      ? window.Auth.signUpWithEmail(email, password, name.trim())
      : window.Auth.signInWithEmail(email, password),
      mode === 'signup'
    );
  };
  const onForgot = async () => {
    if (!email) return setError('Digite seu e-mail para recuperar a senha');
    setError(''); setLoading(true);
    try {
      const res = await window.Auth.resetPassword(email);
      setInfo(res.mock
        ? 'Modo demo: simulação de recuperação enviada.'
        : 'E-mail de recuperação enviado. Verifique sua caixa.');
    } catch (e) {
      setError(e && e.message ? e.message : 'Falha ao enviar recuperação');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      position: 'absolute', inset: 0,
      display: 'flex', flexDirection: 'column',
      background: CDV.bg,
      overflow: 'hidden',
    }}>
      <StatusBar />

      {/* Hero — logo blurred no topo (proporcional, não estica) */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 0,
        overflow: 'hidden',
      }}>
        {/* Logo blurred — tamanho fixo em px pra ficar igual em qualquer tela */}
        <div style={{
          position: 'absolute',
          top: 'calc(env(safe-area-inset-top) + 20px)',
          left: '50%',
          transform: 'translateX(-50%)',
          width: 'min(70vw, 280px)',
          height: 'min(70vw, 280px)',
          backgroundImage: 'url("assets/logo-icon.png")',
          backgroundSize: 'contain',
          backgroundRepeat: 'no-repeat',
          backgroundPosition: 'center',
          filter: 'blur(14px) saturate(120%)',
          opacity: 0.22,
        }} />
        {/* Overlay com gradientes pra esmaecer e dar profundidade */}
        <div style={{
          position: 'absolute', inset: 0,
          background: `
            radial-gradient(500px 320px at 50% 0%, rgba(59,130,246,0.22), transparent 65%),
            radial-gradient(420px 260px at 90% 100%, rgba(177,151,252,0.14), transparent 65%),
            linear-gradient(180deg, transparent 0%, ${CDV.bg} 75%)
          `,
        }} />
      </div>

      <div style={{
        position: 'relative', zIndex: 1, flex: 1, overflow: 'auto',
        padding: '54px 24px 24px',
        display: 'flex', flexDirection: 'column',
      }}>
        {/* Logo + nome top */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 32 }}>
          <BrandLogo size={64} animated />
          <div style={{
            fontFamily: fontDisplay,
            fontSize: 22, fontWeight: 400, letterSpacing: -0.5,
            color: CDV.text, marginTop: 14, lineHeight: 1.1, textAlign: 'center',
          }}>
            Central <i style={{
              backgroundImage: 'linear-gradient(135deg, #C9B5FF 0%, #9D7AFF 45%, #FF8FB1 100%)',
              WebkitBackgroundClip: 'text', backgroundClip: 'text',
              WebkitTextFillColor: 'transparent', color: 'transparent',
            }}>da Vida</i>
          </div>
        </div>

        {/* Glass card com o form */}
        <div style={{
          background: 'rgba(20, 18, 30, 0.55)',
          backdropFilter: 'blur(20px) saturate(140%)',
          WebkitBackdropFilter: 'blur(20px) saturate(140%)',
          border: '1px solid rgba(255,255,255,0.08)',
          borderRadius: 22,
          padding: '24px 22px 22px',
          boxShadow: '0 20px 60px -20px rgba(0,0,0,0.55), 0 0 0 1px rgba(255,255,255,0.04) inset',
        }}>
          <div style={{ fontSize: 24, fontWeight: 700, color: CDV.text, letterSpacing: -0.6, lineHeight: 1.15 }}>
            {mode === 'signup' ? (
              <>Sua nova vida <i style={{
                backgroundImage: 'linear-gradient(135deg, #C9B5FF 0%, #9D7AFF 45%, #FF8FB1 100%)',
                WebkitBackgroundClip: 'text', backgroundClip: 'text',
                WebkitTextFillColor: 'transparent', color: 'transparent',
                fontFamily: fontDisplay, fontWeight: 400,
              }}>começa hoje</i></>
            ) : (
              <>Bem-vindo <i style={{
                backgroundImage: 'linear-gradient(135deg, #C9B5FF 0%, #9D7AFF 45%, #FF8FB1 100%)',
                WebkitBackgroundClip: 'text', backgroundClip: 'text',
                WebkitTextFillColor: 'transparent', color: 'transparent',
                fontFamily: fontDisplay, fontWeight: 400,
              }}>de volta</i></>
            )}
          </div>
          <div style={{ fontSize: 13, color: CDV.textDim, marginTop: 6, lineHeight: 1.4 }}>
            {mode === 'signup'
              ? 'Tarefas, finanças, hábitos e metas — guiados por IA.'
              : 'Continue de onde parou. Sofia está te esperando.'}
          </div>

        {/* Depoimento — só no signup */}
        {mode === 'signup' && (
          <div style={{
            marginTop: 14, padding: 14, borderRadius: 14, position: 'relative', overflow: 'hidden',
            background: `linear-gradient(135deg, ${CDV.brand}14, ${CDV.brand}04 50%, ${CDV.surface})`,
            border: `1px solid ${CDV.brand}30`,
          }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
              <div style={{
                width: 34, height: 34, borderRadius: 99, flexShrink: 0,
                background: 'linear-gradient(135deg, #FFB547, #FF7A6B)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#fff', fontSize: 13, fontWeight: 700,
              }}>M</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, color: CDV.text, lineHeight: 1.45, fontStyle: 'italic' }}>
                  "Em 1 mês organizei minha rotina inteira. A Sofia parece que me conhece."
                </div>
                <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 6 }}>
                  <b style={{ color: CDV.text, fontWeight: 600 }}>Mariana, 28</b> · São Paulo
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Banner trial */}
        {mode === 'signup' && (
          <div style={{
            marginTop: 12, padding: 14, borderRadius: 14, position: 'relative', overflow: 'hidden',
            background: 'linear-gradient(135deg, rgba(94,227,168,0.18), rgba(94,227,168,0.04))',
            border: `1px solid ${CDV.mint}40`,
          }}>
            <div style={{
              position: 'absolute', top: -30, right: -30, width: 110, height: 110, borderRadius: 99,
              background: `radial-gradient(circle, ${CDV.mint}55, transparent 60%)`,
              filter: 'blur(22px)', opacity: 0.55, pointerEvents: 'none',
            }} />
            <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{
                width: 38, height: 38, borderRadius: 11,
                background: `linear-gradient(135deg, ${CDV.mint}38, ${CDV.mint}14)`,
                border: `1px solid ${CDV.mint}40`, color: CDV.mint,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                boxShadow: `0 6px 16px -6px ${CDV.mint}80`,
              }}>
                <Icon name="sparkle" size={18} />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: CDV.text }}>3 dias grátis · sem cobrança</div>
                <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 2, lineHeight: 1.4 }}>
                  Teste todos os módulos. Cancele com 1 clique se não amar.
                </div>
              </div>
            </div>
          </div>
        )}

        {!configured && (
          <div style={{
            marginTop: 14, padding: '10px 12px', borderRadius: 12,
            background: CDV.amberSoft, border: `1px solid ${CDV.amber}30`,
            fontSize: 12, color: CDV.amber, fontWeight: 500,
          }}>
            Modo demo · configure Supabase em <b>auth-config.js</b> para auth real
          </div>
        )}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 22 }}>
          {mode === 'signup' && (
            <input value={name} onChange={e => setName(e.target.value)} placeholder="Seu nome" type="text" autoComplete="name"
              style={{
                height: 54, borderRadius: 16, border: `1px solid ${CDV.stroke}`,
                background: CDV.surface, color: CDV.text, padding: '0 18px', fontSize: 15,
                outline: 'none', fontFamily: 'inherit',
              }} />
          )}
          <input value={email} onChange={e => setEmail(e.target.value)} placeholder="seu@email.com" type="email" autoComplete="email"
            style={{
              height: 54, borderRadius: 16, border: `1px solid ${CDV.stroke}`,
              background: CDV.surface, color: CDV.text, padding: '0 18px', fontSize: 15,
              outline: 'none', fontFamily: 'inherit',
            }} />
          <input type="password" placeholder={mode === 'signup' ? 'Senha (mín. 6 caracteres)' : 'Senha'}
            value={password} onChange={e => setPassword(e.target.value)}
            autoComplete={mode === 'signup' ? 'new-password' : 'current-password'}
            onKeyDown={e => { if (e.key === 'Enter' && mode === 'signin') onEmail(); }}
            style={{
              height: 54, borderRadius: 16, border: `1px solid ${CDV.stroke}`,
              background: CDV.surface, color: CDV.text, padding: '0 18px', fontSize: 15,
              outline: 'none', fontFamily: 'inherit',
            }} />
          {mode === 'signup' && (
            <input type="password" placeholder="Confirme sua senha"
              value={confirmPassword} onChange={e => setConfirmPassword(e.target.value)}
              autoComplete="new-password"
              onKeyDown={e => { if (e.key === 'Enter') onEmail(); }}
              style={{
                height: 54, borderRadius: 16,
                border: `1px solid ${confirmPassword && confirmPassword !== password ? CDV.coral : CDV.stroke}`,
                background: CDV.surface, color: CDV.text, padding: '0 18px', fontSize: 15,
                outline: 'none', fontFamily: 'inherit',
              }} />
          )}
          {error && (
            <div style={{ fontSize: 12, color: CDV.coral, padding: '0 4px' }}>⚠ {error}</div>
          )}
          {info && (
            <div style={{ fontSize: 12, color: CDV.mint, padding: '0 4px' }}>✓ {info}</div>
          )}
          <button onClick={onEmail} disabled={loading} style={{
            height: 54, borderRadius: 16, border: 'none',
            background: CDV.brandGrad, color: '#fff', fontWeight: 600, fontSize: 15,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            boxShadow: '0 8px 28px -8px rgba(177,151,252,0.6)',
            opacity: loading ? 0.6 : 1, cursor: loading ? 'wait' : 'pointer',
          }}>
            {loading ? 'Carregando...' : (mode === 'signup' ? 'Continuar para pagamento' : 'Entrar')}
            {!loading && <Icon name="arrowRight" size={16} />}
          </button>
          {mode === 'signin' && (
            <div style={{ textAlign: 'center', marginTop: 4 }}>
              <span onClick={onForgot} style={{ color: CDV.brand, fontSize: 13, fontWeight: 500, cursor: 'pointer' }}>
                Esqueci minha senha
              </span>
            </div>
          )}
        </div>
      </div>
      <div style={{ textAlign: 'center', fontSize: 13, color: CDV.textDim, marginTop: 12 }}>
        {mode === 'signup' ? 'Já tem conta?' : 'Novo aqui?'}{' '}
        <span
          onClick={() => { setMode(mode === 'signup' ? 'signin' : 'signup'); setError(''); setInfo(''); setConfirmPassword(''); }}
          style={{ color: CDV.brand, fontWeight: 600, cursor: 'pointer' }}
        >
          {mode === 'signup' ? 'Entrar' : 'Crie sua conta'}
        </span>
      </div>

      {/* Trust badges */}
      <div style={{
        marginTop: 14, display: 'flex', alignItems: 'center', justifyContent: 'center',
        gap: 12, fontSize: 10, color: CDV.textMuted,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <Icon name="shield" size={11} color={CDV.mint} /> LGPD
        </div>
        <div style={{ width: 3, height: 3, borderRadius: 99, background: CDV.textMuted }} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <Icon name="lock" size={11} color={CDV.mint} /> Criptografado
        </div>
        <div style={{ width: 3, height: 3, borderRadius: 99, background: CDV.textMuted }} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <Icon name="check" size={11} color={CDV.mint} /> Sem fidelidade
        </div>
      </div>
      </div>{/* /content padded */}
      <HomeIndicator light />
    </div>
  );
};

// ── Card setup (trial de 3 dias) ────────────────────────────
const CardSetupScreen = ({ onBack, onSubmit }) => {
  const [number, setNumber] = React.useState('');
  const [expiry, setExpiry] = React.useState('');
  const [cvv, setCvv] = React.useState('');
  const [holder, setHolder] = React.useState('');
  const [error, setError] = React.useState('');

  const formatNumber = (v) => v.replace(/\D/g, '').slice(0, 19).replace(/(\d{4})(?=\d)/g, '$1 ');
  const formatExpiry = (v) => {
    const d = v.replace(/\D/g, '').slice(0, 4);
    return d.length > 2 ? `${d.slice(0, 2)}/${d.slice(2)}` : d;
  };

  // Detecta bandeira a partir do BIN
  const detectBrand = (n) => {
    const d = n.replace(/\D/g, '');
    if (/^4/.test(d)) return 'visa';
    if (/^(5[1-5]|2[2-7])/.test(d)) return 'mastercard';
    if (/^3[47]/.test(d)) return 'amex';
    if (/^(6011|65|64[4-9])/.test(d)) return 'elo';
    return 'cartão';
  };
  const brand = detectBrand(number);
  const last4 = number.replace(/\D/g, '').slice(-4);
  const digitsOnly = number.replace(/\D/g, '');
  const valid =
    digitsOnly.length >= 13 &&
    /^\d{2}\/\d{2}$/.test(expiry) &&
    cvv.length >= 3 &&
    holder.trim().length > 0;

  const submit = () => {
    setError('');
    if (!valid) {
      setError('Preencha todos os campos corretamente');
      return;
    }
    // Não enviamos número completo: apenas últimos 4, bandeira e validade
    onSubmit({
      brand,
      last4,
      expiry,
      holder: holder.trim(),
      addedAt: new Date().toISOString(),
    });
  };

  return (
    <div style={{
      position: 'absolute', inset: 0, padding: '70px 24px 36px',
      display: 'flex', flexDirection: 'column',
      background: CDV.bg,
    }}>
      <StatusBar />
      <div style={{ marginTop: 12, flex: 1, overflow: 'auto' }}>
        {/* Progress dots */}
        <div style={{ display: 'flex', gap: 6, marginBottom: 22 }}>
          <div style={{ height: 4, flex: 1, background: CDV.brand, borderRadius: 4 }} />
          <div style={{ height: 4, flex: 1, background: CDV.brand, borderRadius: 4 }} />
          <div style={{ height: 4, flex: 1, background: 'rgba(255,255,255,0.1)', borderRadius: 4 }} />
        </div>

        <button onClick={onBack} style={{
          background: 'transparent', border: 'none', color: CDV.textDim,
          fontSize: 13, fontWeight: 500, cursor: 'pointer', padding: 0, marginBottom: 14,
          display: 'flex', alignItems: 'center', gap: 4, fontFamily: 'inherit',
        }}>
          <Icon name="chevronRight" size={14} color={CDV.textDim} style={{ transform: 'rotate(180deg)' }} /> Voltar
        </button>

        <div style={{ fontSize: 26, fontWeight: 700, color: CDV.text, letterSpacing: -0.5, lineHeight: 1.15 }}>
          Adicione seu cartão
        </div>
        <div style={{ fontSize: 13, color: CDV.textDim, marginTop: 6, lineHeight: 1.4 }}>
          Você terá <b style={{ color: CDV.mint }}>3 dias grátis</b>. Depois cobramos R$ 29,90/mês — cancele quando quiser.
        </div>

        {/* Preview do cartão ao vivo */}
        <div style={{
          marginTop: 22, padding: 22, borderRadius: 22, height: 200,
          background: 'linear-gradient(135deg, #2A1B4A 0%, #4A1B33 100%)',
          border: `1px solid ${CDV.strokeHi}`,
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{
            position: 'absolute', top: -50, right: -50, width: 200, height: 200, borderRadius: 99,
            background: 'radial-gradient(circle, rgba(177,151,252,0.5), transparent 60%)', filter: 'blur(20px)',
          }} />
          <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', height: '100%', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.7)', fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>
                Central da Vida
              </div>
              <div style={{
                padding: '4px 10px', borderRadius: 6, background: 'rgba(255,255,255,0.12)',
                fontSize: 10, color: '#fff', fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase',
              }}>{brand}</div>
            </div>
            <div>
              <div style={{
                fontSize: 22, fontWeight: 600, color: '#fff', letterSpacing: 3, fontFamily: fontMono,
              }}>
                {number || '•••• •••• •••• ••••'}
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 14, alignItems: 'flex-end' }}>
                <div>
                  <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.5)', fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>Titular</div>
                  <div style={{ fontSize: 12, color: '#fff', marginTop: 2, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.5 }}>
                    {holder || 'NOME NO CARTÃO'}
                  </div>
                </div>
                <div>
                  <div style={{ fontSize: 9, color: 'rgba(255,255,255,0.5)', fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>Validade</div>
                  <div style={{ fontSize: 12, color: '#fff', marginTop: 2, fontWeight: 500, fontFamily: fontMono }}>
                    {expiry || 'MM/AA'}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Form */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 18 }}>
          <input
            value={number}
            onChange={e => setNumber(formatNumber(e.target.value))}
            placeholder="Número do cartão"
            inputMode="numeric"
            autoComplete="cc-number"
            style={{
              height: 52, borderRadius: 14, border: `1px solid ${CDV.stroke}`,
              background: CDV.surface, color: CDV.text, padding: '0 16px', fontSize: 15,
              outline: 'none', fontFamily: 'inherit', letterSpacing: 1,
            }}
          />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <input
              value={expiry}
              onChange={e => setExpiry(formatExpiry(e.target.value))}
              placeholder="MM/AA"
              inputMode="numeric"
              autoComplete="cc-exp"
              style={{
                height: 52, borderRadius: 14, border: `1px solid ${CDV.stroke}`,
                background: CDV.surface, color: CDV.text, padding: '0 16px', fontSize: 15,
                outline: 'none', fontFamily: 'inherit', letterSpacing: 1,
              }}
            />
            <input
              value={cvv}
              onChange={e => setCvv(e.target.value.replace(/\D/g, '').slice(0, 4))}
              placeholder="CVV"
              inputMode="numeric"
              autoComplete="cc-csc"
              style={{
                height: 52, borderRadius: 14, border: `1px solid ${CDV.stroke}`,
                background: CDV.surface, color: CDV.text, padding: '0 16px', fontSize: 15,
                outline: 'none', fontFamily: 'inherit', letterSpacing: 2,
              }}
            />
          </div>
          <input
            value={holder}
            onChange={e => setHolder(e.target.value.toUpperCase())}
            placeholder="Nome impresso no cartão"
            autoComplete="cc-name"
            style={{
              height: 52, borderRadius: 14, border: `1px solid ${CDV.stroke}`,
              background: CDV.surface, color: CDV.text, padding: '0 16px', fontSize: 15,
              outline: 'none', fontFamily: 'inherit', textTransform: 'uppercase',
            }}
          />
          {error && (
            <div style={{ fontSize: 12, color: CDV.coral, padding: '0 4px' }}>⚠ {error}</div>
          )}
        </div>

        {/* Disclaimers */}
        <div style={{
          marginTop: 16, padding: 12, borderRadius: 12,
          background: CDV.surfaceHi, border: `1px solid ${CDV.stroke}`,
        }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
            <Icon name="shield" size={14} color={CDV.mint} style={{ marginTop: 2, flexShrink: 0 }} />
            <div style={{ fontSize: 11, color: CDV.textDim, lineHeight: 1.5 }}>
              Não armazenamos o número completo nem o CVV. Salvamos apenas os últimos 4 dígitos e a validade pra identificar seu cartão. Pagamento processado por gateway seguro.
            </div>
          </div>
        </div>
      </div>

      <button onClick={submit} style={{
        marginTop: 16, height: 56, borderRadius: 18, border: 'none',
        background: CDV.brandGrad, color: '#fff', fontWeight: 700, fontSize: 16,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        boxShadow: '0 10px 30px -10px rgba(177,151,252,0.6)',
        opacity: valid ? 1 : 0.6, cursor: valid ? 'pointer' : 'not-allowed',
        fontFamily: 'inherit',
      }}>
        <Icon name="sparkle" size={18} /> Começar 3 dias grátis
      </button>
      <div style={{ textAlign: 'center', fontSize: 11, color: CDV.textMuted, marginTop: 8, lineHeight: 1.5 }}>
        Você será lembrado 24h antes da cobrança · cancele a qualquer momento
      </div>
      <HomeIndicator light />
    </div>
  );
};

// ── Personalization ─────────────────────────────────────────
const PersonalizationScreen = ({ onDone }) => {
  const [name, setName] = React.useState('Lucas');
  const [goals, setGoals] = React.useState(['organizar', 'financas']);

  const opts = [
    { id: 'organizar', label: 'Organizar minha rotina', icon: 'tasks' },
    { id: 'financas', label: 'Controlar finanças', icon: 'wallet' },
    { id: 'habitos', label: 'Criar hábitos', icon: 'flame' },
    { id: 'metas', label: 'Atingir metas grandes', icon: 'target' },
    { id: 'foco', label: 'Aumentar foco', icon: 'pomodoro' },
    { id: 'paz', label: 'Reduzir ansiedade', icon: 'meditate' },
  ];

  const toggle = (id) => setGoals(g => g.includes(id) ? g.filter(x => x !== id) : [...g, id]);

  return (
    <div style={{ position: 'absolute', inset: 0, padding: '70px 22px 36px', display: 'flex', flexDirection: 'column', background: CDV.bg }}>
      <StatusBar />
      <div style={{ marginTop: 18, flex: 1, overflow: 'auto' }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 18 }}>
          <div style={{ height: 4, flex: 1, background: CDV.brand, borderRadius: 4 }} />
          <div style={{ height: 4, flex: 1, background: CDV.brand, borderRadius: 4 }} />
          <div style={{ height: 4, flex: 1, background: 'rgba(255,255,255,0.1)', borderRadius: 4 }} />
        </div>
        <div style={{ fontSize: 26, fontWeight: 700, color: CDV.text, letterSpacing: -0.4, lineHeight: 1.15 }}>
          Vamos personalizar sua experiência
        </div>
        <div style={{ fontSize: 14, color: CDV.textDim, marginTop: 8 }}>A IA usará isso para sugerir o que importa para você.</div>

        <div style={{ marginTop: 24, fontSize: 12, color: CDV.textMuted, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase' }}>Como podemos te chamar?</div>
        <input value={name} onChange={e => setName(e.target.value)} placeholder="Seu primeiro nome"
          style={{
            marginTop: 8, height: 54, width: '100%', borderRadius: 16, border: `1px solid ${CDV.stroke}`,
            background: CDV.surface, color: CDV.text, padding: '0 18px', fontSize: 16,
            outline: 'none', fontFamily: 'inherit',
          }} />

        <div style={{ marginTop: 24, fontSize: 12, color: CDV.textMuted, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase' }}>O que você quer melhorar?</div>
        <div style={{ marginTop: 10, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {opts.map(o => {
            const active = goals.includes(o.id);
            return (
              <button key={o.id} onClick={() => toggle(o.id)} style={{
                padding: '16px 14px', height: 96, borderRadius: 18, textAlign: 'left',
                background: active ? CDV.brandSoft : CDV.surface,
                border: `1.5px solid ${active ? CDV.brand : CDV.stroke}`,
                color: CDV.text, fontFamily: 'inherit',
                display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
              }}>
                <Icon name={o.icon} size={22} color={active ? CDV.brand : CDV.textDim} />
                <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.2 }}>{o.label}</div>
              </button>
            );
          })}
        </div>
      </div>
      <button onClick={() => onDone({ name, goals })} style={{
        marginTop: 16, height: 56, borderRadius: 18, border: 'none',
        background: CDV.brandGrad, color: '#fff', fontWeight: 600, fontSize: 16,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        boxShadow: '0 10px 30px -10px rgba(177,151,252,0.6)',
      }}>
        Entrar na minha Central <Icon name="arrowRight" size={18} />
      </button>
      <HomeIndicator light />
    </div>
  );
};

Object.assign(window, { OnboardingFlow });
