// Marketing card generator — 1080x1350 PNG listo para Instagram
// Pure Canvas API, zero dependencies

function _rrPath(c, x, y, w, h, r) {
  c.beginPath();
  c.moveTo(x + r, y);
  c.arcTo(x + w, y,     x + w, y + h, r);
  c.arcTo(x + w, y + h, x,     y + h, r);
  c.arcTo(x,     y + h, x,     y,     r);
  c.arcTo(x,     y,     x + w, y,     r);
  c.closePath();
}

function _drawCard(c, W, H, product, user, img, affiliateLink) {
  // ── Background ───────────────────────────────────────────────
  const bg = c.createLinearGradient(0, 0, 0, H);
  bg.addColorStop(0, '#0C1122');
  bg.addColorStop(1, '#070A12');
  c.fillStyle = bg;
  c.fillRect(0, 0, W, H);

  // Subtle grid
  c.strokeStyle = 'rgba(255,255,255,0.022)';
  c.lineWidth = 1;
  for (let x = 0; x <= W; x += 44) { c.beginPath(); c.moveTo(x, 0); c.lineTo(x, H); c.stroke(); }
  for (let y = 0; y <= H; y += 44) { c.beginPath(); c.moveTo(0, y); c.lineTo(W, y); c.stroke(); }

  // Ambient glow — top left blue
  const g1 = c.createRadialGradient(80, -80, 0, 80, -80, 780);
  g1.addColorStop(0, 'rgba(91,140,255,0.26)');
  g1.addColorStop(1, 'transparent');
  c.fillStyle = g1; c.fillRect(0, 0, W, H);

  // Ambient glow — top right purple
  const g2 = c.createRadialGradient(W + 60, -60, 0, W + 60, -60, 620);
  g2.addColorStop(0, 'rgba(138,91,255,0.22)');
  g2.addColorStop(1, 'transparent');
  c.fillStyle = g2; c.fillRect(0, 0, W, H);

  // Ambient glow — bottom green
  const g3 = c.createRadialGradient(W / 2, H + 40, 0, W / 2, H + 40, 500);
  g3.addColorStop(0, 'rgba(0,224,164,0.1)');
  g3.addColorStop(1, 'transparent');
  c.fillStyle = g3; c.fillRect(0, 0, W, H);

  // ── Top bar ───────────────────────────────────────────────────
  // Logo box gradient
  const logoGrad = c.createLinearGradient(58, 58, 114, 114);
  logoGrad.addColorStop(0, '#6B9AFF');
  logoGrad.addColorStop(1, '#7A4BDF');
  c.fillStyle = logoGrad;
  _rrPath(c, 58, 58, 62, 62, 16); c.fill();

  // Logo glow
  const logoGlow = c.createRadialGradient(89, 89, 0, 89, 89, 50);
  logoGlow.addColorStop(0, 'rgba(91,140,255,0.35)');
  logoGlow.addColorStop(1, 'transparent');
  c.fillStyle = logoGlow; c.fillRect(40, 40, 100, 100);

  // 兄 glyph
  c.font = 'bold 32px serif';
  c.fillStyle = '#fff';
  c.textAlign = 'center';
  c.textBaseline = 'middle';
  c.fillText('兄', 89, 91);

  c.textBaseline = 'alphabetic';
  c.textAlign = 'left';
  c.font = 'bold 30px "Sora", system-ui, sans-serif';
  c.fillStyle = '#E6EAF2';
  c.fillText('Kyoudai', 134, 91);

  c.font = '18px "JetBrains Mono", "Courier New", monospace';
  c.fillStyle = 'rgba(138,147,166,0.7)';
  c.fillText('SELLER PLATFORM', 136, 113);

  // ── Product image area ────────────────────────────────────────
  const IX = 66, IY = 152, IW = W - 132, IH = 840;

  // Card bg
  const cardBg = c.createLinearGradient(IX, IY, IX, IY + IH);
  cardBg.addColorStop(0, '#161D30');
  cardBg.addColorStop(1, '#0E1220');
  c.fillStyle = cardBg;
  _rrPath(c, IX, IY, IW, IH, 32); c.fill();

  // Card border
  c.strokeStyle = 'rgba(255,255,255,0.1)';
  c.lineWidth = 1.5;
  _rrPath(c, IX, IY, IW, IH, 32); c.stroke();

  if (img) {
    c.save();
    _rrPath(c, IX, IY, IW, IH, 32); c.clip();
    // Scale to cover keeping aspect ratio
    const scale = Math.max(IW / img.width, IH / img.height) * 0.92;
    const sw = img.width * scale;
    const sh = img.height * scale;
    c.drawImage(img, IX + (IW - sw) / 2, IY + (IH - sh) / 2, sw, sh);
    // Gradient overlay at bottom
    const ov = c.createLinearGradient(0, IY + IH * 0.48, 0, IY + IH);
    ov.addColorStop(0, 'transparent');
    ov.addColorStop(1, 'rgba(7,10,18,0.72)');
    c.fillStyle = ov; c.fillRect(IX, IY, IW, IH);
    c.restore();
  } else {
    // No image fallback — motif gradient
    c.save();
    _rrPath(c, IX, IY, IW, IH, 32); c.clip();
    const motif = c.createRadialGradient(W / 2, IY + IH * 0.4, 0, W / 2, IY + IH * 0.4, 420);
    motif.addColorStop(0, 'rgba(91,140,255,0.3)');
    motif.addColorStop(0.6, 'rgba(138,91,255,0.15)');
    motif.addColorStop(1, 'transparent');
    c.fillStyle = motif; c.fillRect(IX, IY, IW, IH);
    // Glyph
    c.font = 'bold 220px serif';
    c.fillStyle = 'rgba(255,255,255,0.04)';
    c.textAlign = 'center';
    c.textBaseline = 'middle';
    c.fillText('兄', W / 2, IY + IH / 2);
    c.textAlign = 'left';
    c.textBaseline = 'alphabetic';
    c.restore();
  }

  // Inner glow top of image
  c.save();
  _rrPath(c, IX, IY, IW, IH, 32); c.clip();
  const ig = c.createRadialGradient(W / 2, IY + 60, 0, W / 2, IY + 60, 380);
  ig.addColorStop(0, 'rgba(91,140,255,0.1)');
  ig.addColorStop(1, 'transparent');
  c.fillStyle = ig; c.fillRect(IX, IY, IW, IH);
  c.restore();

  // ── Info section ──────────────────────────────────────────────
  const IFY = IY + IH + 32;

  // Series / certified label
  c.font = '500 20px "JetBrains Mono", "Courier New", monospace';
  c.fillStyle = 'rgba(138,147,166,0.65)';
  c.textAlign = 'left';
  c.fillText('MAICKJP.COM  ·  PSA CERTIFIED', 66, IFY);

  // Product name
  c.font = 'bold 52px "Sora", system-ui, sans-serif';
  c.fillStyle = '#E6EAF2';
  let name = product.name || 'Producto';
  if (name.length > 22) name = name.slice(0, 22) + '…';
  c.fillText(name, 66, IFY + 66);

  // Price
  c.font = '400 32px "Sora", system-ui, sans-serif';
  c.fillStyle = 'rgba(230,234,242,0.5)';
  c.fillText('€' + (product.price || 0).toFixed(2), 66, IFY + 112);

  // Separator
  c.strokeStyle = 'rgba(255,255,255,0.07)';
  c.lineWidth = 1;
  c.beginPath(); c.moveTo(66, IFY + 136); c.lineTo(W - 66, IFY + 136); c.stroke();

  // Commission pill
  const CX = 66, CY = IFY + 154, CW = 480, CH = 78;
  const cBg = c.createLinearGradient(CX, CY, CX + CW, CY);
  cBg.addColorStop(0, 'rgba(0,224,164,0.2)');
  cBg.addColorStop(1, 'rgba(0,224,164,0.03)');
  c.fillStyle = cBg; _rrPath(c, CX, CY, CW, CH, 18); c.fill();
  c.strokeStyle = 'rgba(0,224,164,0.4)'; c.lineWidth = 1.5;
  _rrPath(c, CX, CY, CW, CH, 18); c.stroke();

  c.font = '500 19px "JetBrains Mono", "Courier New", monospace';
  c.fillStyle = 'rgba(62,232,190,0.8)';
  c.fillText('TÚ GANAS', CX + 24, CY + 26);
  c.font = 'bold 34px "Sora", system-ui, sans-serif';
  c.fillStyle = '#3EE8BE';
  c.fillText('+€' + (product.commission || 0).toFixed(2) + ' por venta', CX + 24, CY + 58);

  // Affiliate handle
  if (user && user.handle) {
    c.font = '500 22px "JetBrains Mono", "Courier New", monospace';
    c.fillStyle = 'rgba(138,147,166,0.55)';
    c.textAlign = 'right';
    c.fillText('@' + user.handle, W - 66, IFY + 200);
  }

  // ── Bottom URL bar ────────────────────────────────────────────
  const BY = H - 110;
  const barBg = c.createLinearGradient(0, BY, 0, H);
  barBg.addColorStop(0, 'rgba(91,140,255,0.09)');
  barBg.addColorStop(1, 'rgba(91,140,255,0.04)');
  c.fillStyle = barBg; c.fillRect(0, BY, W, H - BY);

  c.strokeStyle = 'rgba(91,140,255,0.22)'; c.lineWidth = 1;
  c.beginPath(); c.moveTo(0, BY); c.lineTo(W, BY); c.stroke();

  // Show affiliate tracking link — this is what drives commissions
  var displayLink = affiliateLink || 'www.maickjp.com';
  // Trim protocol for cleaner display
  displayLink = displayLink.replace(/^https?:\/\//, '');

  c.textAlign = 'center';
  c.textBaseline = 'middle';

  // "LINK DE COMPRA" label
  c.font = '500 18px "JetBrains Mono", "Courier New", monospace';
  c.fillStyle = 'rgba(110,160,255,0.55)';
  c.fillText('LINK DE COMPRA', W / 2, BY + 28);

  // The actual link — bold, prominent
  c.font = 'bold 30px "JetBrains Mono", "Courier New", monospace';
  c.fillStyle = 'rgba(110,160,255,0.95)';
  // If link is long, reduce font size
  if (displayLink.length > 32) {
    c.font = 'bold 24px "JetBrains Mono", "Courier New", monospace';
  }
  c.fillText(displayLink, W / 2, BY + 70);
}

function generateMarketingCard(product, user, onReady, affiliateLink) {
  const W = 1080, H = 1350;
  const canvas = document.createElement('canvas');
  canvas.width = W; canvas.height = H;
  const ctx = canvas.getContext('2d');

  // Resolve affiliate link: prefer passed link, then LINKS lookup, then fallback
  var link = affiliateLink;
  if (!link) {
    var linkObj = (window.KYOUDAI.LINKS || []).find(function(l) { return l.productId === product.id; });
    link = linkObj ? linkObj.displayUrl : (window.KYOUDAI_CONFIG.shopUrl + '/products/' + product.slug + '?ref=' + (user.referral || ''));
    if (link) link = link.replace(/^https?:\/\//, '');
  }

  function finish(img) {
    _drawCard(ctx, W, H, product, user, img, link);
    onReady(canvas.toDataURL('image/png'));
  }

  var doRender = function() {
    if (product.imageUrl) {
      var img = new Image();
      img.crossOrigin = 'anonymous';
      img.onload = function() { finish(img); };
      img.onerror = function() { finish(null); };
      img.src = product.imageUrl;
    } else {
      finish(null);
    }
  };

  if (document.fonts && document.fonts.ready) {
    document.fonts.ready.then(doRender);
  } else {
    doRender();
  }
}

function CardPreviewModal({ product, user, onClose }) {
  const [dataUrl, setDataUrl] = React.useState(null);

  React.useEffect(() => {
    generateMarketingCard(product, user, function(url) {
      setDataUrl(url);
    });
  }, []);

  function download() {
    var a = document.createElement('a');
    a.download = 'maickjp-' + (product.slug || product.id) + '.png';
    a.href = dataUrl;
    a.click();
  }

  return (
    <div onClick={e => { if (e.target === e.currentTarget) onClose(); }}
      style={{ position:'fixed', inset:0, zIndex:1000, background:'rgba(0,0,0,0.88)',
               backdropFilter:'blur(8px)', display:'flex', alignItems:'center',
               justifyContent:'center', flexDirection:'column', gap:20, padding:24 }}>

      {/* Preview */}
      <div style={{ position:'relative' }}>
        {!dataUrl && (
          <div className="glass" style={{ width:320, height:400, display:'grid', placeItems:'center', borderRadius:22 }}>
            <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:12 }}>
              <div className="skel" style={{ width:48, height:48, borderRadius:12 }}/>
              <div style={{ fontSize:13, color:'var(--sub)' }}>Generando tarjeta…</div>
            </div>
          </div>
        )}
        {dataUrl && (
          <img src={dataUrl} alt="Marketing card"
            style={{ width:320, height:400, borderRadius:22, display:'block',
                     boxShadow:'0 0 0 1px rgba(255,255,255,0.08), 0 40px 100px -20px rgba(0,0,0,0.95)' }}/>
        )}
      </div>

      {/* Actions */}
      <div style={{ display:'flex', gap:10, alignItems:'center' }}>
        <button className="btn" onClick={onClose}>Cerrar</button>
        <button className="btn btn-primary" onClick={download} disabled={!dataUrl}
          style={{ gap:8, height:40, paddingLeft:18, paddingRight:18 }}>
          <I.download style={{ width:14, height:14 }}/> Descargar PNG
        </button>
      </div>

      <div style={{ fontSize:11, color:'var(--dim)', textAlign:'center', lineHeight:1.6 }}>
        1080 × 1350 px · Instagram Feed & Stories
      </div>
    </div>
  );
}

window.generateMarketingCard = generateMarketingCard;
window.CardPreviewModal = CardPreviewModal;
