(function (global) {
  global.ARQ = global.ARQ || {};
  ARQ.exportHtml = {
    run: function () {
      var c = ARQ.canvasEngine.getCanvas();
      if (!c) return;
      var inner = function () {
        return new Promise(function (resolve) {
          var dataUrl = c.toDataURL('image/png');
          var p = ARQ.store.getProject();
          var nombre = (p && p.nombre) || 'export';
          var html = '<!DOCTYPE html><html lang="es"><head><meta charset="UTF-8"><title>' + nombre + '</title></head><body style="margin:0;background:#111;">' +
            '<img src="' + dataUrl + '" style="max-width:100%;height:auto;display:block;margin:0 auto;" alt="hoja"/></body></html>';
          var blob = new Blob([html], { type: 'text/html' });
          var file = new File([blob], 'hoja_' + (p && p.hoja_activa_id ? p.hoja_activa_id.slice(0, 8) : 'x') + '.html', { type: 'text/html' });
          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: 'html',
                  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, 'HTML guardado');
              } else {
                ARQ._downloadBlob(blob, file.name);
              }
              resolve();
            }).catch(function () { ARQ._downloadBlob(blob, file.name); resolve(); });
          } else {
            ARQ._downloadBlob(blob, file.name);
            resolve();
          }
        });
      };
      if (ARQ.ops && ARQ.ops.run) {
        ARQ.ops.run(inner, { label: 'Generando HTML…', blocking: 'nonblocking' }).catch(function (e) {
          ARQ.bus.emit(ARQ.EVENTS.TOAST, (e && e.message) || 'Error al exportar HTML');
        });
      } else {
        inner();
      }
    },
  };
})(typeof window !== 'undefined' ? window : this);
