(function (global) {
  global.ARQ = global.ARQ || {};
  ARQ.assets = {
    init: function () {
      var self = this;
      if (global.pdfjsLib && global.pdfjsLib.GlobalWorkerOptions) {
        global.pdfjsLib.GlobalWorkerOptions.workerSrc = '../assets/vendor/pdfjs/pdf.worker.min.js';
      }
      $('#btn-import-image').on('click', function () { $('#input-import-file').trigger('click'); });
      $('#input-import-file').on('change', function (e) {
        var files = e.target.files;
        if (!files || !files.length) return;
        for (var i = 0; i < files.length; i++) {
          self.importFile(files[i]);
        }
        e.target.value = '';
      });
      $('#layer-import-file').on('change', function (e) {
        var files = e.target.files;
        var lid = $(e.target).data('layer-id');
        if (!files || !files.length || !lid) {
          e.target.value = '';
          return;
        }
        self.importFileToLayer(lid, files[0]);
        e.target.value = '';
        $(e.target).removeData('layer-id');
      });
      $('#asset-thumbs').on('click', '.arq-asset-thumb', function () {
        var url = $(this).data('url');
        if (url) self.insertIntoActiveLayer(url);
      });
    },

    importFileToLayer: async function (layerId, file) {
      var self = this;
      if (!file) return;
      var sheet = ARQ.utils.activeSheet(ARQ.store.getProject());
      if (!sheet) return;
      var targetLayer = ARQ.layers.findLayerById(sheet, layerId);
      if (!targetLayer) return;
      if (!ARQ.guards.canDrawOnLayer(targetLayer)) {
        ARQ.bus.emit(ARQ.EVENTS.TOAST, 'Desbloquea y muestra la capa para importar');
        return;
      }
      var name = (file.name || '').toLowerCase();
      var isPdf = file.type === 'application/pdf' || name.endsWith('.pdf');
      if (isPdf) {
        await this.importPdfToLayers(layerId, file);
        return;
      }
      var mb = file.size / (1024 * 1024);
      if (mb > ARQ.MAX_IMAGE_IMPORT_MB) {
        if (!(await ARQ.dialog.confirm('Archivo ~' + mb.toFixed(1) + ' MB. ¿Importar de todos modos?'))) return;
      }
      var reader = new FileReader();
      reader.onload = function () {
        var dataUrl = reader.result;
        self.applyDataUrlToLayer(layerId, dataUrl, file.name);
      };
      reader.readAsDataURL(file);
    },

    importPdfToLayers: async function (targetLayerId, file) {
      var self = this;
      var pdfjsLib = global.pdfjsLib;
      if (!pdfjsLib || !pdfjsLib.getDocument) {
        ARQ.bus.emit(ARQ.EVENTS.TOAST, 'PDF.js no está disponible');
        return;
      }
      var mb = file.size / (1024 * 1024);
      if (mb > ARQ.MAX_IMAGE_IMPORT_MB * 2) {
        if (!(await ARQ.dialog.confirm('PDF ~' + mb.toFixed(1) + ' MB. ¿Continuar?'))) return;
      }
      var inner = function (opCtx) {
        return new Promise(function (resolve, reject) {
          var reader = new FileReader();
          reader.onload = function () {
            var typedarray = new Uint8Array(reader.result);
            pdfjsLib.getDocument({ data: typedarray }).promise.then(function (pdf) {
              var numPages = pdf.numPages;
              var baseLabel = (file.name || 'documento.pdf').replace(/\.[^.]+$/, '');
              var scale = 2;
              var results = [];

              function renderPage(pageNum) {
                return pdf.getPage(pageNum).then(function (page) {
                  var viewport = page.getViewport({ scale: scale });
                  var c = global.document.createElement('canvas');
                  c.width = viewport.width;
                  c.height = viewport.height;
                  var x = c.getContext('2d');
                  return page.render({ canvasContext: x, viewport: viewport }).promise.then(function () {
                    return { dataUrl: c.toDataURL('image/png'), w: c.width, h: c.height };
                  });
                });
              }

              var chain = Promise.resolve();
              var p;
              for (p = 1; p <= numPages; p++) {
                (function (pg) {
                  chain = chain.then(function () {
                    if (opCtx && opCtx.id && ARQ.ops && ARQ.ops.step) {
                      var pct = numPages ? Math.min(99, Math.round((100 * pg) / numPages)) : 0;
                      ARQ.ops.step(opCtx.id, 'Procesando PDF… (página ' + pg + '/' + numPages + ')', 'page', pct);
                    }
                    return renderPage(pg).then(function (r) {
                      results.push({ page: pg, dataUrl: r.dataUrl, w: r.w, h: r.h });
                    });
                  });
                })(p);
              }
              chain.then(function () {
                if (opCtx && opCtx.id && ARQ.ops && ARQ.ops.step) {
                  ARQ.ops.step(opCtx.id, 'Aplicando capas al proyecto…', 'apply', 100);
                }
                ARQ.history.pushUndo();
                var sheet = ARQ.utils.activeSheet(ARQ.store.getProject());
                if (!sheet) {
                  resolve();
                  return;
                }
                var z = ARQ.layers.maxZIndex(sheet);
                results.forEach(function (item, idx) {
                  var layerName = baseLabel + ' — pág. ' + item.page + ' / ' + numPages;
                  if (idx === 0) {
                    var layer0 = ARQ.layers.findLayerById(sheet, targetLayerId);
                    if (layer0) {
                      layer0.nombre = layerName;
                      self.setLayerImageFromDataUrl(layer0, item.dataUrl, item.w, item.h);
                    }
                  } else {
                    z += 1;
                    var nl = ARQ.layers.appendImageLayer(sheet, layerName, z);
                    self.setLayerImageFromDataUrl(nl, item.dataUrl, item.w, item.h);
                  }
                });
                ARQ.store.setDirty(true);
                ARQ.layers.renderPanel();
                ARQ.canvasEngine.redraw();
                ARQ.history.pushDescription('Importar PDF');
                resolve();
              }).catch(function (err) {
                console.error(err);
                reject(err || new Error('No se pudo leer el PDF'));
              });
            }).catch(function (err) {
              console.error(err);
              reject(err || new Error('PDF inválido'));
            });
          };
          reader.onerror = function () {
            reject(new Error('No se pudo leer el archivo'));
          };
          reader.readAsArrayBuffer(file);
        });
      };
      if (ARQ.ops && ARQ.ops.run) {
        ARQ.ops.run(inner, { label: 'Procesando PDF…', blocking: 'critical' }).catch(function (e) {
          ARQ.bus.emit(ARQ.EVENTS.TOAST, (e && e.message) ? e.message : 'Error al importar PDF');
        });
      } else {
        inner({}).catch(function () {
          ARQ.bus.emit(ARQ.EVENTS.TOAST, 'Error al importar PDF');
        });
      }
    },

    applyDataUrlToLayer: function (layerId, dataUrl, fileLabel) {
      var sheet = ARQ.utils.activeSheet(ARQ.store.getProject());
      if (!sheet) return;
      var layer = ARQ.layers.findLayerById(sheet, layerId);
      if (!layer) return;
      if (!ARQ.guards.canDrawOnLayer(layer)) {
        ARQ.bus.emit(ARQ.EVENTS.TOAST, 'Desbloquea la capa para importar');
        return;
      }
      var im = new Image();
      im.onload = function () {
        ARQ.history.pushUndo();
        ARQ.assets.setLayerImageFromDataUrl(layer, dataUrl, im.width, im.height);
        if (fileLabel) layer.nombre = String(fileLabel).replace(/\.[^.]+$/, '') || layer.nombre;
        ARQ.store.setDirty(true);
        ARQ.layers.renderPanel();
        ARQ.canvasEngine.redraw();
        ARQ.history.pushDescription('Importar a capa');
      };
      im.onerror = function () {
        ARQ.bus.emit(ARQ.EVENTS.TOAST, 'No se pudo cargar la imagen');
      };
      im.src = dataUrl;
    },

    setLayerImageFromDataUrl: function (layer, dataUrl, naturalW, naturalH) {
      var sheet = ARQ.utils.activeSheet(ARQ.store.getProject());
      if (!sheet) return;
      var w = sheet.ancho || 1920;
      var h = sheet.alto || 1080;
      var scale = Math.min(w / naturalW, h / naturalH, 1) * 0.75;
      var tw = naturalW * scale;
      var th = naturalH * scale;
      layer.contenido = layer.contenido || {};
      layer.contenido.strokes = layer.contenido.strokes || [];
      layer.contenido.texts = layer.contenido.texts || [];
      layer.contenido.shapes = layer.contenido.shapes || [];
      layer.contenido.imageSrc = dataUrl;
      layer.contenido.imageTransform = {
        x: (w - tw) / 2,
        y: (h - th) / 2,
        w: tw,
        h: th,
        rotation: 0,
        naturalW: naturalW,
        naturalH: naturalH,
      };
      delete layer.contenido.imageTransform.corners;
      layer.tipo = 'imagen';
    },

    insertIntoActiveLayer: function (url) {
      var layer = ARQ.store.activeLayer();
      var sheet = ARQ.utils.activeSheet(ARQ.store.getProject());
      if (!layer || !sheet || !ARQ.guards.canDrawOnLayer(layer)) return;
      ARQ.history.pushUndo();
      var im = new Image();
      im.onload = function () {
        ARQ.assets.setLayerImageFromDataUrl(layer, url, im.width, im.height);
        ARQ.store.setDirty(true);
        ARQ.canvasEngine.redraw();
        ARQ.history.pushDescription('Imagen insertada');
      };
      im.src = url;
    },

    /** @deprecated usar insertIntoActiveLayer */
    insertIntoCanvas: function (url) {
      this.insertIntoActiveLayer(url);
    },

    importFile: async function (file) {
      var mb = file.size / (1024 * 1024);
      if (mb > ARQ.MAX_IMAGE_IMPORT_MB) {
        if (!(await ARQ.dialog.confirm('Archivo ~' + mb.toFixed(1) + ' MB. ¿Importar de todos modos?'))) return;
      }
      var reader = new FileReader();
      reader.onload = function () {
        var dataUrl = reader.result;
        var p = ARQ.store.getProject();
        if (!p) return;
        p.assets = p.assets || [];
        var asset = {
          id: ARQ.utils.uuid(),
          nombre: file.name,
          tipo: file.type || 'image',
          ruta: '',
          miniatura: dataUrl.slice(0, 120) + '…',
          fondo_removido: false,
          origen: 'local',
          fecha: ARQ.utils.nowIso(),
          metadata: {},
        };
        p.assets.push(asset);
        ARQ.projects.uploadFile(p.id, 'assets', file).then(function (res) {
          if (res.success && res.path) {
            asset.ruta = res.path;
            ARQ.store.setDirty(true);
            ARQ.assets.renderThumbs();
          }
        }).catch(function () {
          asset.ruta = 'data-url';
          asset.dataUrl = dataUrl;
          ARQ.store.setDirty(true);
          ARQ.assets.renderThumbs();
        });
        ARQ.assets.renderThumbs();
        ARQ.store.setDirty(true);
      };
      reader.readAsDataURL(file);
    },

    renderThumbs: function () {
      var $g = $('#asset-thumbs');
      $g.empty();
      var p = ARQ.store.getProject();
      if (!p || !p.assets) return;
      p.assets.forEach(function (a) {
        var src = a.dataUrl || (a.ruta && a.ruta !== 'data-url' ? '../' + a.ruta : '');
        if (!src) return;
        var div = $('<div class="arq-asset-thumb"/>').data('url', src);
        div.append($('<img alt=""/>').attr('src', src));
        $g.append(div);
      });
    },

    removeImageFromLayer: function (layerId) {
      var sheet = ARQ.utils.activeSheet(ARQ.store.getProject());
      if (!sheet) return;
      var layer = ARQ.layers.findLayerById(sheet, layerId);
      if (!layer || !layer.contenido || !layer.contenido.imageSrc) return;
      if (!ARQ.guards.canDrawOnLayer(layer)) {
        ARQ.bus.emit(ARQ.EVENTS.TOAST, 'Desbloquea la capa para quitar la imagen');
        return;
      }
      ARQ.history.pushUndo();
      delete layer.contenido.imageSrc;
      delete layer.contenido.imageTransform;
      layer.tipo = 'vector';
      if (ARQ.transform && ARQ.transform.layerId === layerId) ARQ.transform.deactivate();
      ARQ.store.setDirty(true);
      ARQ.layers.renderPanel();
      ARQ.canvasEngine.redraw();
      ARQ.history.pushDescription('Quitar imagen de capa');
    },

    removeBackgroundSimple: function (dataUrl, threshold, cb) {
      var im = new Image();
      im.onload = function () {
        var c = global.document.createElement('canvas');
        c.width = im.width;
        c.height = im.height;
        var x = c.getContext('2d');
        x.drawImage(im, 0, 0);
        var d = x.getImageData(0, 0, c.width, c.height);
        var p = d.data;
        var t = threshold == null ? 240 : threshold;
        for (var i = 0; i < p.length; i += 4) {
          if (p[i] > t && p[i + 1] > t && p[i + 2] > t) {
            p[i + 3] = 0;
          }
        }
        x.putImageData(d, 0, 0);
        cb(c.toDataURL('image/png'));
      };
      im.src = dataUrl;
    },
  };
})(typeof window !== 'undefined' ? window : this);
