(function (global) {
  global.ARQ = global.ARQ || {};
  ARQ.exportPng = {
    run: function () {
      var c = ARQ.canvasEngine.getCanvas();
      if (!c) return;
      var prefs = ARQ.storage.get(ARQ.STORAGE_KEYS.UI_PREFS) || {};
      var q = parseFloat(prefs.pngQuality) || 0.92;
      var inner = function () {
        return new Promise(function (resolve, reject) {
          c.toBlob(function (blob) {
            if (!blob) {
              reject(new Error('Exportación PNG fallida'));
              return;
            }
            var p = ARQ.store.getProject();
            var file = new File([blob], 'hoja_' + (p.hoja_activa_id || 'x').slice(0, 8) + '.png', { type: 'image/png' });
            if (p && p.id) {
              ARQ.projects.uploadFile(p.id, 'exports', file).then(function (res) {
                if (res.success) {
                  p.exportaciones = p.exportaciones || [];
                  p.exportaciones.push({
                    id: ARQ.utils.uuid(),
                    tipo: 'png',
                    ruta: res.path,
                    url_publica: global.location.origin + global.location.pathname.replace(/\/[^/]*$/, '/../' + res.path),
                    fecha: ARQ.utils.nowIso(),
                    hoja_relacionada: p.hoja_activa_id,
                  });
                  ARQ.store.setDirty(true);
                  ARQ.dialogShare && ARQ.dialogShare.show(res.path);
                  ARQ.bus.emit(ARQ.EVENTS.TOAST, 'PNG guardado en exports');
                } else {
                  ARQ._downloadBlob(blob, file.name);
                }
                resolve();
              }).catch(function () {
                ARQ._downloadBlob(blob, file.name);
                resolve();
              });
            } else {
              ARQ._downloadBlob(blob, file.name);
              resolve();
            }
          }, 'image/png', q);
        });
      };
      if (ARQ.ops && ARQ.ops.run) {
        ARQ.ops.run(inner, { label: 'Exportando PNG…', blocking: 'nonblocking' }).catch(function (e) {
          ARQ.bus.emit(ARQ.EVENTS.TOAST, (e && e.message) || 'Error al exportar PNG');
        });
      } else {
        inner().catch(function (e) {
          ARQ.bus.emit(ARQ.EVENTS.TOAST, (e && e.message) || 'Error');
        });
      }
    },
  };
  ARQ._downloadBlob = function (blob, name) {
    var a = global.document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = name;
    a.click();
    URL.revokeObjectURL(a.href);
  };
})(typeof window !== 'undefined' ? window : this);
