(function (global) {
  global.ARQ = global.ARQ || {};
  ARQ.exportPdf = {
    run: function () {
      var c = ARQ.canvasEngine.getCanvas();
      if (!c) return;
      var jsPDF = global.jspdf && global.jspdf.jsPDF;
      if (!jsPDF) {
        ARQ.bus.emit(ARQ.EVENTS.TOAST, 'jsPDF no cargado');
        return;
      }
      var inner = function () {
        return new Promise(function (resolve) {
          var sheet = ARQ.utils.activeSheet(ARQ.store.getProject());
          var w = (sheet && sheet.ancho) || c.width;
          var h = (sheet && sheet.alto) || c.height;
          var dataUrl = c.toDataURL('image/png');
          var orientation = w >= h ? 'l' : 'p';
          var pdf = new jsPDF({ orientation: orientation, unit: 'pt', format: [w, h] });
          pdf.addImage(dataUrl, 'PNG', 0, 0, w, h);
          var blob = pdf.output('blob');
          var p = ARQ.store.getProject();
          var file = new File([blob], 'hoja_' + (p && p.hoja_activa_id ? p.hoja_activa_id.slice(0, 8) : 'x') + '.pdf', { type: 'application/pdf' });
          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: 'pdf',
                  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, 'PDF guardado');
              } else {
                pdf.save(file.name);
              }
              resolve();
            }).catch(function () { pdf.save(file.name); resolve(); });
          } else {
            pdf.save(file.name);
            resolve();
          }
        });
      };
      if (ARQ.ops && ARQ.ops.run) {
        ARQ.ops.run(inner, { label: 'Generando PDF…', blocking: 'nonblocking' }).catch(function (e) {
          ARQ.bus.emit(ARQ.EVENTS.TOAST, (e && e.message) || 'Error al exportar PDF');
        });
      } else {
        inner();
      }
    },
  };
})(typeof window !== 'undefined' ? window : this);
