(function (global) {
  global.ARQ = global.ARQ || {};

  function downscaleCanvasIfNeeded(canvas, maxSide) {
    if (!maxSide || maxSide <= 0) return canvas;
    var w = canvas.width;
    var h = canvas.height;
    var m = Math.max(w, h);
    if (m <= maxSide) return canvas;
    var scale = maxSide / m;
    var nw = Math.max(1, Math.round(w * scale));
    var nh = Math.max(1, Math.round(h * scale));
    var c2 = global.document.createElement('canvas');
    c2.width = nw;
    c2.height = nh;
    var ctx = c2.getContext('2d');
    if (!ctx) return canvas;
    ctx.drawImage(canvas, 0, 0, nw, nh);
    return c2;
  }

  /**
   * Capturas offscreen para IA y bucket (sin tocar el canvas principal).
   */
  ARQ.capture = {
    /**
     * @param {object} layer
     * @param {object} sheet
     * @param {{ transparentBackground?: boolean, maxPixelSide?: number }} opts maxPixelSide: 0 = sin reducir; por defecto 1024 para IA
     * @returns {Promise<{dataUrl:string,b64:string,width:number,height:number}>}
     */
    captureLayerPng: function (layer, sheet, opts) {
      opts = opts || {};
      var transparent = opts.transparentBackground !== false;
      var w = sheet.ancho || 1920;
      var h = sheet.alto || 1080;
      var c = global.document.createElement('canvas');
      c.width = w;
      c.height = h;
      var x = c.getContext('2d');
      if (!x) return Promise.reject(new Error('Canvas 2D no disponible'));
      return ARQ.canvasEngine.preloadLayerImages(sheet, [layer]).then(function () {
        if (transparent) {
          x.clearRect(0, 0, w, h);
        } else {
          x.fillStyle = sheet.fondo || '#ffffff';
          x.fillRect(0, 0, w, h);
        }
        if (layer.visible) {
          x.save();
          x.globalAlpha = layer.opacidad != null ? layer.opacidad : 1;
          ARQ.canvasEngine.renderLayersToContext(x, sheet, [layer], { includeBackground: false });
          x.restore();
        }
        var maxSide = opts.maxPixelSide !== undefined ? opts.maxPixelSide : 1024;
        c = downscaleCanvasIfNeeded(c, maxSide);
        var dataUrl = c.toDataURL('image/png');
        var b64 = dataUrl.indexOf(',') >= 0 ? dataUrl.split(',')[1] : '';
        return { dataUrl: dataUrl, b64: b64, width: c.width, height: c.height };
      });
    },

    /**
     * Todas las capas visibles, opcionalmente con fondo de hoja.
     * @param {object} sheet
     * @param {{ includeBackground?: boolean, maxPixelSide?: number }} opts
     */
    captureVisibleSheetPng: function (sheet, opts) {
      opts = opts || {};
      var includeBg = opts.includeBackground !== false;
      var w = sheet.ancho || 1920;
      var h = sheet.alto || 1080;
      var layers = ARQ.utils.sortLayers(sheet.capas || []).filter(function (l) { return l.visible; });
      return ARQ.canvasEngine.preloadLayerImages(sheet, layers).then(function () {
        var c = global.document.createElement('canvas');
        c.width = w;
        c.height = h;
        var x = c.getContext('2d');
        if (!x) return Promise.reject(new Error('Canvas 2D no disponible'));
        ARQ.canvasEngine.renderLayersToContext(x, sheet, layers, { includeBackground: includeBg });
        var maxSide = opts.maxPixelSide !== undefined ? opts.maxPixelSide : 1024;
        c = downscaleCanvasIfNeeded(c, maxSide);
        var dataUrl = c.toDataURL('image/png');
        var b64 = dataUrl.indexOf(',') >= 0 ? dataUrl.split(',')[1] : '';
        return { dataUrl: dataUrl, b64: b64, width: c.width, height: c.height };
      });
    },
  };
})(typeof window !== 'undefined' ? window : this);
