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

  function hexToRgba(hex, alpha) {
    var h = String(hex || '#000000').replace('#', '');
    if (h.length === 3) {
      h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];
    }
    var n = parseInt(h, 16);
    if (isNaN(n)) return { r: 0, g: 0, b: 0, a: Math.round((alpha != null ? alpha : 1) * 255) };
    return {
      r: (n >> 16) & 255,
      g: (n >> 8) & 255,
      b: n & 255,
      a: Math.round((alpha != null ? alpha : 1) * 255),
    };
  }

  ARQ.bucketFill = {
    /**
     * Relleno por punto en coordenadas de hoja.
     * Rasteriza la capa, aplica flood fill, reemplaza capa por imagen.
     */
    applyAtSheetPoint: function (layer, sheet, pt) {
      var w = sheet.ancho || 1920;
      var h = sheet.alto || 1080;
      var px = Math.floor(pt.x);
      var py = Math.floor(pt.y);
      if (px < 0 || py < 0 || px >= w || py >= h) return Promise.resolve(0);

      return ARQ.canvasEngine.preloadLayerImages(sheet, [layer]).then(function () {
        var c = global.document.createElement('canvas');
        c.width = w;
        c.height = h;
        var ctx = c.getContext('2d');
        if (!ctx) return Promise.reject(new Error('Canvas'));
        ctx.clearRect(0, 0, w, h);
        ctx.save();
        ctx.globalAlpha = layer.opacidad != null ? layer.opacidad : 1;
        ARQ.canvasEngine.renderLayersToContext(ctx, sheet, [layer], { includeBackground: false });
        ctx.restore();

        var imageData = ctx.getImageData(0, 0, w, h);
        var col = hexToRgba(ARQ.tools.color, ARQ.tools.opacity);
        var tol = 48;
        if (ARQ.tools.colorMaterialId && ARQ.store.getProject() && ARQ.store.getProject().materiales) {
          var mats = ARQ.store.getProject().materiales;
          var mi;
          for (mi = 0; mi < mats.length; mi++) {
            if (mats[mi].id === ARQ.tools.colorMaterialId && mats[mi].hex) {
              col = hexToRgba(mats[mi].hex, ARQ.tools.opacity);
              break;
            }
          }
        }
        var bTol = ARQ.tools.bucketTolerance != null ? ARQ.tools.bucketTolerance : tol;
        var bContig = ARQ.tools.bucketContiguous !== false;
        var filled = ARQ.floodFill.apply(imageData, w, h, px, py, col.r, col.g, col.b, col.a, bTol, bContig);
        if (filled < 1) return 0;
        ctx.putImageData(imageData, 0, 0);
        var dataUrl = c.toDataURL('image/png');

        layer.contenido = layer.contenido || {};
        layer.contenido.strokes = [];
        layer.contenido.shapes = [];
        layer.contenido.texts = [];
        layer.contenido.imageSrc = dataUrl;
        layer.contenido.imageTransform = {
          x: 0,
          y: 0,
          w: w,
          h: h,
          rotation: 0,
          naturalW: w,
          naturalH: h,
        };
        delete layer.contenido.imageTransform.corners;
        layer.tipo = 'imagen';
        ARQ.store.setDirty(true);
        ARQ.canvasEngine.requestRedraw();
        return filled;
      });
    },
  };
})(typeof window !== 'undefined' ? window : this);
