const { useState, useEffect, useRef, useCallback } = React;

function Icon({ d, size = 18 }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">{d}</svg>;
}
const ICONS = {
  lock:    <path d="M5 11h14v10H5zM8 11V7a4 4 0 0 1 8 0v4" />,
  card:    <React.Fragment><rect x="2" y="5" width="20" height="14" rx="2" /><path d="M2 10h20" /></React.Fragment>,
  pix:     <React.Fragment><path d="M12 3l4 4-4 4-4-4z" /><path d="M12 21l4-4-4-4-4 4z" /><path d="M3 12l4-4 4 4-4 4z" /><path d="M21 12l-4-4-4 4 4 4z" /></React.Fragment>,
  check:   <path d="M20 6L9 17l-5-5" />,
  chevron: <path d="M9 18l6-6-6-6" />,
  spin:    <React.Fragment><circle cx="12" cy="12" r="9" stroke="rgba(255,255,255,0.2)" strokeWidth="3" /><path d="M12 3a9 9 0 0 1 9 9" stroke="currentColor" strokeWidth="3" strokeLinecap="round" /></React.Fragment>,
  copy:    <React.Fragment><rect x="9" y="9" width="13" height="13" rx="2" /><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" /></React.Fragment>,
};

function fmtCard(v)   { return v.replace(/\D/g, '').slice(0, 16).replace(/(\d{4})(?=\d)/g, '$1 '); }
function fmtExpiry(v) { const d = v.replace(/\D/g, '').slice(0, 4); return d.length > 2 ? d.slice(0, 2) + '/' + d.slice(2) : d; }
function fmtPhone(v)  { const d = v.replace(/\D/g, '').slice(0, 11); if (d.length <= 2) return d; if (d.length <= 7) return `(${d.slice(0,2)}) ${d.slice(2)}`; return `(${d.slice(0,2)}) ${d.slice(2,7)}-${d.slice(7)}`; }
function fmtCpf(v)    { const d = v.replace(/\D/g, '').slice(0, 11); if (d.length <= 3) return d; if (d.length <= 6) return `${d.slice(0,3)}.${d.slice(3)}`; if (d.length <= 9) return `${d.slice(0,3)}.${d.slice(3,6)}.${d.slice(6)}`; return `${d.slice(0,3)}.${d.slice(3,6)}.${d.slice(6,9)}-${d.slice(9)}`; }
function validCpf(v)  { const d = v.replace(/\D/g, ''); return d.length === 11; }

// ─── Componentes base ────────────────────────────────────────────────────────

function Spinner() {
  return (
    <span style={{ display: 'inline-flex', animation: 'spin 0.8s linear infinite' }}>
      <style>{`@keyframes spin{to{transform:rotate(360deg)}}`}</style>
      <Icon d={ICONS.spin} size={18} />
    </span>
  );
}

function ErrorBox({ msg }) {
  if (!msg) return null;
  return (
    <div style={{ background: 'rgba(255,22,117,0.08)', border: '1px solid rgba(255,22,117,0.3)', borderRadius: 'var(--radius-md)', padding: '12px 16px', marginBottom: 16, fontSize: 13, color: 'var(--magenta-light)', lineHeight: 1.5 }}>
      {msg}
    </div>
  );
}

function Field({ label, ...props }) {
  const [focused, setFocused] = useState(false);
  return (
    <label style={{ display: 'block', marginBottom: 16 }}>
      <span style={{ display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 6 }}>{label}</span>
      <input
        {...props}
        style={{ width: '100%', background: 'var(--bg-primary)', border: `1px solid ${props.error ? 'var(--magenta)' : focused ? 'var(--border-focus)' : 'var(--border-default)'}`, borderRadius: 'var(--radius-md)', padding: '12px 14px', fontSize: 14, color: 'var(--text-primary)', fontFamily: 'var(--font-ui)', outline: 'none', boxSizing: 'border-box', transition: 'border-color .15s' }}
        onFocus={e => { setFocused(true); props.onFocus?.(e); }}
        onBlur={e => { setFocused(false); props.onBlur?.(e); }}
      />
      {props.error && <span style={{ fontSize: 11, color: 'var(--magenta-light)', marginTop: 4, display: 'block' }}>{props.error}</span>}
    </label>
  );
}

// ─── Progress bar ────────────────────────────────────────────────────────────

function ProgressBar({ step }) {
  const steps = ['Conta', 'Pagamento'];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 32 }}>
      {steps.map((s, i) => (
        <React.Fragment key={s}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ width: 26, height: 26, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700, fontFamily: 'var(--font-display)', background: i <= step ? 'var(--gradient-sx)' : 'rgba(255,255,255,0.06)', color: i <= step ? '#fff' : 'var(--text-muted)', flexShrink: 0 }}>
              {i < step ? <Icon d={ICONS.check} size={13} /> : i + 1}
            </div>
            <span style={{ fontSize: 13, fontWeight: 600, color: i <= step ? 'var(--text-primary)' : 'var(--text-muted)' }}>{s}</span>
          </div>
          {i < steps.length - 1 && <div style={{ flex: 1, height: 1, background: i < step ? 'var(--purple)' : 'rgba(255,255,255,0.08)', maxWidth: 60 }} />}
        </React.Fragment>
      ))}
    </div>
  );
}

// ─── Resumo do pedido ────────────────────────────────────────────────────────

function fmtPriceCents(cents) {
  return (cents / 100).toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function OrderSummary({ email, product }) {
  const priceStr = fmtPriceCents(product.priceCents);
  const dailyStr = fmtPriceCents(product.priceCents / 30);
  return (
    <div className="card order-summary-card" style={{ padding: 24 }}>
      <span className="ui-label" style={{ color: 'var(--purple-light)' }}>Resumo do pedido</span>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 16, paddingBottom: 16, borderBottom: '1px solid var(--border-subtle)' }}>
        <div>
          <div className="text-gradient-sx" style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18 }}>{product.name.toUpperCase()}</div>
          <div className="ui-caption" style={{ marginTop: 2 }}>1 mês de acesso · renovação automática</div>
        </div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', margin: '16px 0 6px', fontSize: 14, color: 'var(--text-secondary)' }}>
        <span>Assinatura mensal</span><span style={{ color: 'var(--text-primary)' }}>R$ {priceStr}</span>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--text-muted)', marginBottom: 16 }}>
        <span>Equivale a</span><span>R$ {dailyStr}/dia</span>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', paddingTop: 16, borderTop: '1px solid var(--border-subtle)', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20 }}>
        <span>Total hoje</span><span>R$ {priceStr}</span>
      </div>
      {email && (
        <div className="ui-caption" style={{ marginTop: 14, wordBreak: 'break-all' }}>
          Acesso enviado para <span style={{ color: 'var(--text-secondary)' }}>{email}</span>
        </div>
      )}
      <div style={{ display: 'flex', gap: 8, marginTop: 20, flexWrap: 'wrap' }}>
        {['Compra segura', 'Privacidade protegida', 'Cancele quando quiser'].map(t => (
          <span key={t} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 10, color: 'var(--text-muted)' }}>
            <Icon d={ICONS.lock} size={11} />{t}
          </span>
        ))}
      </div>
    </div>
  );
}

// ─── Step 1 — Conta ──────────────────────────────────────────────────────────

function AccountStep({ data, setData, onNext, product }) {
  const [errors, setErrors] = useState({});
  const [emailStatus, setEmailStatus] = useState('idle'); // idle | checking | new | existing | legacy
  const [loginError, setLoginError] = useState('');
  const [checkingLogin, setCheckingLogin] = useState(false);
  const emailCheckRef = useRef(null);

  // "existing" = já passou pelo checkout novo antes (senha verificável aqui).
  // "legacy" = tem conta antiga no site (a maioria dos nossos usuários hoje) — não dá pra
  // verificar a senha antiga (login do WP tem reCAPTCHA), então tratamos como definir uma
  // senha nova de acesso, que passa a valer para a conta também.
  const isExisting = emailStatus === 'existing';
  const isLegacy = emailStatus === 'legacy';
  const isKnown = isExisting || isLegacy;

  function checkEmail(email) {
    clearTimeout(emailCheckRef.current);
    setLoginError('');
    if (!/^\S+@\S+\.\S+$/.test(email)) { setEmailStatus('idle'); return; }
    setEmailStatus('checking');
    emailCheckRef.current = setTimeout(async () => {
      try {
        const r = await fetch(`/api/checkout/check-email?email=${encodeURIComponent(email)}`);
        const { status } = await r.json();
        setEmailStatus(status || 'new');
      } catch {
        setEmailStatus('idle');
      }
    }, 500);
  }

  function validate() {
    const e = {};
    if (!/^\S+@\S+\.\S+$/.test(data.email))        e.email    = 'Digite um e-mail válido';
    if (data.phone.replace(/\D/g, '').length < 10)  e.phone    = 'Digite um WhatsApp válido com DDD';
    if (isExisting) {
      if (!data.password) e.password = 'Digite sua senha';
    } else {
      if (data.password.length < 6) e.password = 'Mínimo de 6 caracteres';
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  async function handleContinue() {
    if (!validate()) return;
    if (!isExisting) { onNext(); return; }

    // E-mail já cadastrado no checkout novo: confirma a senha antes de prosseguir (evita
    // "criar conta" duplicada e evita anexar uma nova assinatura à conta de outra pessoa).
    setCheckingLogin(true);
    setLoginError('');
    try {
      const r = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: data.email, password: data.password }),
      });
      if (!r.ok) throw new Error();
      onNext();
    } catch {
      setLoginError('Senha incorreta. Tente novamente ou recupere sua senha.');
    } finally {
      setCheckingLogin(false);
    }
  }

  return (
    <div>
      <h2 style={{ marginBottom: 6 }}>{isKnown ? 'Bem-vindo de volta' : 'Crie sua conta'}</h2>
      <p className="body-sm" style={{ marginBottom: 28 }}>
        {isExisting
          ? 'Você já possui cadastro feito no SexyClube. Use a sua senha:'
          : isLegacy
          ? 'Encontramos uma conta sua no Sexy Clube. Crie uma senha de acesso para continuar:'
          : `Seu acesso ao ${product.name} chega neste e-mail assim que o pagamento for confirmado.`}
      </p>
      <Field label="E-mail" type="email" placeholder="voce@email.com" value={data.email} error={errors.email}
        onChange={e => { setData(d => ({ ...d, email: e.target.value })); checkEmail(e.target.value); }} />
      <Field label="WhatsApp" type="tel" placeholder="(11) 91234-5678" value={data.phone} error={errors.phone} onChange={e => setData(d => ({ ...d, phone: fmtPhone(e.target.value) }))} />
      <Field
        label={isExisting ? 'Use a sua senha' : 'Crie uma senha'}
        type="password"
        placeholder={isExisting ? 'Digite sua senha' : 'Mínimo 6 caracteres'}
        value={data.password}
        error={errors.password || loginError}
        onChange={e => { setData(d => ({ ...d, password: e.target.value })); setLoginError(''); }}
      />
      {!isExisting && (
        <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', margin: '4px 0 24px', cursor: 'pointer' }}>
          <input type="checkbox" checked={data.terms} onChange={e => setData(d => ({ ...d, terms: e.target.checked }))} style={{ marginTop: 3, accentColor: 'var(--purple)' }} />
          <span style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>
            Sou maior de 18 anos e concordo com os <a href="#" onClick={e => e.preventDefault()}>Termos de Assinatura</a> e a cobrança recorrente mensal de R$ {fmtPriceCents(product.priceCents)} até o cancelamento.
          </span>
        </label>
      )}
      {isExisting && <div style={{ marginBottom: 24 }} />}
      <SXButton block disabled={(!isExisting && !data.terms) || checkingLogin} onClick={handleContinue}>
        {checkingLogin ? <React.Fragment><Spinner /> Verificando...</React.Fragment> : 'Continuar para pagamento'}
      </SXButton>
    </div>
  );
}

// ─── Bandeiras de cartão ─────────────────────────────────────────────────────

function CardBrandIcons() {
  const brands = ['visa', 'mastercard', 'elo', 'american-express', 'hipercard'];
  return (
    <div style={{ display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap' }}>
      {brands.map(b => (
        <img key={b} src={`assets/cards/${b}.svg`} height="22" alt={b}
          style={{ borderRadius: 4, boxShadow: '0 1px 4px rgba(0,0,0,0.4)', opacity: 0.85 }} />
      ))}
    </div>
  );
}

// ─── Painel PIX ──────────────────────────────────────────────────────────────

function PixRecPanel({ email, phone, onSuccess, product }) {
  const [status, setStatus] = useState('idle'); // idle | loading | waiting | paid | error
  const [pixData, setPixData] = useState(null);
  const [copied, setCopied] = useState(false);
  const [apiError, setApiError] = useState('');
  const [cpf, setCpf] = useState('');
  const [cpfError, setCpfError] = useState('');
  const pollRef = useRef(null);

  useEffect(() => () => clearInterval(pollRef.current), []);

  async function authorize() {
    if (!validCpf(cpf)) { setCpfError('CPF inválido'); return; }
    setCpfError('');
    setStatus('loading');
    setApiError('');
    try {
      const resp = await fetch('/api/checkout/subscribe-pix-rec', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, phone, cpf: cpf.replace(/\D/g, ''), produto: product.slug }),
      });
      const data = await resp.json();
      if (!resp.ok) throw new Error(data.error || 'Erro ao criar assinatura');
      setPixData(data);

      if (data.invoice_id) {
        setStatus('waiting');
        startPolling(data.invoice_id);
      } else {
        // Sem QR code disponível — assinatura criada, e-mail enviado pela IUGU
        setStatus('paid');
        setTimeout(onSuccess, 1000);
      }
    } catch (err) {
      setApiError(err.message);
      setStatus('error');
    }
  }

  function startPolling(invoiceId) {
    pollRef.current = setInterval(async () => {
      try {
        const r = await fetch(`/api/checkout/invoice/${invoiceId}`);
        const { status: s } = await r.json();
        if (s === 'paid') {
          clearInterval(pollRef.current);
          setStatus('paid');
          setTimeout(onSuccess, 800);
        }
      } catch { /* retry */ }
    }, 3000);
  }

  function copyCode() {
    const code = pixData?.pix?.qrcode_text;
    if (!code) return;
    navigator.clipboard?.writeText(code).then(() => { setCopied(true); setTimeout(() => setCopied(false), 2000); });
  }

  function resolveQrSrc(qrcode) {
    if (!qrcode) return null;
    if (qrcode.startsWith('http') || qrcode.startsWith('data:')) return qrcode;
    return `data:image/png;base64,${qrcode}`;
  }

  if (status === 'idle' || status === 'error') {
    return (
      <div>
        <div className="card" style={{ padding: 14, marginBottom: 20, display: 'flex', gap: 12, alignItems: 'flex-start', background: 'rgba(0,194,255,0.06)', border: '1px solid rgba(0,194,255,0.2)' }}>
          <Icon d={ICONS.pix} size={18} />
          <span className="ui-caption" style={{ lineHeight: 1.6 }}>Você paga o primeiro mês agora via PIX. Os próximos ciclos são cobrados automaticamente — cancele quando quiser pela sua conta SX.</span>
        </div>
        <Field label="CPF" placeholder="000.000.000-00" value={cpf} error={cpfError}
          onChange={e => { setCpf(fmtCpf(e.target.value)); setCpfError(''); }} />
        <ErrorBox msg={apiError} />
        <SXButton block onClick={authorize}>Pagar com Pix</SXButton>
      </div>
    );
  }

  if (status === 'loading') {
    return (
      <div style={{ textAlign: 'center', padding: '32px 0' }}>
        <Spinner />
        <p className="ui-caption" style={{ marginTop: 14 }}>Criando assinatura...</p>
      </div>
    );
  }

  const qrSrc = resolveQrSrc(pixData?.pix?.qrcode);
  const qrText = pixData?.pix?.qrcode_text;

  return (
    <div style={{ textAlign: 'center' }}>
      <div style={{ marginBottom: 20 }}>
        <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--blue)', background: 'rgba(0,194,255,0.1)', padding: '4px 12px', borderRadius: 9999, border: '1px solid rgba(0,194,255,0.25)' }}>
          Assinatura criada
        </span>
      </div>

      {qrSrc ? (
        <>
          <p className="body-sm" style={{ marginBottom: 16 }}>Pague o primeiro mês agora para ativar sua assinatura recorrente:</p>
          <img src={qrSrc} width={192} height={192} alt="QR Code PIX"
            style={{ borderRadius: 12, background: '#fff', padding: 10, marginBottom: 20, display: 'block', margin: '0 auto 20px' }} />
          {qrText && (
            <div style={{ display: 'flex', gap: 8, background: 'var(--bg-primary)', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', padding: '10px 14px', marginBottom: 12, textAlign: 'left' }}>
              <span style={{ flex: 1, fontFamily: 'monospace', fontSize: 11, color: 'var(--text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{qrText}</span>
              <button onClick={copyCode} style={{ background: 'none', border: 'none', color: copied ? 'var(--blue)' : 'var(--purple-light)', fontSize: 11, fontWeight: 700, cursor: 'pointer', flexShrink: 0, display: 'flex', alignItems: 'center', gap: 4 }}>
                <Icon d={ICONS.copy} size={12} />{copied ? 'COPIADO!' : 'COPIAR'}
              </button>
            </div>
          )}
          {qrText && qrText.startsWith('http') && (
            <p style={{ fontSize: 11, color: 'var(--text-muted)', marginBottom: 16 }}>
              Ambiente de testes: <a href={qrText} target="_blank" rel="noreferrer" style={{ color: 'var(--blue)' }}>clique aqui para simular o pagamento</a> e aguarde a confirmação abaixo.
            </p>
          )}
          {status === 'waiting' && (
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--text-muted)', marginBottom: 16 }}>
              <Spinner />Aguardando pagamento...
            </div>
          )}
        </>
      ) : (
        <p className="body-sm" style={{ marginBottom: 16 }}>
          Tudo certo! Enviamos um link de pagamento para <strong style={{ color: 'var(--text-primary)' }}>{email}</strong>. Acesse o e-mail para pagar o primeiro mês e ativar sua assinatura.
        </p>
      )}

      <p className="ui-caption">Os próximos meses são cobrados automaticamente. Cancele quando quiser na sua conta SX.</p>
    </div>
  );
}

// ─── Painel Cartão ────────────────────────────────────────────────────────────

function CardPanel({ data, setData, onSuccess, product }) {
  const [errors, setErrors] = useState({});
  const [loading, setLoading] = useState(false);
  const [apiError, setApiError] = useState('');

  function validate() {
    const e = {};
    if (data.cardNumber.replace(/\s/g, '').length < 16) e.cardNumber = 'Número do cartão inválido';
    if (!data.cardName.trim())                           e.cardName   = 'Informe o nome impresso no cartão';
    if (data.cardExpiry.length < 5)                      e.cardExpiry = 'Data inválida';
    if (data.cardCvv.length < 3)                         e.cardCvv   = 'CVV inválido';
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  async function pay() {
    if (!validate()) return;
    setApiError('');
    setLoading(true);

    const nameParts  = data.cardName.trim().split(/\s+/);
    const firstName  = nameParts[0];
    const lastName   = nameParts.slice(1).join(' ') || nameParts[0];
    const [month, year] = data.cardExpiry.split('/');

    try {
      const resp = await fetch('/api/checkout/subscribe-card', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: data.email,
          name: data.cardName,
          phone: data.phone,
          card: {
            number: data.cardNumber,
            firstName,
            lastName,
            month: month?.trim(),
            year: year?.trim(),
            cvv: data.cardCvv,
          },
          produto: product.slug,
        }),
      });
      const result = await resp.json();
      if (!resp.ok) throw new Error(result.error || 'Erro ao processar pagamento');
      onSuccess();
    } catch (err) {
      setApiError(err.message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div>
      <Field label="Número do cartão" placeholder="0000 0000 0000 0000" value={data.cardNumber} error={errors.cardNumber}
        onChange={e => setData(d => ({ ...d, cardNumber: fmtCard(e.target.value) }))} />
      <Field label="Nome impresso no cartão" placeholder="Como está no cartão" value={data.cardName} error={errors.cardName}
        onChange={e => setData(d => ({ ...d, cardName: e.target.value.toUpperCase() }))} />
      <div style={{ display: 'flex', gap: 12 }}>
        <div style={{ flex: 1 }}>
          <Field label="Validade" placeholder="MM/AA" value={data.cardExpiry} error={errors.cardExpiry}
            onChange={e => setData(d => ({ ...d, cardExpiry: fmtExpiry(e.target.value) }))} />
        </div>
        <div style={{ flex: 1 }}>
          <Field label="CVV" placeholder="123" value={data.cardCvv} error={errors.cardCvv}
            onChange={e => setData(d => ({ ...d, cardCvv: e.target.value.replace(/\D/g, '').slice(0, 4) }))} />
        </div>
      </div>
      <CardBrandIcons />
      <p className="ui-caption" style={{ marginTop: 14, marginBottom: 4 }}>
        Cobrança recorrente de R$ {fmtPriceCents(product.priceCents)}/mês no cartão até o cancelamento.
      </p>
      <p className="ui-caption" style={{ marginBottom: 4, opacity: 0.6 }}>
        Teste: Visa 4111 1111 1111 1111 · Master 5500 0000 0000 0004 · CVV qualquer · validade futura
      </p>
      <ErrorBox msg={apiError} />
      <SXButton block onClick={pay} disabled={loading} style={{ marginTop: 8 }}>
        {loading ? <React.Fragment><Spinner /> Processando...</React.Fragment> : 'Confirmar assinatura'}
      </SXButton>
    </div>
  );
}

// ─── Step 2 — Pagamento ───────────────────────────────────────────────────────

function PaymentStep({ data, setData, onBack, onSuccess, iuguReady, product }) {
  const [method, setMethod] = useState('card');

  const tabs = [
    { id: 'card',    label: 'Cartão de Crédito', icon: ICONS.card },
    { id: 'pix-rec', label: 'Pix',               icon: ICONS.pix  },
  ];

  return (
    <div>
      <h2 style={{ marginBottom: 6 }}>Forma de pagamento</h2>
      <p className="body-sm" style={{ marginBottom: 24 }}>Processado com segurança via IUGU.</p>

      <div style={{ display: 'flex', gap: 8, marginBottom: 24, flexWrap: 'wrap' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setMethod(t.id)} style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '10px 16px', borderRadius: 9999, fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'var(--font-ui)', border: `1px solid ${method === t.id ? 'var(--border-brand)' : 'var(--border-default)'}`, background: method === t.id ? 'rgba(123,63,242,0.14)' : 'transparent', color: method === t.id ? 'var(--purple-light)' : 'var(--text-secondary)', transition: 'all .15s' }}>
            <Icon d={t.icon} size={14} />{t.label}
          </button>
        ))}
      </div>

      {method === 'card' && (
        <CardPanel data={data} setData={setData} onSuccess={onSuccess} product={product} />
      )}
      {method === 'pix-rec' && (
        <PixRecPanel email={data.email} phone={data.phone} onSuccess={onSuccess} product={product} />
      )}

      <button onClick={onBack} style={{ display: 'flex', alignItems: 'center', gap: 4, background: 'none', border: 'none', color: 'var(--text-muted)', fontSize: 13, cursor: 'pointer', marginTop: 20 }}>
        <span style={{ transform: 'rotate(180deg)', display: 'inline-flex' }}><Icon d={ICONS.chevron} size={14} /></span> Voltar
      </button>
    </div>
  );
}

// ─── Tela de sucesso ──────────────────────────────────────────────────────────

const PROJETO_NAMES = { sxclube: 'Sexy Clube', papo: 'Papo com Pijama', pimentinhas: 'Pimentinhas', casapim: 'Casa das Pimentinhas' };

function SuccessScreen({ email, onHome, product }) {
  const [going, setGoing] = useState(false);
  const accessBadges = product.kind === 'combo'
    ? product.projetos.map(p => PROJETO_NAMES[p] || p)
    : [product.name];

  async function goToMembers() {
    setGoing(true);
    try {
      const r = await fetch(`/api/checkout/wp-login-url?email=${encodeURIComponent(email)}`);
      const { url } = await r.json();
      if (url) { window.location.href = url; return; }
    } catch { /* cai no fallback abaixo */ }
    setGoing(false);
    onHome();
  }

  return (
    <div style={{ maxWidth: 480, margin: '0 auto', textAlign: 'center', padding: '60px 24px' }}>
      <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--gradient-sx)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 24px', boxShadow: 'var(--glow-purple)' }}>
        <Icon d={ICONS.check} size={30} />
      </div>
      <h1 style={{ fontSize: 'var(--text-3xl)', marginBottom: 10 }}>Assinatura confirmada</h1>
      <p className="body-lg" style={{ marginBottom: 28 }}>
        Seu {product.name} está ativo. Enviamos os detalhes de acesso para{' '}
        <strong style={{ color: 'var(--text-primary)' }}>{email || 'seu e-mail'}</strong>.
      </p>
      <div className="card" style={{ padding: 20, textAlign: 'left', marginBottom: 28 }}>
        {[['Plano', product.name], ['Cobrança', `R$ ${fmtPriceCents(product.priceCents)}/mês`]].map(([k, v]) => (
          <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid var(--border-subtle)', fontSize: 13 }}>
            <span style={{ color: 'var(--text-muted)' }}>{k}</span>
            <span style={{ color: 'var(--text-primary)', fontWeight: 600 }}>{v}</span>
          </div>
        ))}
        <div style={{ padding: '10px 0 2px' }}>
          <span style={{ display: 'block', color: 'var(--text-muted)', fontSize: 13, marginBottom: 8 }}>Acesso incluído</span>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {accessBadges.map(t => (
              <span key={t} style={{ fontSize: 11, fontWeight: 600, padding: '5px 10px', borderRadius: 9999, background: 'rgba(123,63,242,0.14)', border: '1px solid rgba(123,63,242,0.3)', color: 'var(--purple-light)' }}>{t}</span>
            ))}
          </div>
        </div>
      </div>
      {going && (
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10, textAlign: 'left',
          padding: '14px 16px', borderRadius: 'var(--radius-md)', marginBottom: 16,
          background: 'rgba(123,63,242,0.1)', border: '1px solid rgba(123,63,242,0.3)',
        }}>
          <Spinner />
          <span style={{ fontSize: 13, color: 'var(--text-primary)', lineHeight: 1.4 }}>
            <strong>Continue nesta tela</strong> — você está sendo redirecionado para o conteúdo
            de <strong>ASSINANTES SexyClube</strong>...
          </span>
        </div>
      )}
      <SXButton block onClick={goToMembers} disabled={going}>
        {going ? <React.Fragment><Spinner /> Redirecionando...</React.Fragment> : 'Acessar minha conta'}
      </SXButton>
    </div>
  );
}

// ─── Fluxo principal ──────────────────────────────────────────────────────────

function CheckoutFlow({ onExit }) {
  const [step, setStep]         = useState(0);
  const [iuguReady, setIuguReady] = useState(false);
  const [productList, setProductList] = useState(null);
  const [data, setData]         = useState({
    email: '', phone: '', password: '', terms: false,
    cardNumber: '', cardName: '', cardExpiry: '', cardCvv: '',
  });

  // Inicializa IUGU.js com account_id do backend
  useEffect(() => {
    fetch('/api/config')
      .then(r => r.json())
      .then(cfg => {
        const Iugu = window.Iugu;
        if (Iugu && cfg.iugu_account_id) {
          Iugu.setAccountID(cfg.iugu_account_id);
          if (cfg.test_mode) Iugu.setTestMode(true);
          setIuguReady(true);
        }
      })
      .catch(() => {}); // degradação graciosa se o servidor não estiver disponível
  }, []);

  // Resolve o produto a partir de ?produto= na URL — funciona como destino autônomo,
  // sem depender de navegação prévia no site (link vem de fora do domínio também).
  useEffect(() => {
    fetch('/api/products')
      .then(r => r.json())
      .then(setProductList)
      .catch(() => setProductList([]));
  }, []);

  if (!productList) {
    return (
      <div style={{ minHeight: '100vh', background: 'var(--bg-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Spinner />
      </div>
    );
  }

  const produtoParam = new URLSearchParams(window.location.search).get('produto');
  const product = productList.find(p => p.slug === produtoParam) || productList.find(p => p.slug === 'combo_premium') || productList[0];

  if (step === 2) {
    return (
      <div style={{ minHeight: '100vh', background: 'var(--bg-primary)' }}>
        <SuccessScreen email={data.email} onHome={onExit} product={product} />
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg-primary)' }}>
      <div className="checkout-header" style={{ maxWidth: 1440, margin: '0 auto', padding: '0 24px' }}>
        <div style={{ height: 64, display: 'flex', alignItems: 'center', borderBottom: '1px solid var(--border-subtle)' }}>
          <button onClick={onExit} style={{ background: 'none', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10 }}>
            <img src="assets/Logo-Sexy.svg" height="18" style={{ filter: 'brightness(0) invert(1)' }} alt="SEXY" />
            <span style={{ width: 1, height: 14, background: 'rgba(255,255,255,0.15)' }} />
            <span className="text-gradient-sx" style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15 }}>SX</span>
          </button>
        </div>
      </div>

      <div className="checkout-body" style={{ maxWidth: 900, margin: '0 auto', padding: '48px 24px 100px', display: 'grid', gridTemplateColumns: 'minmax(0,1.3fr) minmax(240px,1fr)', gap: 48 }}>
        <div>
          <ProgressBar step={step} />
          {step === 0 && (
            <AccountStep data={data} setData={setData} onNext={() => { setStep(1); window.scrollTo(0, 0); }} product={product} />
          )}
          {step === 1 && (
            <PaymentStep
              data={data}
              setData={setData}
              iuguReady={iuguReady}
              onBack={() => setStep(0)}
              onSuccess={() => { setStep(2); window.scrollTo(0, 0); }}
              product={product}
            />
          )}
        </div>
        <div><OrderSummary email={data.email} product={product} /></div>
      </div>
    </div>
  );
}

window.CheckoutFlow = CheckoutFlow;
