// Shared watermark helper — applies the PIXFIXCO · DEMO overlay to any image URL
// (data:, blob:, or http(s):) and returns a JPEG data URL. Used by Uploader for
// both the real Kie-enhanced result and the local-only simulate fallback.
//
// applyFakeFilters=true bumps brightness/contrast/saturation in canvas — only
// used when there is no real backend (the simulate fallback). For real Kie
// output we trust the model's enhancement and just stamp the watermark.
window.applyDemoWatermark = async function applyDemoWatermark(srcUrl, opts = {}) {
  const applyFakeFilters = !!opts.applyFakeFilters;
  const maxW = opts.maxWidth || 1600;

  const img = new Image();
  img.src = srcUrl;
  await new Promise((res, rej) => {
    img.onload = res;
    img.onerror = () => rej(new Error("could not load image for watermarking"));
  });

  const canvas = document.createElement("canvas");
  const scale = Math.min(1, maxW / img.width);
  canvas.width = img.width * scale;
  canvas.height = img.height * scale;
  const ctx = canvas.getContext("2d");

  if (applyFakeFilters) {
    ctx.filter = "brightness(1.18) contrast(1.22) saturate(1.25)";
  }
  ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
  ctx.filter = "none";

  // Bottom-right plate: "PIXFIXCO · DEMO"
  ctx.font = `${Math.max(18, canvas.width * 0.022)}px ui-sans-serif, system-ui`;
  ctx.textBaseline = "bottom";
  const label = "PIXFIXCO · DEMO";
  const pad = canvas.width * 0.02;
  const tw = ctx.measureText(label).width;
  ctx.fillStyle = "rgba(0,0,0,0.45)";
  ctx.fillRect(canvas.width - tw - pad * 2.2, canvas.height - pad * 2.4, tw + pad * 1.4, pad * 1.8);
  ctx.fillStyle = "rgba(255,255,255,0.95)";
  ctx.fillText(label, canvas.width - tw - pad * 1.5, canvas.height - pad);

  // Diagonal "PIXFIXCO" overlay
  ctx.save();
  ctx.translate(canvas.width / 2, canvas.height / 2);
  ctx.rotate(-Math.PI / 6);
  ctx.font = `700 ${canvas.width * 0.08}px ui-sans-serif, system-ui`;
  ctx.textAlign = "center";
  ctx.fillStyle = "rgba(255,255,255,0.14)";
  ctx.fillText("PIXFIXCO", 0, 0);
  ctx.restore();

  return canvas.toDataURL("image/jpeg", 0.9);
};
