// zeus-pago-simple.jsx — Tarjeta · Bizum · Bitcoin · Lightning · PayPal

const BTC_ADDRESS       = '1A1zP1eP5QGefi2DMPTfTL5SLmv7Divf6N'; // ← tu dirección BTC on-chain
const LIGHTNING_ADDRESS = 'zeusventas@getalby.com';              // ← tu Lightning Address (ej: Alby, Strike)
const BTC_WALLET_LABEL  = 'Zeus Ventas';
const BTC_LIMIT_USD     = 100000; // Si BTC > 100.000$ no aceptamos pagos on-chain

function FormaPago({ t, product, envio }) {
  const [metodo,   setMetodo]   = React.useState('tarjeta');
  const [nombre,   setNombre]   = React.useState(localStorage.getItem('pago_nombre') || '');
  const [email,    setEmail]    = React.useState(localStorage.getItem('pago_email')  || '');
  const [enviando, setEnviando] = React.useState(false);
  const [mensaje,  setMensaje]  = React.useState('');
  const [pagoOk,   setPagoOk]   = React.useState(false);

  // Tarjeta
  const [cardNum,    setCardNum]    = React.useState(localStorage.getItem('pago_card_num')    || '');
  const [cardExp,    setCardExp]    = React.useState(localStorage.getItem('pago_card_exp')    || '');
  const [cardCVC,    setCardCVC]    = React.useState(localStorage.getItem('pago_card_cvc')    || '');
  const [cardNombre, setCardNombre] = React.useState(localStorage.getItem('pago_card_nombre') || '');

  // Bizum
  const [bizumTel, setBizumTel] = React.useState(localStorage.getItem('pago_bizum_tel') || '');

  // BTC
  const [btcPrice,   setBtcPrice]   = React.useState(null);
  const [btcCopiado, setBtcCopiado] = React.useState(false);

  const totalEur = (Number(product?.price) || 0) + (envio || 0);
  const totalBtc = btcPrice ? (totalEur / btcPrice).toFixed(6) : null;

  // Precio BTC en vivo (Binance API pública)
  React.useEffect(() => {
    if (metodo !== 'btc') return;
    if (btcPrice) return;
    fetch('https://api.binance.com/api/v3/ticker/price?symbol=BTCEUR')
      .then(r => r.json())
      .then(d => setBtcPrice(Number(d.price)))
      .catch(() => setBtcPrice(95000)); // fallback si falla la API
  }, [metodo]);

  const fmtCard = v => v.replace(/\D/g,'').slice(0,16).replace(/(\d{4})/g,'$1 ').trim();
  const fmtExp  = v => { v=v.replace(/\D/g,''); return v.length>=2 ? v.slice(0,2)+'/'+v.slice(2,4) : v; };

  const copiarBTC = () => {
    navigator.clipboard.writeText(BTC_ADDRESS).then(() => {
      setBtcCopiado(true);
      setTimeout(() => setBtcCopiado(false), 2000);
    });
  };

  const validar = () => {
    if (!nombre.trim()) { setMensaje('❌ Rellena tu nombre'); return false; }
    if (!email.trim())  { setMensaje('❌ Rellena tu email');  return false; }
    if (metodo === 'tarjeta') {
      if (cardNum.replace(/\s/g,'').length < 16) { setMensaje('❌ Tarjeta incompleta (16 dígitos)'); return false; }
      if (cardExp.length < 5) { setMensaje('❌ Vencimiento inválido MM/AA'); return false; }
      if (cardCVC.length < 3) { setMensaje('❌ CVV inválido'); return false; }
    }
    if (metodo === 'bizum') {
      if (bizumTel.replace(/\D/g,'').length < 9) { setMensaje('❌ Teléfono Bizum inválido'); return false; }
    }
    return true;
  };

  const pagar = async () => {
    setMensaje('');
    if (!validar()) return;

    // Autorrelleno: guardar
    localStorage.setItem('pago_nombre', nombre);
    localStorage.setItem('pago_email',  email);
    if (metodo === 'tarjeta') {
      localStorage.setItem('pago_card_num',    cardNum);
      localStorage.setItem('pago_card_exp',    cardExp);
      localStorage.setItem('pago_card_cvc',    cardCVC);
      localStorage.setItem('pago_card_nombre', cardNombre);
    }
    if (metodo === 'bizum') localStorage.setItem('pago_bizum_tel', bizumTel);

    // BTC / Lightning: mostramos dirección
    if (metodo === 'btc' || metodo === 'lightning') { setPagoOk(true); return; }
    // BTC desactivado
    if (metodo === 'btc_disabled') { setMensaje('❌ Bitcoin no disponible ahora (precio > 100.000$)'); return; }

    setEnviando(true);
    await new Promise(r => setTimeout(r, 1800));
    setEnviando(false);
    setPagoOk(true);
  };

  // Estilos
  const inp = {
    width:'100%', padding:'11px 13px', border:`2px solid ${t.border}`, borderRadius:10,
    fontSize:14, fontFamily:'Outfit,sans-serif', color:t.text, background:t.bg,
    boxSizing:'border-box', marginBottom:14,
  };
  const lbl = { display:'block', fontWeight:700, fontSize:12, textTransform:'uppercase',
    letterSpacing:0.5, color:t.text, marginBottom:6 };

  const COLS = { tarjeta:'#1a6dca', bizum:'#00a859', btc:'#f7931a', lightning:'#f59e0b', btc_disabled:'#9ca3af', paypal:'#003087' };

  // Comprobar si BTC está permitido (precio < 100.000$)
  const btcAllowed = btcPrice ? (btcPrice / 1.08) < BTC_LIMIT_USD : true; // 1.08 aprox EUR→USD
  const btcPriceUSD = btcPrice ? Math.round(btcPrice / 1.08) : null;

  const metodos = [
    { id:'tarjeta',   icon:'💳', label:'Tarjeta',          sub:'Visa · Mastercard · Amex' },
    { id:'bizum',     icon:'📱', label:'Bizum',             sub:'Pago bancario instantáneo' },
    { id:'lightning', icon:'⚡', label:'Lightning (BTC)',   sub:'Comisión mínima · Instantáneo' },
    ...(btcAllowed
      ? [{ id:'btc', icon:'₿', label:'Bitcoin on-chain', sub:'Red Bitcoin principal' }]
      : [{ id:'btc_disabled', icon:'₿', label:'Bitcoin (no disponible)', sub:`Precio > 100.000$ · Riesgo alto` }]
    ),
    { id:'paypal',    icon:'🅿️', label:'PayPal',            sub:'Pago seguro' },
  ];

  // ── PANTALLA BTC / CONFIRMACIÓN ──────────────────────────────────
  if (pagoOk) {
    // ── LIGHTNING confirmación ─────────────────────────────────────
    if (metodo === 'lightning') {
      const lnInvoice = `lightning:${LIGHTNING_ADDRESS}?amount=${totalBtc}&label=${encodeURIComponent('Zeus Ventas - ' + (product?.title||''))}&message=${encodeURIComponent('Pago Zeus Ventas')}`;
      return (
        <div style={{ background:t.card, border:'3px solid #f59e0b', borderRadius:16, padding:28, margin:'24px 0', textAlign:'center' }}>
          <div style={{ fontSize:48, marginBottom:10 }}>⚡</div>
          <h2 style={{ fontSize:20, fontWeight:900, color:'#92400e', marginBottom:8 }}>Paga con Lightning</h2>
          <p style={{ fontSize:14, color:t.textMid, marginBottom:12 }}>
            Envía <strong style={{ color:'#f59e0b' }}>{totalBtc} BTC</strong> ({totalEur.toFixed(2)}€) a esta Lightning Address:
          </p>
          <div style={{ background:t.bgAlt, border:'2px dashed #f59e0b', borderRadius:12, padding:'12px 14px', marginBottom:12, display:'flex', gap:10, alignItems:'center' }}>
            <span style={{ fontSize:13, fontFamily:'monospace', color:t.text, flex:1, wordBreak:'break-all', textAlign:'left' }}>{LIGHTNING_ADDRESS}</span>
            <button onClick={() => { navigator.clipboard.writeText(LIGHTNING_ADDRESS); }} style={{ background:'#f59e0b', color:'#fff', border:'none', borderRadius:8, padding:'8px 12px', fontSize:12, fontWeight:800, cursor:'pointer', flexShrink:0, fontFamily:'Outfit,sans-serif' }}>Copiar</button>
          </div>
          <img src={`https://api.qrserver.com/v1/create-qr-code/?size=160x160&data=${encodeURIComponent(LIGHTNING_ADDRESS)}`}
            alt="QR Lightning" style={{ width:160, height:160, borderRadius:12, marginBottom:12, border:'4px solid #f59e0b' }} />
          <p style={{ fontSize:12, color:t.textLight, marginBottom:16, lineHeight:1.6 }}>
            Compatible con Wallet of Satoshi, Phoenix, Breez, BlueWallet, Strike...<br/>
            Una vez enviado, avísanos por WhatsApp al <strong>699 601 627</strong>.
          </p>
          <button onClick={() => setPagoOk(false)} style={{ background:t.bgAlt, border:`1px solid ${t.border}`, borderRadius:10, padding:'10px 20px', fontSize:13, color:t.text, cursor:'pointer', fontFamily:'Outfit,sans-serif' }}>
            ← Volver
          </button>
        </div>
      );
    }

    // ── BTC on-chain confirmación ──────────────────────────────────
    if (metodo === 'btc') {
      return (
        <div style={{ background:t.card, border:'3px solid #f7931a', borderRadius:16, padding:28, margin:'24px 0', textAlign:'center' }}>
          <div style={{ fontSize:48, marginBottom:10 }}>₿</div>
          <h2 style={{ fontSize:20, fontWeight:900, color:'#f7931a', marginBottom:8 }}>Paga con Bitcoin</h2>
          <p style={{ fontSize:14, color:t.textMid, marginBottom:16 }}>
            Envía exactamente <strong style={{ color:'#f7931a' }}>{totalBtc} BTC</strong> ({totalEur.toFixed(2)}€) a esta dirección:
          </p>

          {/* Dirección */}
          <div style={{ background:t.bgAlt, border:'2px dashed #f7931a', borderRadius:12, padding:'12px 14px', marginBottom:16, display:'flex', gap:10, alignItems:'center' }}>
            <span style={{ fontSize:11, fontFamily:'monospace', color:t.text, flex:1, wordBreak:'break-all', textAlign:'left' }}>
              {BTC_ADDRESS}
            </span>
            <button onClick={copiarBTC} style={{ background: btcCopiado ? '#22c55e' : '#f7931a', color:'#fff', border:'none', borderRadius:8, padding:'8px 12px', fontSize:12, fontWeight:800, cursor:'pointer', flexShrink:0, fontFamily:'Outfit,sans-serif' }}>
              {btcCopiado ? '✓ Copiado' : 'Copiar'}
            </button>
          </div>

          {/* QR */}
          <img
            src={`https://api.qrserver.com/v1/create-qr-code/?size=160x160&data=bitcoin:${BTC_ADDRESS}?amount=${totalBtc}&label=${encodeURIComponent(BTC_WALLET_LABEL)}`}
            alt="QR Bitcoin"
            style={{ width:160, height:160, borderRadius:12, marginBottom:16, border:'4px solid #f7931a' }}
          />

          <p style={{ fontSize:12, color:t.textLight, lineHeight:1.6, marginBottom:20 }}>
            ⚠️ Usa <strong>solo la red Bitcoin (BTC)</strong>. Precio válido ahora.<br/>
            Una vez enviado, avísanos por WhatsApp al <strong>699 601 627</strong>.
          </p>

          <button onClick={() => setPagoOk(false)} style={{ background:t.bgAlt, border:`1px solid ${t.border}`, borderRadius:10, padding:'10px 20px', fontSize:13, color:t.text, cursor:'pointer', fontFamily:'Outfit,sans-serif' }}>
            ← Volver
          </button>
        </div>
      );
    }

    // Otros métodos: confirmación
    return (
      <div style={{ background:t.card, border:'3px solid #22c55e', borderRadius:16, padding:28, margin:'24px 0', textAlign:'center' }}>
        <div style={{ fontSize:52, marginBottom:10 }}>✅</div>
        <h2 style={{ fontSize:22, fontWeight:900, color:'#22c55e', marginBottom:8 }}>¡Pago completado!</h2>
        <p style={{ fontSize:15, color:t.textMid, marginBottom:6 }}>
          Hemos recibido tu pago de <strong>{totalEur.toFixed(2)}€</strong>.
        </p>
        <p style={{ fontSize:13, color:t.textLight }}>
          Te contactaremos en <strong>{email}</strong> para coordinar la entrega.
        </p>
      </div>
    );
  }

  // ── FORMULARIO PRINCIPAL ─────────────────────────────────────────
  return (
    <div style={{ background:t.card, border:`3px solid ${t.primary}`, borderRadius:16, padding:24, margin:'24px 0' }}>

      <h2 style={{ fontSize:22, fontWeight:900, color:t.text, marginBottom:20 }}>💳 Forma de Pago</h2>

      {/* Resumen de compra */}
      <div style={{ background:t.bgAlt, padding:16, borderRadius:12, marginBottom:22, border:`1px solid ${t.border}` }}>
        <div style={{ display:'flex', justifyContent:'space-between', marginBottom:8, fontSize:14, color:t.textMid }}>
          <span>Producto</span><strong style={{ color:t.text }}>{Number(product?.price||0).toFixed(2)}€</strong>
        </div>
        <div style={{ display:'flex', justifyContent:'space-between', paddingBottom:12, marginBottom:12, borderBottom:`1px solid ${t.border}`, fontSize:14, color:t.textMid }}>
          <span>Envío</span><strong style={{ color:t.text }}>{(envio||0).toFixed(2)}€</strong>
        </div>
        <div style={{ display:'flex', justifyContent:'space-between', fontSize:18, fontWeight:900 }}>
          <span style={{ color:t.text }}>TOTAL</span>
          <span style={{ color:t.primary }}>{totalEur.toFixed(2)}€</span>
        </div>
        {/* Equivalente BTC en tiempo real */}
        {metodo === 'btc' && btcPrice && (
          <div style={{ marginTop:10, textAlign:'right', fontSize:13, color:'#f7931a', fontWeight:700 }}>
            ≈ {totalBtc} BTC
            <span style={{ fontWeight:400, color:t.textLight, marginLeft:6 }}>
              (1 BTC = {btcPrice.toLocaleString('es-ES',{maximumFractionDigits:0})}€)
            </span>
          </div>
        )}
      </div>

      {/* Selector de método — 2 columnas */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginBottom:22 }}>
        {metodos.map(m => {
          const activo = metodo === m.id;
          const col = COLS[m.id];
          return (
            <button key={m.id} onClick={() => { setMetodo(m.id); setMensaje(''); }}
              style={{
                padding:'12px 10px', borderRadius:12,
                border: `2px solid ${activo ? col : t.border}`,
                background: activo ? col+'18' : t.bgAlt,
                cursor:'pointer', textAlign:'left', transition:'all 0.2s',
                outline: activo ? `2px solid ${col}` : 'none',
              }}>
              <div style={{ fontSize:22, marginBottom:2 }}>{m.icon}</div>
              <div style={{ fontSize:13, fontWeight:800, color: activo ? col : t.text, fontFamily:'Outfit,sans-serif' }}>{m.label}</div>
              <div style={{ fontSize:11, color:t.textLight, fontFamily:'Outfit,sans-serif' }}>{m.sub}</div>
            </button>
          );
        })}
      </div>

      {/* Datos personales (comunes a todos) */}
      <div style={{ marginBottom:20, paddingBottom:20, borderBottom:`1px solid ${t.border}` }}>
        <label style={lbl}>Nombre *</label>
        <input type="text" value={nombre} onChange={e=>setNombre(e.target.value)} placeholder="Josep García" style={inp} />
        <label style={lbl}>Email *</label>
        <input type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder="josep@email.com" style={{ ...inp, marginBottom:0 }} />
      </div>

      {/* ── TARJETA ── */}
      {metodo === 'tarjeta' && (
        <div style={{ marginBottom:20, paddingBottom:20, borderBottom:`1px solid ${t.border}` }}>
          <label style={lbl}>Nombre en la tarjeta *</label>
          <input type="text" value={cardNombre} onChange={e=>setCardNombre(e.target.value.toUpperCase())} placeholder="COMO APARECE EN LA TARJETA" style={inp} />
          <label style={lbl}>Número de tarjeta *</label>
          <input type="text" value={cardNum} onChange={e=>setCardNum(fmtCard(e.target.value))} placeholder="1234 5678 9012 3456" maxLength="19" style={inp} />
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <div>
              <label style={lbl}>Vencimiento *</label>
              <input type="text" value={cardExp} onChange={e=>setCardExp(fmtExp(e.target.value))} placeholder="MM/AA" maxLength="5" style={{ ...inp, marginBottom:0 }} />
            </div>
            <div>
              <label style={lbl}>CVV *</label>
              <input type="text" value={cardCVC} onChange={e=>setCardCVC(e.target.value.replace(/\D/g,'').slice(0,4))} placeholder="123" maxLength="4" style={{ ...inp, marginBottom:0 }} />
            </div>
          </div>
          <div style={{ marginTop:10, fontSize:12, color:t.textLight }}>🔒 Datos encriptados · Nunca guardamos el CVV</div>
        </div>
      )}

      {/* ── BIZUM ── */}
      {metodo === 'bizum' && (
        <div style={{ marginBottom:20, paddingBottom:20, borderBottom:`1px solid ${t.border}` }}>
          <label style={lbl}>Tu teléfono Bizum *</label>
          <input type="tel" value={bizumTel} onChange={e=>setBizumTel(e.target.value)} placeholder="612 345 678" style={inp} />
          <div style={{ background:'#e8f5e9', border:'1px solid #a5d6a7', borderRadius:10, padding:12, fontSize:13, color:'#2e7d32', lineHeight:1.5 }}>
            📱 Recibirás una solicitud de pago de <strong>Zeus Ventas</strong> en tu app bancaria.<br/>
            Confirma la transferencia de <strong>{totalEur.toFixed(2)}€</strong> y listo.
          </div>
        </div>
      )}

      {/* ── BITCOIN ── */}
      {metodo === 'btc' && (
        <div style={{ marginBottom:20, paddingBottom:20, borderBottom:`1px solid ${t.border}` }}>
          {btcPrice ? (
            <div style={{ background:'#fff8ee', border:'2px solid #f7931a', borderRadius:12, padding:16, fontSize:14 }}>
              <div style={{ fontWeight:800, color:'#f7931a', marginBottom:8, fontSize:15 }}>₿ Pago con Bitcoin</div>
              <div style={{ color:t.textMid, marginBottom:6 }}>Importe exacto a enviar:</div>
              <div style={{ fontSize:26, fontWeight:900, color:'#f7931a', marginBottom:4 }}>{totalBtc} BTC</div>
              <div style={{ fontSize:12, color:t.textLight }}>
                ({totalEur.toFixed(2)}€ · cotización en vivo: {btcPrice.toLocaleString('es-ES',{maximumFractionDigits:0})}€/BTC)
              </div>
              <div style={{ marginTop:10, fontSize:12, color:t.textMid }}>
                Al pulsar "Pagar con Bitcoin" verás la dirección de wallet y el QR para escanear desde cualquier app (Kraken, Coinbase, Trust Wallet…).
              </div>
            </div>
          ) : (
            <div style={{ padding:16, textAlign:'center', color:t.textLight, fontSize:14 }}>⏳ Obteniendo cotización BTC/EUR…</div>
          )}
        </div>
      )}

      {/* ── LIGHTNING ── */}
      {metodo === 'lightning' && (
        <div style={{ marginBottom:20, paddingBottom:20, borderBottom:`1px solid ${t.border}` }}>
          <div style={{ background:'#fffbeb', border:'2px solid #f59e0b', borderRadius:12, padding:16, fontSize:14 }}>
            <div style={{ fontWeight:800, color:'#92400e', marginBottom:8, fontSize:15 }}>⚡ Lightning Network</div>
            <div style={{ color:'#78350f', marginBottom:6 }}>Pago instantáneo con comisión mínima (menos de 1 céntimo).</div>
            <div style={{ fontSize:13, color:'#92400e', marginBottom:4 }}>Importe: <strong>{totalEur.toFixed(2)}€</strong> ≈ <strong style={{ color:'#f59e0b' }}>{totalBtc ? totalBtc + ' BTC' : '...'}</strong></div>
            <div style={{ fontSize:12, color:'#b45309', marginTop:8 }}>Compatible con: Wallet of Satoshi, Phoenix, Breez, Muun, BlueWallet, Strike…</div>
          </div>
        </div>
      )}

      {/* ── BTC DESACTIVADO ── */}
      {metodo === 'btc_disabled' && (
        <div style={{ marginBottom:20, paddingBottom:20, borderBottom:`1px solid ${t.border}` }}>
          <div style={{ background:'#fef2f2', border:'2px solid #ef4444', borderRadius:12, padding:16, fontSize:14 }}>
            <div style={{ fontWeight:800, color:'#7f1d1d', marginBottom:8 }}>₿ Bitcoin temporalmente no disponible</div>
            <div style={{ color:'#991b1b', lineHeight:1.6 }}>
              Bitcoin cotiza por encima de los <strong>100.000$</strong> ({btcPriceUSD ? btcPriceUSD.toLocaleString('es-ES') + '$' : '...'}).
            </div>
            <div style={{ color:'#b91c1c', fontSize:13, marginTop:6 }}>
              Consideramos que a este precio el riesgo de depreciación es alto. Cuando baje de 100.000$ se reactivará automáticamente.
            </div>
            <div style={{ color:'#991b1b', fontSize:13, marginTop:6, fontWeight:700 }}>
              Usa Lightning Network para pagar con BTC con comisiones mínimas.
            </div>
          </div>
        </div>
      )}

      {/* ── PAYPAL ── */}
      {metodo === 'paypal' && (
        <div style={{ marginBottom:20, paddingBottom:20, borderBottom:`1px solid ${t.border}` }}>
          <div style={{ background:'#e8f0fe', border:'1px solid #90caf9', borderRadius:10, padding:14, fontSize:13, color:'#1565c0', lineHeight:1.6 }}>
            🅿️ Al pulsar "Pagar con PayPal" te redirigiremos a PayPal para completar el pago de <strong>{totalEur.toFixed(2)}€</strong> de forma segura.
          </div>
        </div>
      )}

      {/* Error */}
      {mensaje && (
        <div style={{ background:'#ffebee', border:'1px solid #ef9a9a', borderRadius:10, padding:12, fontSize:13, color:'#c62828', marginBottom:16, fontWeight:600 }}>
          {mensaje}
        </div>
      )}

      {/* Botón — color y texto cambia según método */}
      <button onClick={pagar}
        disabled={enviando || (metodo==='btc' && !btcPrice)}
        style={{
          width:'100%', padding:18, borderRadius:12, border:'none', fontSize:16, fontWeight:900,
          fontFamily:'Outfit,sans-serif', cursor: enviando ? 'not-allowed' : 'pointer',
          background: COLS[metodo] || t.primary, color:'#fff',
          opacity: (enviando||(metodo==='btc'&&!btcPrice)) ? 0.7 : 1,
          transition:'background 0.3s',
        }}>
        {enviando ? '⏳ Procesando…'
          : metodo==='tarjeta' ? `💳 Pagar con tarjeta — ${totalEur.toFixed(2)}€`
          : metodo==='bizum'   ? `📱 Pagar con Bizum — ${totalEur.toFixed(2)}€`
          : metodo==='btc'     ? `₿ Pagar con Bitcoin${totalBtc ? ' — '+totalBtc+' BTC':''}`
          :                      `🅿️ Pagar con PayPal — ${totalEur.toFixed(2)}€`}
      </button>

      <div style={{ marginTop:10, fontSize:11, color:t.textLight, textAlign:'center' }}>
        🔒 Pago seguro · Zeus Ventas nunca comparte tus datos
      </div>

    </div>
  );
}

Object.assign(window, { FormaPago });
