// Checkout — PIX + cartão de crédito, otimizado para conversão BR

function Checkout({ navigate, initialPlan }) {
  const [method, setMethod] = useState('pix'); // pix | card
  const [planId, setPlanId] = useState(initialPlan || 'profissional');
  const [installments, setInstallments] = useState(1);
  const [coupon, setCoupon] = useState('');
  const [couponApplied, setCouponApplied] = useState(false);
  const [form, setForm] = useState({
    cardName:'', cardNumber:'', exp:'', cvv:'',
    cpf:'', email: USER.email, name: USER.name, phone:'',
    cep:'', address:'', city:'', state:'',
  });
  const [phase, setPhase] = useState('form'); // form | processing | pix-waiting | done
  const [error, setError] = useState(null);
  const [pixPayload, setPixPayload] = useState(null);
  const [completedOrderId, setCompletedOrderId] = useState(null);

  const plan = PLANS.find(p => p.id === planId) || PLANS[1];
  const price = plan.price;
  const discount = couponApplied ? Math.round(price * 0.1) : 0;
  const total = price - discount;

  const submit = async (e) => {
    e?.preventDefault?.();
    if (!form.name || !form.cpf || !form.email) {
      setError('Preencha seus dados de identificação.');
      return;
    }
    setError(null);
    setPhase('processing');

    try {
      // ── Tokenização do cartão no frontend (PCI-DSS compliant) ──
      // O número, CVV e validade NUNCA passam pelo nosso servidor.
      let cardToken = undefined;
      if (method === 'card') {
        if (!form.cardNumber || !form.exp || !form.cvv || !form.cardName) {
          setError('Preencha todos os dados do cartão.');
          setPhase('form');
          return;
        }
        const [mm, yy] = String(form.exp).split('/');
        try {
          cardToken = await window.DB.tokenizeCard({
            number: form.cardNumber,
            holderName: form.cardName,
            expMonth: parseInt(mm, 10),
            expYear: parseInt('20' + yy, 10),
            cvv: form.cvv,
          });
        } catch (tokenErr) {
          setError('Erro ao processar cartão: ' + tokenErr.message);
          setPhase('form');
          return;
        }
      }

      const payload = {
        planId: plan.id,
        method,
        coupon: couponApplied ? coupon : null,
        installments,
        customer: {
          name: form.name,
          email: form.email,
          cpf: form.cpf,
          phone: form.phone,
          cep: form.cep,
          address: form.address,
          city: form.city,
          state: form.state,
        },
        // Envia APENAS o token — sem número, CVV ou validade
        cardToken: method === 'card' ? cardToken : undefined,
      };
      const data = await window.DB.createOrder(payload);

      if (method === 'pix') {
        setPixPayload({
          qr_code: data.qr_code,
          qr_code_url: data.qr_code_url,
          id: data.orderId,
        });
        setCompletedOrderId(data.orderId);
        setPhase('pix-waiting');
      } else {
        if (data.status === 'paid') {
          setCompletedOrderId(data.orderId);
          await window.DB.loadSession();
          setPhase('done');
        } else {
          throw new Error('Pagamento não aprovado. Status: ' + data.status);
        }
      }
    } catch (err) {
      console.error(err);
      setError(err.message);
      setPhase('form');
    }
  };

  if (phase === 'done') return <Success navigate={navigate} plan={plan} total={total} method={method} orderId={completedOrderId}/>;

  return (
    <div style={{ minHeight:'100dvh', background:'var(--bg)', display:'flex', flexDirection:'column' }}>
      <CheckoutNav navigate={navigate}/>

      <div className="m-single-col m-section" style={{ flex: 1, display:'grid', gridTemplateColumns:'1.3fr 1fr', maxWidth: 1240, width:'100%', margin:'0 auto', padding:'32px 32px 48px', gap: 40 }}>

        {/* LEFT — form */}
        <div>
          <div style={{ marginBottom: 24 }}>
            <button onClick={() => navigate('#/signup')} className="tap-fade" style={{ fontSize: 13, color:'var(--ink-3)', display:'flex', alignItems:'center', gap: 6, marginBottom: 14 }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M15 6l-6 6 6 6"/></svg>
              Voltar
            </button>
            <h1 className="serif m-h1" style={{ fontSize: 52, lineHeight: 1, margin: 0, letterSpacing:'-0.015em' }}>
              Finalizar compra
            </h1>
            <p style={{ color:'var(--ink-3)', fontSize: 15, marginTop: 10, maxWidth: 520 }}>
              Pagamento único. Sem mensalidade, sem renovação automática.
            </p>
          </div>

          {error && (
            <div style={{
              marginBottom: 20, padding: '12px 16px', borderRadius: 10,
              background:'#FDECE7', border:'1px solid #E8B7A5', color:'#7A2E18',
              display:'flex', alignItems:'center', justifyContent:'space-between', gap: 12,
            }}>
              <span style={{ fontSize: 13 }}>{error}</span>
              <button onClick={() => setError(null)} style={{ fontSize: 12, color:'#7A2E18', padding: '4px 8px' }}>Fechar</button>
            </div>
          )}

          {/* Method selector */}
          <section style={sectionStyle}>
            <SectionHeader num="01" title="Como você quer pagar?"/>
            <div className="m-stack-2" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap: 12 }}>
              <MethodCard
                active={method==='pix'} onClick={() => setMethod('pix')}
                icon={<PixIcon/>}
                title="PIX"
                desc="Pagamento instantâneo"
                badge={<span style={badgeGreen}>Mais rápido</span>}
                sub="Aprovação em segundos"
              />
              <MethodCard
                active={method==='card'} onClick={() => setMethod('card')}
                icon={<CardIcon/>}
                title="Cartão de crédito"
                desc="Visa, Master, Elo, Amex"
                badge={<span style={badgeNeutral}>em até 12x</span>}
                sub="Parcele sem juros · cobrança única"
              />
            </div>
          </section>

          {/* Payment details */}
          <section style={sectionStyle}>
            <SectionHeader num="02" title={method==='pix' ? 'Seus dados' : 'Dados do cartão'}/>

            {method === 'card' && (
              <div style={{ display:'flex', flexDirection:'column', gap: 12 }}>
                <Field label="Número do cartão">
                  <div style={{ position:'relative' }}>
                    <input
                      value={form.cardNumber}
                      onChange={e => setForm({...form, cardNumber: formatCard(e.target.value)})}
                      placeholder="1234 5678 9012 3456"
                      style={{...fieldInput, letterSpacing:'.04em', fontFamily:'var(--mono)', paddingRight: 110 }}
                      maxLength={19}
                    />
                    <div style={{
                      position:'absolute', right: 10, top:'50%', transform:'translateY(-50%)',
                      display:'flex', gap: 4, pointerEvents:'none',
                    }}>
                      <BrandChip label="VISA"/><BrandChip label="MC" bg="#EB001B"/><BrandChip label="ELO" bg="#1B1B1B"/>
                    </div>
                  </div>
                </Field>
                <Field label="Nome impresso no cartão">
                  <input value={form.cardName} onChange={e => setForm({...form, cardName: e.target.value.toUpperCase()})}
                    placeholder="COMO ESTÁ NO CARTÃO" style={{...fieldInput, textTransform:'uppercase', letterSpacing:'.02em'}}/>
                </Field>
                <div className="m-stack-2" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap: 12 }}>
                  <Field label="Validade">
                    <input value={form.exp} onChange={e => setForm({...form, exp: formatExp(e.target.value)})}
                      placeholder="MM/AA" style={{...fieldInput, fontFamily:'var(--mono)'}} maxLength={5}/>
                  </Field>
                  <Field label="CVV" right={<span title="3 dígitos no verso" style={{ color:'var(--ink-3)', fontSize: 12 }}>ⓘ</span>}>
                    <input value={form.cvv} onChange={e => setForm({...form, cvv: e.target.value.replace(/\D/g,'').slice(0,4)})}
                      placeholder="123" style={{...fieldInput, fontFamily:'var(--mono)'}} maxLength={4}/>
                  </Field>
                </div>
                <Field label="Parcelas">
                  <select value={installments} onChange={e => setInstallments(+e.target.value)}
                    style={{...fieldInput, appearance:'none', backgroundImage:'linear-gradient(45deg, transparent 50%, var(--ink-3) 50%), linear-gradient(135deg, var(--ink-3) 50%, transparent 50%)', backgroundPosition:'calc(100% - 20px) 50%, calc(100% - 15px) 50%', backgroundSize:'5px 5px', backgroundRepeat:'no-repeat'}}>
                    {[1,2,3,4,6,10,12].map(n => {
                      const parc = (total / n);
                      const suffix = n === 1 ? `R$ ${total.toFixed(2).replace('.',',')} à vista` : `${n}x de R$ ${parc.toFixed(2).replace('.',',')} sem juros`;
                      return <option key={n} value={n}>{suffix}</option>;
                    })}
                  </select>
                </Field>
              </div>
            )}

            {method === 'pix' && phase !== 'pix-waiting' && (
              <div style={{
                padding: 18, background:'var(--accent-soft)', border:'1px solid var(--accent)',
                borderRadius: 12, display:'flex', gap: 14, alignItems:'flex-start',
              }}>
                <div style={{ width: 36, height: 36, borderRadius: 8, background:'#fff', display:'flex', alignItems:'center', justifyContent:'center', flexShrink: 0 }}>
                  <PixIcon size={22}/>
                </div>
                <div style={{ fontSize: 13, color:'var(--ink-2)', lineHeight: 1.5 }}>
                  Ao clicar em <b>gerar PIX</b>, mostramos um QR Code e código para copiar. A confirmação chega em segundos e sua conta é ativada automaticamente.
                </div>
              </div>
            )}

            {method === 'pix' && phase === 'pix-waiting' && (
              <PixWaiting pixPayload={pixPayload} onPaid={async () => {
                await window.DB.loadSession();
                setPhase('done');
              }}/>
            )}
          </section>

          {/* Identification */}
          {phase !== 'pix-waiting' && (
            <section style={sectionStyle}>
              <SectionHeader num="03" title="Identificação (nota fiscal)"/>
            <div className="m-stack" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap: 12 }}>
                <Field label="Nome completo">
                  <input value={form.name} onChange={e => setForm({...form, name: e.target.value})} style={fieldInput}/>
                </Field>
                <Field label="CPF">
                  <input value={form.cpf} onChange={e => setForm({...form, cpf: formatCPF(e.target.value)})}
                    placeholder="000.000.000-00" style={{...fieldInput, fontFamily:'var(--mono)'}} maxLength={14}/>
                </Field>
                <Field label="E-mail">
                  <input type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} style={fieldInput}/>
                </Field>
                <Field label="Celular (WhatsApp)">
                  <input value={form.phone} onChange={e => setForm({...form, phone: formatPhone(e.target.value)})}
                    placeholder="(11) 98765-4321" style={{...fieldInput, fontFamily:'var(--mono)'}} maxLength={15}/>
                </Field>
                <Field label="CEP">
                  <input value={form.cep} onChange={e => setForm({...form, cep: e.target.value.replace(/\D/g,'').slice(0,8)})}
                    placeholder="00000-000" style={{...fieldInput, fontFamily:'var(--mono)'}} maxLength={9}/>
                </Field>
                <Field label="Endereço (rua e número)">
                  <input value={form.address} onChange={e => setForm({...form, address: e.target.value})}
                    placeholder="Rua das Flores, 123" style={fieldInput}/>
                </Field>
                <Field label="Cidade">
                  <input value={form.city} onChange={e => setForm({...form, city: e.target.value})} style={fieldInput}/>
                </Field>
                <Field label="Estado (UF)">
                  <input value={form.state} onChange={e => setForm({...form, state: e.target.value.toUpperCase().slice(0,2)})}
                    placeholder="SP" style={{...fieldInput, fontFamily:'var(--mono)', textTransform:'uppercase'}} maxLength={2}/>
                </Field>
              </div>
            </section>
          )}

          {phase !== 'pix-waiting' && (
            <div style={{ marginTop: 24 }}>
              <Button variant="primary" size="lg" onClick={submit}
                style={{ width:'100%', justifyContent:'center', padding:'16px 20px', fontSize: 16 }}>
                {method === 'pix'
                  ? <>Gerar PIX de R$ {total.toFixed(2).replace('.',',')} <Icons.Arrow size={16}/></>
                  : phase === 'processing'
                    ? <>Processando...</>
                    : <>Finalizar assinatura · R$ {total.toFixed(2).replace('.',',')} <Icons.Arrow size={16}/></>
                }
              </Button>
              <div style={{ display:'flex', alignItems:'center', gap: 8, marginTop: 12, fontSize: 12, color:'var(--ink-3)', justifyContent:'center' }}>
                <LockIcon/> Pagamento protegido · criptografia SSL · conformidade PCI DSS
              </div>
            </div>
          )}
        </div>

        {/* RIGHT — order summary */}
        <aside className="m-aside-static" style={{ position:'sticky', top: 32, alignSelf:'start' }}>
          <div style={{
            background:'var(--paper)', border:'1px solid var(--line)', borderRadius: 18,
            overflow:'hidden', boxShadow:'var(--shadow-sm)',
          }}>
            <div style={{ padding:'18px 20px', borderBottom:'1px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'space-between', gap: 10 }}>
              <span className="serif" style={{ fontSize: 22, whiteSpace:'nowrap' }}>Resumo do pedido</span>
              <span style={{ flexShrink: 0 }}>
                <Pill tone="olive"><Icons.Check size={11}/>&nbsp;Pagamento único</Pill>
              </span>
            </div>

            {/* Plan switcher */}
            <div style={{ padding: 18, borderBottom:'1px solid var(--line)' }}>
              <div style={{ fontSize: 11, color:'var(--ink-3)', letterSpacing:'.08em', textTransform:'uppercase', marginBottom: 10 }}>Pacote</div>
              <div style={{ display:'flex', flexDirection:'column', gap: 8 }}>
                {PLANS.map(p => (
                  <button key={p.id} onClick={() => setPlanId(p.id)} style={{
                    display:'flex', alignItems:'center', gap: 10, padding:'10px 12px', borderRadius: 10,
                    border: '1.5px solid ' + (planId===p.id ? 'var(--accent)' : 'var(--line)'),
                    background: planId===p.id ? 'var(--accent-soft)' : 'var(--paper)',
                    textAlign:'left',
                  }}>
                    <div style={{
                      width: 16, height: 16, borderRadius:'50%',
                      border:'2px solid ' + (planId===p.id ? 'var(--accent)' : 'var(--line-2)'),
                      display:'flex', alignItems:'center', justifyContent:'center', flexShrink: 0,
                    }}>
                      {planId===p.id && <div style={{ width: 7, height: 7, borderRadius:'50%', background:'var(--accent)' }}/>}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 600, fontSize: 13 }}>{p.name}</div>
                      <div style={{ fontSize: 11, color:'var(--ink-3)' }}>{p.enterprise ? 'Sob demanda' : `${p.credits} créditos`}</div>
                    </div>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>R$ {p.price}</div>
                  </button>
                ))}
              </div>
              <div style={{ display:'flex', alignItems:'center', gap: 8, marginTop: 12, padding:'8px 10px', background:'var(--bg-warm)', border:'1px dashed var(--line-2)', borderRadius: 8, fontSize: 11, color:'var(--ink-3)' }}>
                <Icons.Clock size={12}/> Créditos não expiram · use quando quiser
              </div>
            </div>

            {/* Breakdown */}
            <div style={{ padding: 18, borderBottom:'1px solid var(--line)', display:'flex', flexDirection:'column', gap: 10 }}>
              <Row k={`${plan.name} · ${plan.credits} créditos`} v={`R$ ${price.toFixed(2).replace('.',',')}`}/>
              {couponApplied && (
                <Row k={`Cupom ${coupon}`} v={`-R$ ${discount.toFixed(2).replace('.',',')}`} color="var(--olive)"/>
              )}
            </div>

            {/* Coupon */}
            <div style={{ padding: 18, borderBottom:'1px solid var(--line)' }}>
              {!couponApplied ? (
                <div style={{ display:'flex', gap: 8 }}>
                  <input
                    value={coupon} onChange={e => setCoupon(e.target.value.toUpperCase())}
                    placeholder="Cupom de desconto"
                    style={{...fieldInput, flex: 1, padding:'10px 12px', fontSize: 13}}/>
                  <Button variant="secondary" size="sm" onClick={() => coupon && setCouponApplied(true)}>Aplicar</Button>
                </div>
              ) : (
                <div style={{
                  display:'flex', alignItems:'center', justifyContent:'space-between',
                  padding:'10px 12px', background:'#EAF2E4', border:'1px solid var(--olive)',
                  borderRadius: 10,
                }}>
                  <div style={{ display:'flex', alignItems:'center', gap: 8, fontSize: 13, color:'var(--olive)' }}>
                    <Icons.Check size={14}/> Cupom <b>{coupon}</b> aplicado
                  </div>
                  <button onClick={() => { setCoupon(''); setCouponApplied(false); }}
                    style={{ color:'var(--olive)', padding: 2 }}><Icons.X size={14}/></button>
                </div>
              )}
            </div>

            {/* Total */}
            <div style={{ padding: 20, background:'var(--bg-warm)' }}>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
                <div>
                  <div style={{ fontSize: 12, color:'var(--ink-3)' }}>Total a pagar</div>
                  <div style={{ fontSize: 11, color:'var(--ink-3)', marginTop: 2 }}>
                    Cobrança única · sem renovação
                  </div>
                </div>
                <div style={{ textAlign:'right' }}>
                  <div className="serif" style={{ fontSize: 36, lineHeight: 1, letterSpacing:'-0.02em' }}>
                    R$ {total.toFixed(2).replace('.',',')}
                  </div>
                  {method==='card' && installments > 1 && (
                    <div style={{ fontSize: 11, color:'var(--ink-3)', marginTop: 4 }}>
                      ou {installments}x de R$ {(total/installments).toFixed(2).replace('.',',')} sem juros
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* Trust badges */}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap: 10, marginTop: 14 }}>
            <TrustBadge icon={<LockIcon/>} title="Pagamento seguro" desc="Criptografia SSL 256-bit"/>
            <TrustBadge icon={<ShieldIcon/>} title="Garantia 30 dias" desc="Reembolso sem perguntas"/>
          </div>

          {/* Social proof */}
          <div style={{
            marginTop: 14, padding: 16, background:'var(--paper)', border:'1px solid var(--line)',
            borderRadius: 14, fontSize: 13, color:'var(--ink-2)',
          }}>
            <div style={{ display:'flex', alignItems:'center', gap: 8, marginBottom: 8 }}>
              <div style={{ display:'flex' }}>
                {[1,2,3,4,5].map(i => <svg key={i} width="14" height="14" viewBox="0 0 24 24" fill="var(--accent)"><path d="M12 3l2.8 6 6.2.9-4.5 4.3 1 6.3L12 17.8 6.5 20.5l1-6.3L3 9.9 9.2 9z"/></svg>)}
              </div>
              <span style={{ fontSize: 12, color:'var(--ink-3)' }}>4.9 · 2.340 anfitriões</span>
            </div>
            <div style={{ fontStyle:'italic', lineHeight: 1.5 }}>
              "Paguei no PIX e em 5 minutos estava editando. Já recuperei o investimento no primeiro fim de semana."
            </div>
            <div style={{ fontSize: 12, color:'var(--ink-3)', marginTop: 8 }}>— Beatriz R., Ubatuba</div>
          </div>
        </aside>
      </div>
    </div>
  );
}

// --- Sub-components ---

function CheckoutNav({ navigate }) {
  return (
    <nav className="m-nav" style={{
      display:'flex', alignItems:'center', justifyContent:'space-between',
      padding: '20px 32px', borderBottom:'1px solid var(--line)',
      paddingTop: 'calc(14px + var(--safe-top))',
      position:'sticky', top: 0, zIndex: 40,
      background:'rgba(245,241,235,.92)', backdropFilter:'blur(12px)', WebkitBackdropFilter:'blur(12px)',
    }}>
      <button onClick={() => navigate('#/landing')} style={{ display:'flex', alignItems:'center', gap: 10 }}>
        <AftershotMark/>
        <span className="serif" style={{ fontSize: 22 }}>Aftershot</span>
      </button>
      <div className="hide-mobile" style={{ display:'flex', alignItems:'center', gap: 14, fontSize: 12, color:'var(--ink-3)' }}>
        <LockIcon/> <span>Ambiente seguro</span>
        <span>·</span>
        <span>Precisa de ajuda? <a href="mailto:contato@aftershot.com.br" style={{ color:'var(--ink-2)', textDecoration:'underline' }}>contato@aftershot.com.br</a></span>
      </div>
      <div className="show-mobile" style={{ display:'none', alignItems:'center', gap: 6, fontSize: 12, color:'var(--ink-3)' }}>
        <LockIcon/> <span>Seguro</span>
      </div>
    </nav>
  );
}

function SectionHeader({ num, title }) {
  return (
    <div style={{ display:'flex', alignItems:'baseline', gap: 12, marginBottom: 14, flexWrap:'nowrap' }}>
      <span className="mono" style={{
        fontSize: 11, color:'var(--accent)', letterSpacing:'.08em',
        padding:'3px 7px', background:'var(--accent-soft)', borderRadius: 6,
        flexShrink: 0, whiteSpace:'nowrap',
      }}>{num}</span>
      <span className="serif" style={{ fontSize: 22, whiteSpace:'nowrap', lineHeight: 1.15 }}>{title}</span>
    </div>
  );
}

function MethodCard({ active, onClick, icon, title, desc, badge, sub }) {
  return (
    <button onClick={onClick} style={{
      padding: 16, borderRadius: 14, textAlign:'left',
      border: '1.5px solid ' + (active ? 'var(--ink)' : 'var(--line)'),
      background: active ? 'var(--paper)' : 'var(--paper)',
      boxShadow: active ? 'var(--shadow-md)' : 'none',
      display:'flex', flexDirection:'column', gap: 10,
      position:'relative', minHeight: 120,
    }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
        <div style={{
          width: 40, height: 40, borderRadius: 10,
          background: active ? 'var(--bg-warm)' : 'var(--bg-warm)',
          display:'flex', alignItems:'center', justifyContent:'center',
        }}>{icon}</div>
        {badge}
      </div>
      <div>
        <div style={{ fontWeight: 600, fontSize: 15 }}>{title}</div>
        <div style={{ fontSize: 12, color:'var(--ink-3)', marginTop: 2 }}>{desc}</div>
        <div style={{ fontSize: 11, color:'var(--ink-4)', marginTop: 6 }}>{sub}</div>
      </div>
      {active && (
        <div style={{
          position:'absolute', top: 10, right: 10, width: 18, height: 18,
          background:'var(--ink)', color:'white', borderRadius:'50%',
          display:'flex', alignItems:'center', justifyContent:'center',
        }}><Icons.Check size={11}/></div>
      )}
    </button>
  );
}

function Row({ k, v, color }) {
  return (
    <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', fontSize: 13 }}>
      <span style={{ color:'var(--ink-3)' }}>{k}</span>
      <span style={{ fontWeight: 500, color: color || 'var(--ink)' }}>{v}</span>
    </div>
  );
}

function TrustBadge({ icon, title, desc }) {
  return (
    <div style={{
      padding: 12, background:'var(--paper)', border:'1px solid var(--line)', borderRadius: 10,
      display:'flex', gap: 10, alignItems:'center',
    }}>
      <div style={{ color:'var(--olive)', flexShrink: 0 }}>{icon}</div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 12, fontWeight: 600 }}>{title}</div>
        <div style={{ fontSize: 11, color:'var(--ink-3)', marginTop: 1 }}>{desc}</div>
      </div>
    </div>
  );
}

function BrandChip({ label, bg = '#1A1F71' }) {
  return (
    <span style={{
      fontSize: 9, fontWeight: 700, letterSpacing:'.04em',
      padding:'3px 5px', borderRadius: 3, color:'white', background: bg,
    }}>{label}</span>
  );
}

function PixWaiting({ pixPayload, onPaid }) {
  const [seconds, setSeconds] = useState(600);
  useEffect(() => {
    if (seconds <= 0) return;
    const t = setTimeout(() => setSeconds(s => s - 1), 1000);
    return () => clearTimeout(t);
  }, [seconds]);

  useEffect(() => {
    if (!pixPayload?.id) return;
    let cancelled = false;
    const tick = async () => {
      if (cancelled) return;
      try {
        const data = await window.DB.pollOrder(pixPayload.id);
        if (data.status === 'paid') {
          cancelled = true;
          await window.DB.loadSession();
          onPaid();
          return;
        }
      } catch (e) {
        console.warn('[pix-poll]', e.message);
      }
      if (!cancelled) setTimeout(tick, 4000);
    };
    setTimeout(tick, 4000);
    return () => { cancelled = true; };
  }, [pixPayload]);

  const mm = String(Math.floor(seconds/60)).padStart(2,'0');
  const ss = String(seconds % 60).padStart(2,'0');
  const code = pixPayload?.qr_code || 'Gerando...';
  const [copied, setCopied] = useState(false);
  const [checking, setChecking] = useState(false);
  const [checkMsg, setCheckMsg] = useState(null);

  const checkNow = async () => {
    if (!pixPayload?.id) return;
    setChecking(true);
    setCheckMsg(null);
    try {
      const data = await window.DB.pollOrder(pixPayload.id);
      if (data.status === 'paid') {
        onPaid();
      } else {
        setCheckMsg('Pagamento ainda não identificado. Aguarde ou tente de novo em alguns segundos.');
      }
    } catch (e) {
      setCheckMsg('Não foi possível consultar o pagamento. Tente novamente.');
    } finally {
      setChecking(false);
    }
  };

  return (
    <div className="m-stack" style={{ display:'grid', gridTemplateColumns:'240px 1fr', gap: 24, alignItems:'center' }}>
      <div style={{
        aspectRatio: '1/1', background:'white', border:'1px solid var(--line)',
        borderRadius: 12, padding: 12, display:'flex', alignItems:'center', justifyContent:'center',
        maxWidth: 260, margin:'0 auto',
      }}>
        {pixPayload?.qr_code_url ? <img src={pixPayload.qr_code_url} style={{ width:'100%' }} alt="QR Code PIX"/> : <QRPlaceholder/>}
      </div>
      <div>
        <div style={{ display:'flex', alignItems:'center', gap: 8, marginBottom: 10 }}>
          <div style={{ width: 8, height: 8, borderRadius:'50%', background:'var(--accent)', animation:'pulse 1.5s ease-in-out infinite' }}/>
          <span style={{ fontSize: 12, fontWeight: 600, color:'var(--accent)', letterSpacing:'.08em', textTransform:'uppercase' }}>Aguardando pagamento</span>
        </div>
        <style>{`@keyframes pulse { 0%,100% { opacity: 1 } 50% { opacity: .3 } }`}</style>
        <div className="serif" style={{ fontSize: 26, lineHeight: 1.2, marginBottom: 6 }}>
          Escaneie o QR Code no app do seu banco
        </div>
        <div style={{ fontSize: 13, color:'var(--ink-3)', marginBottom: 14 }}>
          Expira em <b className="mono" style={{ color:'var(--ink)' }}>{mm}:{ss}</b>
        </div>
        <div style={{
          background:'var(--bg-warm)', border:'1px solid var(--line)', borderRadius: 10,
          padding: 10, fontSize: 11, fontFamily:'var(--mono)', wordBreak:'break-all', color:'var(--ink-2)',
          marginBottom: 10, lineHeight: 1.4,
        }}>
          {code}
        </div>
        <div style={{ display:'flex', gap: 8 }}>
          <Button variant="primary" size="sm" onClick={() => {
            if (pixPayload?.qr_code) navigator.clipboard.writeText(pixPayload.qr_code);
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
          }}>
            {copied ? <><Icons.Check size={13}/> Copiado!</> : <><CopyIcon/> Copiar código PIX</>}
          </Button>
          <Button variant="secondary" size="sm" onClick={checkNow} disabled={checking}>
            {checking ? 'Verificando...' : 'Já paguei'}
          </Button>
        </div>
        {checkMsg && (
          <div style={{ marginTop: 10, fontSize: 12, color:'var(--ink-3)' }}>{checkMsg}</div>
        )}
      </div>
    </div>
  );
}

function Success({ navigate, plan, total, method, orderId }) {
  const [receiptCode, setReceiptCode] = useState(null);
  const [receiptError, setReceiptError] = useState(null);
  const [loadingReceipt, setLoadingReceipt] = useState(false);

  // Tenta obter o código de recibo. Pode demorar alguns segundos pro backend
  // processar o webhook e gravar — então fazemos retry curto.
  useEffect(() => {
    if (!orderId) return;
    let cancelled = false;
    let attempt = 0;
    const tryFetch = async () => {
      if (cancelled) return;
      attempt++;
      try {
        const data = await window.DB.getReceiptCode(orderId);
        if (data.receipt_code) {
          setReceiptCode(data.receipt_code);
          return;
        }
      } catch (e) {
        if (attempt >= 5) { setReceiptError(e.message); return; }
      }
      if (!cancelled && attempt < 8) setTimeout(tryFetch, 1500);
    };
    tryFetch();
    return () => { cancelled = true; };
  }, [orderId]);

  const openReceipt = async () => {
    if (receiptCode) {
      window.open(`/api/checkout/receipt/${receiptCode}.html`, '_blank');
      return;
    }
    if (!orderId) return;
    setLoadingReceipt(true);
    try {
      const data = await window.DB.getReceiptCode(orderId);
      if (data.receipt_code) {
        setReceiptCode(data.receipt_code);
        window.open(`/api/checkout/receipt/${data.receipt_code}.html`, '_blank');
      } else {
        setReceiptError('Recibo ainda não disponível. Tente novamente em alguns segundos.');
      }
    } catch (e) {
      setReceiptError(e.message);
    } finally {
      setLoadingReceipt(false);
    }
  };

  return (
    <div style={{ minHeight:'100vh', background:'var(--bg)', display:'flex', flexDirection:'column' }}>
      <CheckoutNav navigate={navigate}/>
      <div style={{ flex: 1, display:'flex', alignItems:'center', justifyContent:'center', padding: 40 }}>
        <div style={{ maxWidth: 540, textAlign:'center' }}>
          <div style={{
            width: 80, height: 80, margin:'0 auto 24px', borderRadius:'50%',
            background:'var(--accent)', color:'white',
            display:'flex', alignItems:'center', justifyContent:'center',
            boxShadow:'0 8px 24px -8px rgba(201,100,66,.5)',
          }}>
            <Icons.Check size={40} sw={2.5}/>
          </div>
          <h1 className="serif m-h1" style={{ fontSize: 56, lineHeight: 1, margin:'0 0 14px', letterSpacing:'-0.02em' }}>
            Está tudo certo!
          </h1>
          <p style={{ fontSize: 16, color:'var(--ink-3)', maxWidth: 440, margin:'0 auto 28px', textWrap:'pretty' }}>
            Seu pacote <b style={{color:'var(--ink)'}}>{plan.name}</b> foi liberado.
            Enviamos o recibo para seu e-mail. Já pode começar a editar.
          </p>

          {receiptCode && (
            <div style={{
              maxWidth: 420, margin:'0 auto 24px', padding:'14px 18px',
              background:'var(--accent-soft)', border:'1px dashed var(--accent)', borderRadius: 12,
            }}>
              <div style={{ fontSize: 11, color:'var(--ink-3)', letterSpacing:'.08em', textTransform:'uppercase' }}>
                Código de verificação
              </div>
              <div className="mono" style={{ fontSize: 20, fontWeight: 600, letterSpacing:'.06em', marginTop: 4 }}>
                {receiptCode}
              </div>
            </div>
          )}

          <div style={{
            display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap: 12,
            maxWidth: 480, margin:'0 auto 32px',
          }}>
            {[
              ['Valor pago', `R$ ${total.toFixed(2).replace('.',',')}`],
              ['Método', method === 'pix' ? 'PIX' : 'Cartão'],
              ['Créditos', `${plan.credits}`],
            ].map(([k,v]) => (
              <div key={k} style={{ padding: 14, background:'var(--paper)', border:'1px solid var(--line)', borderRadius: 12 }}>
                <div style={{ fontSize: 11, color:'var(--ink-3)', letterSpacing:'.06em', textTransform:'uppercase' }}>{k}</div>
                <div className="serif" style={{ fontSize: 22, marginTop: 4 }}>{v}</div>
              </div>
            ))}
          </div>
          <div className="m-stack" style={{ display:'flex', gap: 10, justifyContent:'center', flexWrap:'wrap' }}>
            <Button variant="primary" size="lg" onClick={() => navigate('#/dashboard')} className="m-btn-full">
              Editar primeira foto <Icons.Arrow size={16}/>
            </Button>
            <Button variant="secondary" size="lg" onClick={openReceipt} disabled={loadingReceipt || !orderId} className="m-btn-full">
              {loadingReceipt ? 'Carregando…' : 'Baixar recibo'}
            </Button>
          </div>
          {receiptError && (
            <div style={{ marginTop: 14, fontSize: 12, color:'var(--ink-3)' }}>{receiptError}</div>
          )}
        </div>
      </div>
    </div>
  );
}

// --- Icons / helpers ---
function PixIcon({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      <path d="M5.3 9.4a3 3 0 014.2 0l2.5 2.5-2.5 2.5a3 3 0 01-4.2 0L3.6 12.7a1 1 0 010-1.4zM18.7 9.4l1.7 1.9a1 1 0 010 1.4l-1.7 1.7a3 3 0 01-4.2 0L12 12l2.5-2.6a3 3 0 014.2 0zM7.8 6.4L12 2.2l4.2 4.2a3 3 0 00-4.2 0l-4.2 0z" fill="#32BCAD"/>
      <path d="M16.2 17.6L12 21.8l-4.2-4.2a3 3 0 004.2 0l4.2 0z" fill="#32BCAD"/>
    </svg>
  );
}
function CardIcon({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="var(--ink)" strokeWidth="1.5">
      <rect x="2" y="5" width="20" height="14" rx="2.5"/>
      <path d="M2 10h20" strokeWidth="1.8"/>
      <path d="M6 15h4M14 15h4" strokeLinecap="round"/>
    </svg>
  );
}
function LockIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
      <rect x="5" y="11" width="14" height="10" rx="2"/>
      <path d="M8 11V7a4 4 0 118 0v4"/>
    </svg>
  );
}
function ShieldIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 3l8 3v6c0 5-3.5 8.5-8 9.5-4.5-1-8-4.5-8-9.5V6z"/>
      <path d="M9 12l2 2 4-4"/>
    </svg>
  );
}
function CopyIcon() {
  return (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="9" y="9" width="12" height="12" rx="2"/>
      <path d="M15 3H5a2 2 0 00-2 2v10"/>
    </svg>
  );
}
function QRPlaceholder() {
  // deterministic pseudo-random 21x21 QR-like pattern
  const cells = [];
  for (let y = 0; y < 21; y++) for (let x = 0; x < 21; x++) {
    const v = (Math.sin(x*3.7 + y*1.3) * 43758.5453) % 1;
    cells.push({ x, y, on: Math.abs(v) > 0.55 });
  }
  // finder patterns (corners)
  const isFinder = (x,y) => {
    const corners = [[0,0],[14,0],[0,14]];
    return corners.some(([cx,cy]) => x>=cx && x<cx+7 && y>=cy && y<cy+7);
  };
  const inFinderPixel = (x,y) => {
    const corners = [[0,0],[14,0],[0,14]];
    for (const [cx,cy] of corners) {
      const dx = x-cx, dy = y-cy;
      if (dx>=0 && dx<7 && dy>=0 && dy<7) {
        const inOuter = dx===0||dx===6||dy===0||dy===6;
        const inInner = dx>=2 && dx<=4 && dy>=2 && dy<=4;
        return inOuter || inInner;
      }
    }
    return false;
  };
  return (
    <svg viewBox="0 0 21 21" width="100%" height="100%" shapeRendering="crispEdges">
      {cells.map(c => {
        const on = isFinder(c.x, c.y) ? inFinderPixel(c.x, c.y) : c.on;
        return on ? <rect key={`${c.x}-${c.y}`} x={c.x} y={c.y} width="1" height="1" fill="#1F1A15"/> : null;
      })}
      {/* aftershot center mark */}
      <rect x="9" y="9" width="3" height="3" fill="white"/>
      <rect x="9.5" y="9.5" width="2" height="2" fill="#C96442"/>
    </svg>
  );
}

// Formatters
function formatCard(v) { return v.replace(/\D/g,'').slice(0,16).replace(/(.{4})/g,'$1 ').trim(); }
function formatExp(v) {
  const d = v.replace(/\D/g,'').slice(0,4);
  return d.length > 2 ? `${d.slice(0,2)}/${d.slice(2)}` : d;
}
function formatCPF(v) {
  const d = v.replace(/\D/g,'').slice(0,11);
  return d.replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d{1,2})$/, '$1-$2');
}
function formatPhone(v) {
  const d = v.replace(/\D/g,'').slice(0,11);
  if (d.length <= 10) return d.replace(/(\d{2})(\d)/, '($1) $2').replace(/(\d{4})(\d)/, '$1-$2');
  return d.replace(/(\d{2})(\d)/, '($1) $2').replace(/(\d{5})(\d)/, '$1-$2');
}

const sectionStyle = {
  padding:'20px 22px', background:'var(--paper)', border:'1px solid var(--line)',
  borderRadius: 16, marginBottom: 16,
};
const badgeGreen = {
  fontSize: 10, fontWeight: 600, letterSpacing:'.04em',
  padding:'4px 7px', borderRadius: 6, background:'#EAF2E4', color:'var(--olive)',
};
const badgeNeutral = {
  fontSize: 10, fontWeight: 600, letterSpacing:'.04em',
  padding:'4px 7px', borderRadius: 6, background:'var(--bg-deep)', color:'var(--ink-2)',
};

Object.assign(window, { Checkout });
