const { useState, useEffect, useRef } = React;

// ── Helpers ───────────────────────────────────────────────────────────────────

function brl(cents) {
  return (cents / 100).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
}
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) { return v.replace(/\D/g, '').length === 11; }
function fmtCardNumber(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 validEmail(v) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v); }

// ── UI primitives ─────────────────────────────────────────────────────────────

function Field({ label, error, ...props }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: '#9999B2', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</label>
      <input {...props} style={{
        width: '100%', padding: '11px 14px', background: '#14141C',
        border: `1px solid ${error ? '#FF1675' : 'rgba(255,255,255,0.1)'}`, borderRadius: 10,
        color: '#EFEFEF', fontSize: 14, outline: 'none',
      }} />
      {error && <div style={{ color: '#FF1675', fontSize: 11, marginTop: 4 }}>{error}</div>}
    </div>
  );
}

function Button({ children, block, disabled, ...props }) {
  return (
    <button {...props} disabled={disabled} style={{
      display: block ? 'block' : 'inline-block', width: block ? '100%' : 'auto',
      background: disabled ? 'rgba(255,255,255,0.08)' : 'linear-gradient(135deg,#7B3FF2,#FF1675)',
      border: 'none', borderRadius: 9999, color: '#fff', fontSize: 14, fontWeight: 700,
      padding: '13px 24px', cursor: disabled ? 'not-allowed' : 'pointer', opacity: disabled ? 0.6 : 1,
    }}>{children}</button>
  );
}

function Spinner() {
  return (
    <div style={{ width: 22, height: 22, borderRadius: '50%', border: '2px solid rgba(123,63,242,0.3)', borderTopColor: '#7B3FF2', animation: 'spin 0.8s linear infinite', display: 'inline-block' }}>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}

function ErrorBox({ msg }) {
  if (!msg) return null;
  return <div style={{ background: 'rgba(255,22,117,0.1)', border: '1px solid rgba(255,22,117,0.3)', borderRadius: 10, padding: '10px 14px', color: '#FF6FA8', fontSize: 12, marginBottom: 14 }}>{msg}</div>;
}

// ── NavBar ────────────────────────────────────────────────────────────────────

function NavBar() {
  return (
    <nav style={{ position: 'fixed', top: 0, left: 0, right: 0, zIndex: 200, height: 64, background: 'rgba(10,10,15,0.92)', backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)', borderBottom: '1px solid rgba(255,255,255,0.06)', display: 'flex', alignItems: 'center', padding: '0 24px', gap: 16 }}>
      <a href="/" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <img src="/assets/sx_fill.svg" style={{ height: 26, filter: 'brightness(0) invert(1)' }} alt="SX" />
      </a>
      <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#C8A96E', fontFamily: "'Inter',sans-serif" }}>Edições Revista Sexy</span>
      <div style={{ marginLeft: 'auto', display: 'flex', gap: 12, alignItems: 'center' }}>
        <a href="/projeto/revista" style={{ fontSize: 13, fontWeight: 500, color: '#9999B2' }}>Revista Sexy</a>
        <a href="/assinar" style={{ background: 'linear-gradient(135deg,#7B3FF2,#FF1675)', borderRadius: 9999, color: '#fff', fontSize: 12, fontWeight: 600, padding: '7px 16px' }}>Assinar</a>
      </div>
    </nav>
  );
}

// ── Checkout modal ────────────────────────────────────────────────────────────

function CheckoutModal({ magazine, onClose }) {
  const [step, setStep] = useState('form'); // form | pix-wait | success | error
  const [method, setMethod] = useState('pix');
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [cpf, setCpf] = useState('');
  const [card, setCard] = useState({ number: '', name: '', expiry: '', cvv: '' });
  const [loading, setLoading] = useState(false);
  const [apiError, setApiError] = useState('');
  const [pixData, setPixData] = useState(null);
  const [redirectUrl, setRedirectUrl] = useState(null);
  const pollRef = useRef(null);

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

  function validateForm() {
    if (!validEmail(email)) { setApiError('E-mail inválido.'); return false; }
    if (!validCpf(cpf)) { setApiError('CPF inválido.'); return false; }
    if (method === 'credit_card') {
      if (card.number.replace(/\s/g, '').length < 16) { setApiError('Número do cartão inválido.'); return false; }
      if (!card.name.trim()) { setApiError('Informe o nome impresso no cartão.'); return false; }
      if (card.expiry.length < 5) { setApiError('Validade inválida.'); return false; }
      if (card.cvv.length < 3) { setApiError('CVV inválido.'); return false; }
    }
    return true;
  }

  function startPolling(invoiceId) {
    pollRef.current = setInterval(async () => {
      try {
        const r = await fetch(`/api/checkout/magazine/invoice/${invoiceId}`);
        const data = await r.json();
        if (data.status === 'paid') {
          clearInterval(pollRef.current);
          setRedirectUrl(data.wp_redirect_url);
          setStep('success');
        }
      } catch { /* retry */ }
    }, 3000);
  }

  async function submit() {
    setApiError('');
    if (!validateForm()) return;
    setLoading(true);

    try {
      if (method === 'pix') {
        const resp = await fetch('/api/checkout/magazine/charge-pix', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email, name, cpf: cpf.replace(/\D/g, ''), wc_product_id: magazine.wc_product_id }),
        });
        const data = await resp.json();
        if (!resp.ok) throw new Error(data.error || 'Erro ao gerar Pix.');
        setPixData(data);
        setStep('pix-wait');
        startPolling(data.invoice_id);
      } else {
        const [expMonth, expYear] = card.expiry.split('/');
        const resp = await fetch('/api/checkout/magazine/charge-card', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            email, name,
            card: { number: card.number, firstName: name.split(' ')[0], lastName: name.split(' ').slice(1).join(' '), month: expMonth, year: expYear, cvv: card.cvv },
            wc_product_id: magazine.wc_product_id,
          }),
        });
        const data = await resp.json();
        if (!resp.ok) throw new Error(data.error || 'Cobrança recusada.');
        setRedirectUrl(data.wp_redirect_url);
        setStep('success');
      }
    } catch (err) {
      setApiError(err.message);
    } finally {
      setLoading(false);
    }
  }

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

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.7)', backdropFilter: 'blur(4px)', zIndex: 300, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <div onClick={e => e.stopPropagation()} style={{ background: '#14141C', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 20, padding: 28, width: '100%', maxWidth: 420, maxHeight: '90vh', overflowY: 'auto' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 20 }}>
          <div>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#C8A96E' }}>Compra avulsa</div>
            <div style={{ fontFamily: "'Space Grotesk',sans-serif", fontWeight: 700, fontSize: 16, color: '#EFEFEF', marginTop: 4 }}>{magazine.name}</div>
            <div style={{ fontSize: 20, fontWeight: 700, color: '#C8A96E', marginTop: 4 }}>{brl(magazine.price_cents)}</div>
          </div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', color: '#9999B2', fontSize: 20, cursor: 'pointer', lineHeight: 1 }}>&times;</button>
        </div>

        {step === 'form' && (
          <>
            <div style={{ display: 'flex', gap: 4, background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 9999, padding: 3, marginBottom: 18 }}>
              {[['pix', 'Pix'], ['credit_card', 'Cartão']].map(([value, label]) => (
                <button key={value} onClick={() => setMethod(value)} style={{
                  flex: 1, background: method === value ? 'rgba(123,63,242,0.25)' : 'transparent', border: 'none', borderRadius: 9999,
                  color: method === value ? '#EFEFEF' : 'rgba(255,255,255,0.45)', fontSize: 13, fontWeight: 600, padding: '8px 0', cursor: 'pointer',
                }}>{label}</button>
              ))}
            </div>

            <Field label="E-mail" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="voce@email.com" />
            <Field label="Nome" value={name} onChange={e => setName(e.target.value)} placeholder="Seu nome completo" />
            <Field label="CPF" value={cpf} onChange={e => setCpf(fmtCpf(e.target.value))} placeholder="000.000.000-00" />

            {method === 'credit_card' && (
              <>
                <Field label="Número do cartão" value={card.number} onChange={e => setCard({ ...card, number: fmtCardNumber(e.target.value) })} placeholder="0000 0000 0000 0000" />
                <Field label="Nome no cartão" value={card.name} onChange={e => setCard({ ...card, name: e.target.value })} placeholder="Como está no cartão" />
                <div style={{ display: 'flex', gap: 12 }}>
                  <div style={{ flex: 1 }}><Field label="Validade" value={card.expiry} onChange={e => setCard({ ...card, expiry: fmtExpiry(e.target.value) })} placeholder="MM/AA" /></div>
                  <div style={{ flex: 1 }}><Field label="CVV" value={card.cvv} onChange={e => setCard({ ...card, cvv: e.target.value.replace(/\D/g, '').slice(0, 4) })} placeholder="123" /></div>
                </div>
              </>
            )}

            <ErrorBox msg={apiError} />
            <Button block disabled={loading} onClick={submit}>
              {loading ? 'Processando...' : method === 'pix' ? 'Gerar Pix' : 'Pagar com Cartão'}
            </Button>
            <p style={{ fontSize: 11, color: '#55556A', marginTop: 12, textAlign: 'center' }}>Pagamento único — sem cobrança recorrente.</p>
          </>
        )}

        {step === 'pix-wait' && (
          <div style={{ textAlign: 'center' }}>
            {pixData?.pix?.qrcode && (
              <img src={resolveQrSrc(pixData.pix.qrcode)} width={192} height={192} alt="QR Code Pix"
                style={{ borderRadius: 12, background: '#fff', padding: 10, margin: '0 auto 16px', display: 'block' }} />
            )}
            <p style={{ fontSize: 13, color: '#9999B2', marginBottom: 16 }}>Escaneie o QR code ou copie o código Pix pra pagar.</p>
            {pixData?.pix?.qrcode_text && (
              <textarea readOnly value={pixData.pix.qrcode_text} onClick={e => e.target.select()}
                style={{ width: '100%', height: 60, background: '#0A0A0F', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 10, color: '#9999B2', fontSize: 10, fontFamily: 'monospace', padding: 10, marginBottom: 16, resize: 'none' }} />
            )}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, fontSize: 13, color: '#9999B2' }}>
              <Spinner /> Aguardando pagamento...
            </div>
          </div>
        )}

        {step === 'success' && (
          <div style={{ textAlign: 'center', padding: '12px 0' }}>
            <div style={{ fontSize: 40, marginBottom: 12 }}>✓</div>
            <div style={{ fontFamily: "'Space Grotesk',sans-serif", fontWeight: 700, fontSize: 18, color: '#EFEFEF', marginBottom: 8 }}>Compra confirmada!</div>
            <p style={{ fontSize: 13, color: '#9999B2', marginBottom: 20 }}>Seu download está disponível na sua conta do Sexy Clube.</p>
            {redirectUrl ? (
              <a href={redirectUrl}><Button block>Acessar meu download</Button></a>
            ) : (
              <p style={{ fontSize: 12, color: '#55556A' }}>Enviamos os detalhes de acesso pro seu e-mail.</p>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// ── Grid de edições ───────────────────────────────────────────────────────────

function MagazineCard({ magazine, onBuy }) {
  return (
    <div className="mag-card" onClick={() => onBuy(magazine)} style={{
      borderRadius: 16, overflow: 'hidden', position: 'relative', aspectRatio: '3/4',
      background: '#14141C', border: '1px solid rgba(255,255,255,0.06)',
    }}>
      {magazine.cover && (
        <img src={magazine.cover} alt={magazine.name} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} onError={e => e.target.style.display = 'none'} />
      )}
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(10,10,15,0.95) 0%, rgba(10,10,15,0.15) 55%, transparent 100%)' }} />
      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '14px 14px 16px' }}>
        <div style={{ fontFamily: "'Space Grotesk',sans-serif", fontWeight: 700, fontSize: 13, color: '#EFEFEF', lineHeight: 1.25, marginBottom: 8 }}>{magazine.name}</div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontSize: 15, fontWeight: 700, color: '#C8A96E' }}>{brl(magazine.price_cents)}</span>
          <span style={{ fontSize: 11, fontWeight: 600, color: '#fff', background: 'linear-gradient(135deg,#7B3FF2,#FF1675)', borderRadius: 9999, padding: '5px 12px' }}>Comprar</span>
        </div>
      </div>
    </div>
  );
}

function Edicoes() {
  const [magazines, setMagazines] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState(null);

  useEffect(() => {
    fetch('/api/magazines')
      .then(r => r.json())
      .then(data => setMagazines(Array.isArray(data) ? data : []))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  return (
    <div style={{ background: '#0A0A0F', minHeight: '100vh' }}>
      <NavBar />
      <div style={{ paddingTop: 64 }}>
        <div className="section-pad" style={{ maxWidth: 1400, margin: '0 auto', padding: '40px 40px 48px' }}>
          <div style={{ marginBottom: 32 }}>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#C8A96E', marginBottom: 6 }}>REVISTA SEXY · ACERVO DIGITAL</div>
            <h1 style={{ fontFamily: "'Space Grotesk',sans-serif", fontWeight: 700, fontSize: 32, color: '#EFEFEF', textTransform: 'uppercase' }}>Edições Avulsas</h1>
            <p style={{ fontSize: 14, color: '#9999B2', marginTop: 8, maxWidth: 560 }}>Compre e baixe edições completas da Revista Sexy em PDF — sem assinatura, pagamento único.</p>
          </div>

          {loading ? (
            <div className="mag-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(5,1fr)', gap: 14 }}>
              {Array.from({ length: 10 }).map((_, i) => (
                <div key={i} style={{ borderRadius: 16, background: '#14141C', border: '1px solid rgba(255,255,255,0.05)', aspectRatio: '3/4' }} />
              ))}
            </div>
          ) : magazines.length === 0 ? (
            <div style={{ padding: '60px 0', textAlign: 'center', color: '#55556A', fontSize: 14 }}>Nenhuma edição disponível no momento.</div>
          ) : (
            <div className="mag-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(5,1fr)', gap: 14 }}>
              {magazines.map(m => <MagazineCard key={m.id} magazine={m} onBuy={setSelected} />)}
            </div>
          )}
        </div>
      </div>

      {selected && <CheckoutModal magazine={selected} onClose={() => setSelected(null)} />}
    </div>
  );
}

window.Edicoes = Edicoes;
