/* checkout.jsx — tela de assinatura / checkout do Plano Pro */
const {
  Button: CBtn, Badge: CBadge, Input: CInput, Separator: CSep, cn: ccn,
  formatBRL: cBRL,
  IconLock: CLock, IconShield: CShield, IconCheck: CCheck, IconArrowRight: CArrow,
  IconWallet: CWallet, IconBolt: CBolt, IconChart: CChart, IconStar: CStar,
} = window;

const C_PRICING = {
  monthly: { perMonth: 29.9, today: 29.9, label: 'Mensal', billedNote: 'Cobrado todo mês. Cancele quando quiser.', save: 0 },
  annual: { perMonth: 24.9, today: 298.8, label: 'Anual', billedNote: 'Cobrado uma vez por ano (R$ 298,80).', save: 59.0 },
};

const onlyDigits = (s) => (s || '').replace(/\D/g, '');
function fmtCard(v) { return onlyDigits(v).slice(0, 16).replace(/(.{4})/g, '$1 ').trim(); }
function fmtExp(v) { const d = onlyDigits(v).slice(0, 4); return d.length >= 3 ? d.slice(0, 2) + '/' + d.slice(2) : d; }
function fmtCpf(v) {
  const d = onlyDigits(v).slice(0, 11);
  return d.replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})\.(\d{3})(\d)/, '$1.$2.$3').replace(/\.(\d{3})(\d)/, '.$1-$2');
}
function cardBrand(num) {
  const n = onlyDigits(num);
  if (/^4/.test(n)) return 'Visa';
  if (/^(5[1-5]|2[2-7])/.test(n)) return 'Mastercard';
  if (/^3[47]/.test(n)) return 'Amex';
  if (/^(636368|438935|504175|451416|636297|5067|4576|4011|506699)/.test(n)) return 'Elo';
  if (/^(606282|3841)/.test(n)) return 'Hipercard';
  return n.length >= 2 ? 'Cartão' : '';
}

/* Preview do cartão (atualiza ao vivo) */
function CardPreview({ number, name, exp, brand }) {
  const display = (number || '').padEnd(19, '•').replace(/(.{4})/g, '$1 ').trim().slice(0, 23);
  return (
    <div className="relative aspect-[1.6/1] w-full max-w-xs overflow-hidden rounded-2xl border border-white/10 p-5 text-white shadow-2xl shadow-black/50"
      style={{ background: 'linear-gradient(135deg, #0F8C78 0%, #0A0A0A 70%), radial-gradient(120% 120% at 0% 0%, rgba(22,191,163,.5), transparent 50%)' }}>
      <div className="absolute inset-0 -z-0 opacity-30" style={{ background: 'radial-gradient(80% 80% at 100% 100%, rgba(249,94,46,.35), transparent 60%)' }} />
      <div className="relative flex h-full flex-col justify-between">
        <div className="flex items-center justify-between">
          <span className="h-7 w-9 rounded-md bg-gradient-to-br from-yellow-200/80 to-yellow-500/70" />
          <span className="font-syne text-sm font-bold tracking-wide">{brand || 'AchaMais'}</span>
        </div>
        <div className="font-mono text-lg tracking-[0.12em] tabular-nums">{display}</div>
        <div className="flex items-end justify-between">
          <div>
            <div className="text-[8px] uppercase tracking-widest text-white/50">Titular</div>
            <div className="truncate text-xs font-medium uppercase tracking-wide">{name || 'NOME NO CARTÃO'}</div>
          </div>
          <div className="text-right">
            <div className="text-[8px] uppercase tracking-widest text-white/50">Validade</div>
            <div className="font-mono text-xs">{exp || 'MM/AA'}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function MethodTab({ active, onClick, icon: Icon, label }) {
  return (
    <button onClick={onClick}
      className={ccn('flex flex-1 items-center justify-center gap-2 rounded-xl border px-3 py-2.5 text-sm font-medium transition-all',
        active ? 'border-brand/60 bg-brand/10 text-white' : 'border-edge bg-white/[0.02] text-zinc-400 hover:text-zinc-200')}>
      <Icon active={active} /> {label}
    </button>
  );
}
const IcoCard = ({ active }) => (
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={active ? '#16BFA3' : 'currentColor'} strokeWidth="2"><rect x="2" y="5" width="20" height="14" rx="2" /><line x1="2" y1="10" x2="22" y2="10" /></svg>
);
const IcoPix = ({ active }) => (
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={active ? '#16BFA3' : 'currentColor'} strokeWidth="2"><path d="M12 3 3 12l9 9 9-9-9-9z" /><path d="M7.5 7.5 12 12l4.5-4.5" /></svg>
);
const IcoBoleto = ({ active }) => (
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={active ? '#16BFA3' : 'currentColor'} strokeWidth="2"><rect x="3" y="5" width="18" height="14" rx="1" /><line x1="7" y1="8" x2="7" y2="16" /><line x1="10" y1="8" x2="10" y2="16" /><line x1="14" y1="8" x2="14" y2="16" /><line x1="17" y1="8" x2="17" y2="16" /></svg>
);

function Field({ label, children, className }) {
  return (
    <label className={ccn('block', className)}>
      <span className="mb-1.5 block text-xs font-medium text-zinc-400">{label}</span>
      {children}
    </label>
  );
}

function Checkout({ user, onBack, onSuccess }) {
  const { useState } = React;
  const [cycle, setCycle] = useState('annual');
  const [method, setMethod] = useState('card');
  const [card, setCard] = useState({ number: '', name: '', exp: '', cvv: '' });
  const [installments, setInstallments] = useState(1);
  const [cpf, setCpf] = useState('');
  const [email, setEmail] = useState((user && user.email) || '');
  const [status, setStatus] = useState('form'); // form | processing | success
  const [err, setErr] = useState('');
  const [copied, setCopied] = useState(false);

  const price = C_PRICING[cycle];
  const brand = cardBrand(card.number);
  const pixCode = '00020126360014BR.GOV.BCB.PIX0114achamais@pix.br5204000053039865802BR5909AchaMais6009SAO PAULO62070503***6304A1B2';

  const maxInst = cycle === 'annual' ? 12 : 1;

  const validate = () => {
    if (!email.trim() || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email.trim())) return 'Informe um e-mail válido.';
    if (onlyDigits(cpf).length !== 11) return 'Informe um CPF válido.';
    if (method === 'card') {
      if (onlyDigits(card.number).length < 16) return 'Número do cartão incompleto.';
      if (!card.name.trim()) return 'Informe o nome impresso no cartão.';
      if (onlyDigits(card.exp).length !== 4) return 'Validade inválida.';
      if (onlyDigits(card.cvv).length < 3) return 'CVV inválido.';
    }
    return '';
  };

  const pay = () => {
    const v = validate();
    if (v) { setErr(v); return; }
    setErr('');
    setStatus('processing');
    setTimeout(() => setStatus('success'), 1400);
  };

  const copyPix = () => {
    try { navigator.clipboard.writeText(pixCode); } catch (e) {}
    setCopied(true);
    setTimeout(() => setCopied(false), 1800);
  };

  /* ---------- SUCESSO ---------- */
  if (status === 'success') {
    return (
      <main className="mx-auto flex w-full max-w-xl flex-1 flex-col items-center justify-center px-5 py-20 text-center">
        <span className="relative mb-6 flex h-20 w-20 items-center justify-center rounded-full bg-brand/15 text-brand">
          <span className="best-pulse absolute inset-0 rounded-full" />
          <CCheck size={36} />
        </span>
        <h1 className="font-syne text-3xl font-extrabold tracking-tight text-white">Assinatura confirmada! 🎉</h1>
        <p className="mt-3 max-w-md text-pretty text-zinc-400">
          Bem-vinda ao <span className="font-semibold text-white">AchaMais Pro</span>. Suas buscas agora são ilimitadas e todos os recursos já estão liberados.
        </p>
        <div className="mt-7 w-full rounded-2xl border border-edge bg-panel p-5 text-left">
          <div className="flex items-center justify-between text-sm">
            <span className="text-zinc-400">Plano</span>
            <span className="font-semibold text-white">Pro · {price.label}</span>
          </div>
          <CSep className="my-3" />
          <div className="flex items-center justify-between text-sm">
            <span className="text-zinc-400">Pago hoje</span>
            <span className="font-semibold text-white">{cBRL(price.today)}{method === 'card' && installments > 1 ? ` em ${installments}x` : ''}</span>
          </div>
          <CSep className="my-3" />
          <div className="flex items-center justify-between text-sm">
            <span className="text-zinc-400">Próxima renovação</span>
            <span className="text-zinc-300">{cycle === 'annual' ? 'em 12 meses' : 'em 30 dias'}</span>
          </div>
        </div>
        <CBtn size="lg" className="mt-7 w-full sm:w-auto" onClick={onSuccess}>Ir para o painel <CArrow size={18} /></CBtn>
        <p className="mt-4 text-xs text-zinc-600">Um comprovante foi enviado para {email || 'seu e-mail'}.</p>
      </main>
    );
  }

  /* ---------- FORM ---------- */
  return (
    <main className="mx-auto w-full max-w-5xl flex-1 px-5 py-8">
      <button onClick={onBack} className="mb-5 inline-flex items-center gap-1.5 text-sm text-zinc-500 transition-colors hover:text-zinc-300">
        <span className="text-base leading-none">←</span> Voltar
      </button>

      <div className="mb-7 flex items-end justify-between gap-4">
        <div>
          <h1 className="font-syne text-2xl font-extrabold tracking-tight text-white">Finalizar assinatura</h1>
          <p className="mt-1 text-sm text-zinc-500">Você está a um passo do AchaMais Pro.</p>
        </div>
        <span className="hidden items-center gap-1.5 rounded-full border border-edge px-3 py-1 text-xs text-zinc-400 sm:inline-flex">
          <CLock size={13} className="text-brand" /> Pagamento seguro
        </span>
      </div>

      <div className="grid gap-6 lg:grid-cols-[1.5fr_1fr]">
        {/* COLUNA ESQUERDA — pagamento */}
        <div className="space-y-6">
          {/* Ciclo */}
          <section className="rounded-2xl border border-edge bg-panel p-5">
            <h2 className="mb-3 font-syne text-base font-bold text-white">1. Escolha o ciclo</h2>
            <div className="grid grid-cols-2 gap-3">
              {['annual', 'monthly'].map((c) => {
                const p = C_PRICING[c];
                const active = cycle === c;
                return (
                  <button key={c} onClick={() => { setCycle(c); if (c === 'monthly') setInstallments(1); }}
                    className={ccn('relative rounded-xl border p-4 text-left transition-all', active ? 'border-brand/60 bg-brand/[0.07]' : 'border-edge bg-white/[0.02] hover:border-zinc-700')}>
                    {c === 'annual' && <span className="absolute -top-2 right-3 rounded-full bg-brand px-2 py-0.5 text-[10px] font-bold text-ink">2 meses grátis</span>}
                    <div className="flex items-center gap-2">
                      <span className={ccn('flex h-4 w-4 items-center justify-center rounded-full border', active ? 'border-brand bg-brand' : 'border-zinc-600')}>
                        {active && <span className="h-1.5 w-1.5 rounded-full bg-ink" />}
                      </span>
                      <span className="text-sm font-semibold text-white">{p.label}</span>
                    </div>
                    <div className="mt-2 flex items-baseline gap-0.5">
                      <span className="font-num text-xl font-extrabold leading-none text-white">{cBRL(p.perMonth)}</span>
                      <span className="text-xs font-medium text-zinc-500">/mês</span>
                    </div>
                    {c === 'annual' ? <div className="text-xs text-brand">economize {cBRL(p.save)}</div> : <div className="text-xs text-zinc-500">flexível</div>}
                  </button>
                );
              })}
            </div>
          </section>

          {/* Método */}
          <section className="rounded-2xl border border-edge bg-panel p-5">
            <h2 className="mb-3 font-syne text-base font-bold text-white">2. Forma de pagamento</h2>
            <div className="flex gap-2">
              <MethodTab active={method === 'card'} onClick={() => setMethod('card')} icon={IcoCard} label="Cartão" />
              <MethodTab active={method === 'pix'} onClick={() => setMethod('pix')} icon={IcoPix} label="Pix" />
              <MethodTab active={method === 'boleto'} onClick={() => setMethod('boleto')} icon={IcoBoleto} label="Boleto" />
            </div>

            {method === 'card' && (
              <div className="mt-5 grid gap-5 sm:grid-cols-[1fr_auto]">
                <div className="order-2 space-y-3 sm:order-1">
                  <Field label="Número do cartão">
                    <div className="relative">
                      <CInput inputMode="numeric" value={card.number} onChange={(e) => setCard({ ...card, number: fmtCard(e.target.value) })} placeholder="0000 0000 0000 0000" className="pr-16 font-mono" />
                      {brand && <span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs font-semibold text-zinc-400">{brand}</span>}
                    </div>
                  </Field>
                  <Field label="Nome impresso no cartão">
                    <CInput value={card.name} onChange={(e) => setCard({ ...card, name: e.target.value.toUpperCase() })} placeholder="COMO ESTÁ NO CARTÃO" className="uppercase" />
                  </Field>
                  <div className="grid grid-cols-2 gap-3">
                    <Field label="Validade">
                      <CInput inputMode="numeric" value={card.exp} onChange={(e) => setCard({ ...card, exp: fmtExp(e.target.value) })} placeholder="MM/AA" className="font-mono" />
                    </Field>
                    <Field label="CVV">
                      <CInput inputMode="numeric" value={card.cvv} onChange={(e) => setCard({ ...card, cvv: onlyDigits(e.target.value).slice(0, 4) })} placeholder="123" className="font-mono" />
                    </Field>
                  </div>
                  {cycle === 'annual' && (
                    <Field label="Parcelamento">
                      <div className="relative">
                        <select value={installments} onChange={(e) => setInstallments(Number(e.target.value))}
                          className="h-11 w-full appearance-none rounded-lg border border-edge bg-white/[0.04] px-4 text-sm text-zinc-100 focus:border-brand/60 focus:outline-none focus:ring-2 focus:ring-brand/25">
                          {Array.from({ length: maxInst }).map((_, i) => {
                            const n = i + 1;
                            return <option key={n} value={n} className="bg-[#161616]">{n}x de {cBRL(price.today / n)}{n === 1 ? ' à vista' : ' sem juros'}</option>;
                          })}
                        </select>
                        <span className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-zinc-500">▾</span>
                      </div>
                    </Field>
                  )}
                </div>
                <div className="order-1 sm:order-2">
                  <CardPreview number={onlyDigits(card.number)} name={card.name} exp={card.exp} brand={brand} />
                </div>
              </div>
            )}

            {method === 'pix' && (
              <div className="mt-5 flex flex-col items-center gap-4 sm:flex-row sm:items-start">
                <div className="grid h-40 w-40 shrink-0 place-items-center rounded-xl border border-edge"
                  style={{ background: 'repeating-conic-gradient(#0d0d0d 0% 25%, #15151a 0% 50%) 0 0 / 14px 14px' }}>
                  <span className="rounded-md bg-black/70 px-2 py-1 font-mono text-[10px] uppercase tracking-widest text-zinc-400">QR Pix</span>
                </div>
                <div className="flex-1">
                  <p className="text-sm text-zinc-300">Escaneie o QR Code no app do seu banco ou use o <span className="text-white">copia e cola</span>:</p>
                  <div className="mt-3 flex items-center gap-2 rounded-lg border border-edge bg-white/[0.03] p-2">
                    <span className="flex-1 truncate font-mono text-[11px] text-zinc-500">{pixCode}</span>
                    <CBtn variant="secondary" size="sm" onClick={copyPix}>{copied ? 'Copiado!' : 'Copiar'}</CBtn>
                  </div>
                  <p className="mt-3 inline-flex items-center gap-1.5 text-xs text-brand"><CBolt size={13} /> Aprovação na hora, assim que o pagamento cair.</p>
                </div>
              </div>
            )}

            {method === 'boleto' && (
              <div className="mt-5 rounded-xl border border-edge bg-white/[0.02] p-4 text-sm text-zinc-400">
                O boleto vence em 3 dias úteis e a liberação ocorre em até 2 dias após o pagamento. Para acesso imediato, prefira <button onClick={() => setMethod('pix')} className="text-brand hover:underline">Pix</button> ou cartão.
              </div>
            )}
          </section>

          {/* Dados de cobrança */}
          <section className="rounded-2xl border border-edge bg-panel p-5">
            <h2 className="mb-3 font-syne text-base font-bold text-white">3. Dados de cobrança</h2>
            <div className="grid gap-3 sm:grid-cols-2">
              <Field label="CPF">
                <CInput inputMode="numeric" value={cpf} onChange={(e) => setCpf(fmtCpf(e.target.value))} placeholder="000.000.000-00" className="font-mono" />
              </Field>
              <Field label="E-mail para o comprovante">
                <CInput type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="voce@email.com" />
              </Field>
            </div>
          </section>
        </div>

        {/* COLUNA DIREITA — resumo */}
        <aside className="lg:sticky lg:top-24 lg:self-start">
          <div className="rounded-2xl border border-edge bg-panel p-5">
            <div className="flex items-center gap-3 border-b border-edge pb-4">
              <span className="flex h-10 w-10 items-center justify-center rounded-xl bg-brand/15 text-brand"><CStar size={18} /></span>
              <div>
                <div className="font-syne text-base font-bold text-white">AchaMais Pro</div>
                <div className="text-xs text-zinc-500">Plano {price.label.toLowerCase()}</div>
              </div>
              <CBadge variant="brand" className="ml-auto">Pro</CBadge>
            </div>

            <ul className="space-y-2 py-4 text-sm text-zinc-300">
              <li className="flex items-center gap-2"><CCheck size={15} className="text-brand" /> Buscas ilimitadas</li>
              <li className="flex items-center gap-2"><CChart size={15} className="text-brand" /> Gerador de links com sub-id</li>
              <li className="flex items-center gap-2"><CStar size={15} className="text-brand" /> Alertas de melhor comissão</li>
            </ul>

            <CSep />
            <div className="space-y-2 py-4 text-sm">
              <div className="flex justify-between text-zinc-400"><span>Plano {price.label}</span><span className="tabular-nums">{cBRL(price.today)}</span></div>
              {price.save > 0 && <div className="flex justify-between text-brand"><span>Economia anual</span><span className="tabular-nums">- {cBRL(price.save)}</span></div>}
            </div>
            <CSep />
            <div className="flex items-end justify-between py-4">
              <span className="text-sm text-zinc-400">Total hoje</span>
              <span className="font-num text-2xl font-extrabold text-white">{cBRL(price.today)}</span>
            </div>

            {err && <div className="mb-3 rounded-lg border border-coral/30 bg-coral/[0.06] px-3 py-2 text-xs text-coral">{err}</div>}

            <CBtn className="w-full" disabled={status === 'processing'} onClick={pay}>
              {status === 'processing' ? 'Processando…' : method === 'pix' ? 'Confirmar pagamento Pix' : method === 'boleto' ? 'Gerar boleto' : `Pagar ${cBRL(price.today)}`}
            </CBtn>

            <p className="mt-3 text-center text-[11px] leading-relaxed text-zinc-600">{price.billedNote} Ao assinar, você concorda com os Termos e a Política de Privacidade.</p>

            <div className="mt-4 flex items-center justify-center gap-4 border-t border-edge pt-4 text-[11px] text-zinc-600">
              <span className="inline-flex items-center gap-1"><CLock size={12} /> SSL 256-bit</span>
              <span className="inline-flex items-center gap-1"><CShield size={12} /> Mercado Pago</span>
            </div>
          </div>
        </aside>
      </div>
    </main>
  );
}

Object.assign(window, { Checkout });
