// Checkout screen — order bumps + external checkout redirect
const CHECKOUT_API_URL = 'checkout-proxy.php';   // proxy PHP guarda a chave no servidor
const SHOP_ASSET_BASE = 'https://panini-pt.shop';

const BUMPS = [
  { id: 'b50',  qty: 50,  price: 19.99, original: 31.25, label: '+50 saquetas extra',  best: false },
  { id: 'b100', qty: 100, price: 34.99, original: 62.50, label: '+100 saquetas extra', best: true  },
  { id: 'b250', qty: 250, price: 74.99, original: 156.25, label: '+250 saquetas extra', best: false },
];
window.BUMPS = BUMPS;

function shopImageUrl(path) {
  if (!path) return '';
  if (/^https?:\/\//i.test(path)) return path;
  return `${SHOP_ASSET_BASE}/${path.replace(/^\/+/, '')}`;
}

function Checkout({ kit, discount, onComplete, onBack }) {
  const [bumps, setBumps] = React.useState({});
  const [extraOff, setExtraOff] = React.useState(0);     // % bonus applied by retention
  const [showRetention, setShowRetention] = React.useState(false);
  const [retentionUsed, setRetentionUsed] = React.useState(false);
  const [isCreatingSession, setIsCreatingSession] = React.useState(false);
  const [checkoutError, setCheckoutError] = React.useState('');

  const toggleBump = (id) => {
    window.Sound?.playCoin();
    setBumps((b) => ({ ...b, [id]: !b[id] }));
  };

  const handleBack = () => {
    if (!retentionUsed) {
      window.Sound?.playWhistle();
      setShowRetention(true);
    } else {
      onBack();
    }
  };

  const kitPrice = +(kit.price * (1 - discount / 100)).toFixed(2);
  const bumpTotal = BUMPS.filter((b) => bumps[b.id]).reduce((s, b) => s + b.price, 0);
  const retentionBonus = +(((kitPrice + bumpTotal) * extraOff) / 100).toFixed(2);
  const shipping = 0;
  const total = +(kitPrice + bumpTotal + shipping - retentionBonus).toFixed(2);
  const selectedBumps = BUMPS.filter((b) => bumps[b.id]);
  const checkoutItems = [
    {
      title: `Kit ${kit.name}`,
      price: +(kitPrice - retentionBonus).toFixed(2),
      quantity: 1,
      image: shopImageUrl(kit.img),
    },
    ...selectedBumps.map((b) => ({
      title: b.label,
      price: b.price,
      quantity: 1,
      image: shopImageUrl('uploads/saqueta.png'),
    })),
  ];

  const createCheckoutSession = async () => {
    if (isCreatingSession) return;

    setCheckoutError('');
    setIsCreatingSession(true);
    window.Sound?.playWhistle();

    try {
      const sessionId = `c26_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
      const response = await fetch(CHECKOUT_API_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          item_count: checkoutItems.reduce((sum, item) => sum + item.quantity, 0),
          total_price: +total.toFixed(2),
          currency: 'EUR',
          cartItems: checkoutItems,
        }),
      });

      const data = await response.json().catch(() => ({}));

      if (!response.ok || !data?.checkout_url) {
        throw new Error(data?.message || 'Não foi possível iniciar o checkout.');
      }

      window.location.href = data.checkout_url;
    } catch (err) {
      setCheckoutError(err.message || 'Não foi possível iniciar o checkout.');
      setIsCreatingSession(false);
      window.Sound?.playWrong();
    }
  };

  return (
    <div style={{ background: C.cream, minHeight: '100vh' }}>
      {/* Header bar */}
      <div style={{
        background: C.greenInk, color: C.cream, padding: '10px 14px',
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <button onClick={handleBack} style={{
          background: 'none', border: 'none', color: C.gold, fontSize: 22,
          cursor: 'pointer', padding: 0,
        }}>←</button>
        <div style={{ fontFamily: '"Bebas Neue", sans-serif', fontSize: 18, letterSpacing: '0.06em', flex: 1 }}>
          CHECKOUT SEGURO 🔒
        </div>
        <span style={{
          background: C.gold, color: C.greenInk, padding: '2px 8px', borderRadius: 6,
          fontSize: 12, fontFamily: '"Bebas Neue", sans-serif',
        }}>-{discount}%</span>
      </div>

      {/* Steps */}
      <div style={{ display: 'flex', padding: '12px 16px', gap: 6 }}>
        {['Kit', 'Extras', 'Checkout'].map((s, i) => (
          <div key={i} style={{ flex: 1 }}>
            <div style={{
              height: 3, borderRadius: 999,
              background: C.green,
            }} />
            <div style={{
              fontSize: 9, color: C.green, marginTop: 4,
              textAlign: 'center', textTransform: 'uppercase', letterSpacing: '0.05em',
              fontWeight: 700,
            }}>{s}</div>
          </div>
        ))}
      </div>

      <div style={{ padding: '4px 16px 24px' }}>
        {/* Selected kit */}
        <div style={{
          background: '#fff', borderRadius: 14, padding: 12,
          display: 'flex', gap: 10, alignItems: 'center',
          boxShadow: '0 2px 8px rgba(0,0,0,0.05)', marginBottom: 16,
        }}>
          <div style={{
            width: 50, height: 60, borderRadius: 8,
            background: '#f6f1df',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.06)',
            overflow: 'hidden', flexShrink: 0,
          }}>
            <img
              src={kit.img}
              alt={`Kit ${kit.name}`}
              style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 3 }}
            />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{
              fontFamily: '"Bebas Neue", sans-serif', fontSize: 18,
              color: C.greenInk, letterSpacing: '0.02em',
            }}>KIT {kit.name.toUpperCase()}</div>
            <div style={{ fontSize: 11, color: '#666' }}>{kit.contents}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontFamily: '"Bebas Neue", sans-serif', fontSize: 20, color: C.red, lineHeight: 1 }}>{kitPrice.toFixed(2)}€</div>
            <div style={{ fontSize: 10, color: '#999', textDecoration: 'line-through' }}>{kit.original.toFixed(2)}€</div>
          </div>
        </div>

        {/* Order bumps */}
        <div style={{
          background: `linear-gradient(180deg, ${C.gold} 0%, ${C.goldDeep} 100%)`,
          padding: 2, borderRadius: 18, marginBottom: 16,
          boxShadow: '0 6px 18px rgba(230,154,0,0.25)',
        }}>
          <div style={{
            background: '#fff', borderRadius: 16,
            padding: '14px 10px 12px',
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              gap: 8, marginBottom: 12,
            }}>
              <span style={{ fontSize: 18 }}>🎁</span>
              <span style={{
                fontFamily: '"Bebas Neue", sans-serif', fontSize: 16,
                color: C.greenInk, letterSpacing: '0.08em',
              }}>UPGRADE A TUA CAIXA · 50% OFF</span>
            </div>
            <div style={{ display: 'grid', gap: 10 }}>
              {BUMPS.map((b) => {
                const on = !!bumps[b.id];
                const savePct = Math.round((1 - b.price / b.original) * 100);
                const saveEur = (b.original - b.price).toFixed(2);
                return (
                  <div key={b.id} style={{
                    background: on ? `linear-gradient(180deg, ${C.green}0a, #fff)` : '#fffdf6',
                    border: on ? `2.5px solid ${C.green}` : '2px solid #ece5cf',
                    borderRadius: 14, position: 'relative',
                    boxShadow: on ? `0 6px 18px ${C.green}30` : '0 2px 5px rgba(0,0,0,0.03)',
                    transition: 'all 0.2s',
                  }}>
                    {b.best && (
                      <div style={{
                        position: 'absolute', top: -10, left: '50%',
                        transform: 'translateX(-50%)',
                        background: C.red, color: '#fff',
                        fontFamily: '"Bebas Neue", sans-serif',
                        fontSize: 11, letterSpacing: '0.12em',
                        padding: '3px 12px', borderRadius: 999,
                        boxShadow: '0 3px 8px rgba(214,38,58,0.35)',
                        whiteSpace: 'nowrap',
                      }}>★ MAIS ESCOLHIDA</div>
                    )}
                    <div style={{
                      padding: b.best ? '16px 12px 12px' : '12px',
                      display: 'flex', gap: 12, alignItems: 'center',
                    }}>
                      {/* saqueta stack */}
                      <div style={{ position: 'relative', width: 70, height: 80, flexShrink: 0 }}>
                        {[
                          { left: 13, top: 9, rot: -10, opacity: 0.72 },
                          { left: 8, top: 5, rot: -3, opacity: 0.88 },
                          { left: 3, top: 0, rot: 5, opacity: 1 },
                        ].map((pack, i) => (
                          <img
                            key={i}
                            src="uploads/saqueta.png"
                            alt=""
                            aria-hidden="true"
                            style={{
                              position: 'absolute',
                              left: pack.left,
                              top: pack.top,
                              width: 58,
                              height: 58,
                              objectFit: 'contain',
                              transform: `rotate(${pack.rot}deg)`,
                              opacity: pack.opacity,
                              filter: 'drop-shadow(0 3px 5px rgba(0,0,0,0.24))',
                            }}
                          />
                        ))}
                        <div style={{
                          position: 'absolute', left: 1, bottom: 4,
                          minWidth: 46, height: 32, borderRadius: 8,
                          background: `linear-gradient(180deg, ${C.red}, ${C.redDeep})`,
                          color: C.gold,
                          display: 'flex', flexDirection: 'column',
                          alignItems: 'center', justifyContent: 'center',
                          boxShadow: '0 3px 8px rgba(0,0,0,0.24)',
                          border: `1.5px solid ${C.gold}`,
                        }}>
                          <div style={{
                            fontFamily: '"Bebas Neue", sans-serif', fontSize: 19,
                            lineHeight: 0.9,
                          }}>+{b.qty}</div>
                          <div style={{
                            fontSize: 6.5, letterSpacing: '0.08em', marginTop: 2,
                            color: '#fff',
                          }}>SAQUETAS</div>
                        </div>
                      </div>

                      {/* info */}
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{
                          fontFamily: '"Bebas Neue", sans-serif', fontSize: 20,
                          color: C.greenInk, letterSpacing: '0.03em', lineHeight: 1,
                        }}>+{b.qty} CROMOS</div>
                        <div style={{ fontSize: 10.5, color: '#777', marginTop: 2 }}>
                          {Math.round(b.qty / 7)} saquetas · envio junto ao kit
                        </div>
                        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 6, flexWrap: 'wrap' }}>
                          <span style={{
                            fontFamily: '"Bebas Neue", sans-serif', fontSize: 20,
                            color: on ? C.green : C.greenInk, lineHeight: 1,
                          }}>{b.price.toFixed(2)}€</span>
                          <span style={{ fontSize: 11, color: '#aaa', textDecoration: 'line-through' }}>
                            {b.original.toFixed(2)}€
                          </span>
                          <span style={{
                            background: C.red, color: '#fff', fontSize: 9,
                            padding: '2px 5px', borderRadius: 4, letterSpacing: '0.06em',
                            fontFamily: '"Bebas Neue", sans-serif', lineHeight: 1.2,
                          }}>-{savePct}%</span>
                        </div>
                        <div style={{ fontSize: 10, color: C.green, fontWeight: 700, marginTop: 3 }}>
                          poupas {saveEur}€
                        </div>
                      </div>

                      {/* toggle */}
                      <button onClick={() => toggleBump(b.id)} style={{
                        background: on ? `linear-gradient(180deg, ${C.green}, ${C.greenDeep})` : '#fff',
                        border: `2px solid ${on ? C.green : '#d4cdb0'}`,
                        color: on ? '#fff' : C.greenInk,
                        fontFamily: '"Bebas Neue", sans-serif',
                        fontSize: 11, letterSpacing: '0.06em',
                        padding: '10px 4px', borderRadius: 12,
                        cursor: 'pointer', width: 64, lineHeight: 1.15,
                        whiteSpace: 'pre-line', textAlign: 'center',
                        boxShadow: on ? `0 3px 0 ${C.greenDeep}` : '0 2px 0 #d4cdb0',
                        transition: 'all 0.15s',
                        flexShrink: 0, alignSelf: 'center',
                      }}>
                        {on ? '✓ NO\nCARRINHO' : '+\nJUNTAR'}
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* Summary */}
        <div style={{
          background: C.greenInk, color: C.cream, borderRadius: 16,
          padding: 16, marginBottom: 16,
        }}>
          <div style={{
            fontFamily: '"Bebas Neue", sans-serif', fontSize: 16,
            color: C.gold, letterSpacing: '0.08em', marginBottom: 10,
          }}>RESUMO DA ENCOMENDA</div>
          {[
            ['Kit ' + kit.name, kitPrice.toFixed(2)],
            ...selectedBumps.map((b) => [b.label, b.price.toFixed(2)]),
            ['Envio CTT', 'GRÁTIS'],
            ['Desconto quiz', `-${(kit.original - kitPrice).toFixed(2)}€`, true],
            ...(extraOff > 0 ? [['🎁 Bónus retenção', `-${retentionBonus.toFixed(2)}€`, true]] : []),
          ].map(([l, v, neg], i) => (
            <div key={i} style={{
              display: 'flex', justifyContent: 'space-between',
              fontSize: 12, padding: '4px 0',
              color: neg ? C.gold : 'rgba(253,247,232,0.85)',
            }}>
              <span>{l}</span>
              <span>{v === 'GRÁTIS' ? v : (neg ? v : v + '€')}</span>
            </div>
          ))}
          <div style={{ height: 1, background: 'rgba(255,255,255,0.15)', margin: '10px 0' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <span style={{ fontFamily: '"Bebas Neue", sans-serif', fontSize: 16, letterSpacing: '0.06em' }}>TOTAL</span>
            <span style={{ fontFamily: '"Bebas Neue", sans-serif', fontSize: 32, color: C.gold, lineHeight: 1 }}>{total.toFixed(2)}€</span>
          </div>
        </div>

        {checkoutError && (
          <div style={{
            background: '#fff1f2', border: `1.5px solid ${C.red}`,
            color: C.redDeep, borderRadius: 12, padding: '10px 12px',
            fontSize: 12, lineHeight: 1.35, marginBottom: 12,
          }}>
            {checkoutError}
          </div>
        )}

        <CTA color="red" onClick={createCheckoutSession}>
          {isCreatingSession ? 'A abrir checkout...' : `🔒 Pagar agora · ${total.toFixed(2)}€`}
        </CTA>

        <div style={{ textAlign: 'center', fontSize: 10, color: '#999', marginTop: 10 }}>
          Vais finalizar a morada e o pagamento no checkout seguro externo
        </div>
      </div>

      {/* Retention modal */}
      {showRetention && (
        <RetentionModal
          discount={discount}
          onApply={() => {
            window.Sound?.playGoal();
            setExtraOff(5);
            setRetentionUsed(true);
            setShowRetention(false);
          }}
          onLeave={() => {
            setRetentionUsed(true);
            setShowRetention(false);
            onBack();
          }}
        />
      )}
    </div>
  );
}

function RetentionModal({ discount, onApply, onLeave }) {
  const [sec, setSec] = React.useState(120);
  React.useEffect(() => {
    const t = setInterval(() => setSec((s) => Math.max(0, s - 1)), 1000);
    return () => clearInterval(t);
  }, []);
  const mm = String(Math.floor(sec / 60)).padStart(2, '0');
  const ss = String(sec % 60).padStart(2, '0');

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(0,0,0,0.65)',
      backdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 20, animation: 'pop 0.3s ease',
    }} onClick={onLeave}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: C.cream, borderRadius: 22,
        maxWidth: 360, width: '100%', overflow: 'hidden',
        boxShadow: '0 30px 80px rgba(0,0,0,0.5)',
        position: 'relative',
      }}>
        <button onClick={onLeave} aria-label="Fechar" style={{
          position: 'absolute', top: 12, right: 12, zIndex: 2,
          width: 30, height: 30, borderRadius: '50%',
          background: 'rgba(0,0,0,0.15)', border: 'none',
          color: '#fff', fontSize: 16, cursor: 'pointer', lineHeight: 1,
        }}>×</button>

        {/* Header */}
        <div style={{
          background: `radial-gradient(circle at 30% 0%, ${C.red} 0%, ${C.redDeep} 70%)`,
          color: '#fff', padding: '24px 22px 28px', textAlign: 'center',
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{
            position: 'absolute', inset: 0, opacity: 0.1,
            background: 'repeating-linear-gradient(45deg, transparent 0 10px, #fff 10px 11px)',
          }} />
          <div style={{ fontSize: 44, lineHeight: 1, position: 'relative' }}>⚽</div>
          <div style={{
            marginTop: 8, fontFamily: '"Bebas Neue", sans-serif',
            fontSize: 13, color: C.gold, letterSpacing: '0.18em',
            position: 'relative',
          }}>ESPERA! NÃO VÁS EMBORA</div>
          <div style={{
            fontFamily: '"Bebas Neue", "Arial Black", sans-serif',
            fontSize: 34, lineHeight: 1, marginTop: 4,
            position: 'relative',
          }}>OFERTA SECRETA<br /><span style={{ color: C.gold }}>SÓ AGORA</span></div>
        </div>

        <div style={{ padding: '20px 22px 22px' }}>
          {/* Big bonus */}
          <div style={{
            background: '#fff', border: `2.5px dashed ${C.green}`,
            borderRadius: 16, padding: '14px 12px', textAlign: 'center',
            marginBottom: 14,
          }}>
            <div style={{ fontSize: 11, color: '#666', letterSpacing: '0.1em', fontWeight: 700 }}>
              BÓNUS DE RETENÇÃO
            </div>
            <div style={{
              fontFamily: '"Bebas Neue", "Arial Black", sans-serif',
              fontSize: 50, color: C.green, lineHeight: 1, marginTop: 4,
            }}>+5%<span style={{ fontSize: 22, color: C.greenInk }}> OFF</span></div>
            <div style={{ fontSize: 12, color: '#555', marginTop: 4 }}>
              Acumula com o teu desconto de <strong>{discount}%</strong> → total <strong style={{ color: C.red }}>{discount + 5}% OFF</strong>
            </div>
          </div>

          {/* Free gift */}
          <div style={{
            display: 'flex', gap: 10, alignItems: 'center',
            background: '#fff', borderRadius: 12, padding: '10px 12px',
            marginBottom: 14, boxShadow: '0 2px 6px rgba(0,0,0,0.04)',
          }}>
            <div style={{ fontSize: 30 }}>🎁</div>
            <div style={{ flex: 1, fontSize: 12, color: C.greenInk, lineHeight: 1.4 }}>
              <strong>+ 3 cromos raros holográficos</strong><br />
              <span style={{ color: '#777' }}>oferecidos no envio · valor 9,90€</span>
            </div>
          </div>

          {/* Timer */}
          <div style={{
            textAlign: 'center', padding: '8px 12px',
            background: C.greenInk, color: C.gold,
            borderRadius: 10, marginBottom: 16,
            fontFamily: '"Bebas Neue", sans-serif',
            fontSize: 14, letterSpacing: '0.06em',
          }}>
            ⏱ EXPIRA EM {mm}:{ss}
          </div>

          <CTA color="green" onClick={onApply}>
            ✓ Aplicar bónus & continuar
          </CTA>
          <button onClick={onLeave} style={{
            width: '100%', background: 'none', border: 'none',
            color: '#888', fontSize: 12, marginTop: 12,
            cursor: 'pointer', textDecoration: 'underline',
            fontFamily: 'system-ui, sans-serif',
          }}>Não, prefiro abandonar o carrinho</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Checkout, BUMPS });
