import { r as i, h as t, H as e, a as s } from "./p-9b9ccd0c.js";

import { g as n } from "./p-d42e842b.js";

import "./p-6534555e.js";

import "lit";

import "lit/directives/when.js";

import "lit/directives/if-defined.js";

import { L as a } from "./p-311eedf3.js";

const o = ":host{display:grid;block-size:100%}.opacity-0{opacity:0}.gxi-hidden{display:none !important}.align-center{display:flex;align-items:center}.align-end{display:flex;align-items:end}.overflow-auto{overflow:auto}:host(.gx-ide-component){height:100% !important;display:flex !important;flex-direction:column !important}.gx-ide-main-wrapper{color:var(--gx-ide-component-text-color);font-weight:var(--font-style-regular);font-size:var(--font-size-body-m);font-family:var(--font-family-body);height:100%;display:flex;flex-direction:column;flex-grow:1;box-sizing:border-box}.buttons-container{display:flex;gap:var(--spacing-gap-m)}.giu-static-pill-icon-and-text,.giu-static-pill{background-color:var(--elevation-background-color, var(--color-accent-surface-elevation-1));padding-inline:var(--spacing-padding-m);color:var(--color-text-neutral-default);font-size:var(--font-size-body-s);line-height:var(--line-height-relaxed);font-weight:var(--font-style-regular);border-radius:4px;min-block-size:25px;display:inline-grid;align-items:center;pointer-events:none;inline-size:max-content}.giu-static-pill-icon-and-text{display:inline-grid;grid-auto-flow:column;grid-auto-columns:max-content;gap:var(--spacing-gap-m)}.tab-full-width-buttons::part(tab-list block-start),.tab-full-width-buttons::part(tab-list block-end){grid-auto-columns:1fr}.tab-full-width-buttons::part(tab block-start){justify-content:center}.tree-view::part(item__header){--icon__system_warning_warning--disabled:var(\n    --icon__system_warning_warning--enabled\n  )}.tabular-grid{--focus-outline-width:1px}button.button-secondary{border-color:var(--color-border-neutral-default)}:host{display:grid;inline-size:100%;block-size:100%}.file-uploader-dialog{display:grid;grid-template-rows:1fr max-content;block-size:100%;min-block-size:0;position:relative}.file-uploader-dialog .dialog-content{min-block-size:0;overflow:auto}.file-uploader{display:flex;flex-direction:column;inline-size:100%;block-size:100%}.file-uploader__list{display:flex;flex-direction:column;inline-size:100%;block-size:100%}.file-uploader__list-header{position:sticky;top:0;z-index:1;display:flex;justify-content:space-between;align-items:center}.file-uploader__list-content{flex:1;overflow-y:auto;display:flex;flex-direction:column;gap:var(--spacing-gap-l);list-style:none;margin:0;padding:0;padding-block-end:var(--spacing-padding-l)}.file-uploader__list-title-container{display:flex;align-items:center;gap:var(--spacing-gap-xs);white-space:nowrap}.file-uploader__drop-zone{display:flex;flex-direction:column;align-items:center;justify-content:center;inline-size:100%;block-size:100%;border:2px dashed var(--color-border-neutral-default);border-radius:8px;transition:border-color 0.3s ease, background-color 0.3s ease, opacity 0.3s ease}.file-uploader__drop-zone--dragging{border-color:var(--color-accent-primary-default);background:var(--color-accent-primary-hover);opacity:0.7}.file-uploader__drop-zone .text-container{display:flex;flex-direction:column;align-items:center;gap:var(--spacing-gap-xs);margin-block-start:8px}.label-primary-row{display:flex;align-items:center;gap:var(--spacing-gap-m)}";

var l = undefined && undefined.__classPrivateFieldGet || function(i, t, e, s) {
  if (e === "a" && !s) throw new TypeError("Private accessor was defined without a getter");
  if (typeof t === "function" ? i !== t || !s : !t.has(i)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return e === "m" ? s : e === "a" ? s.call(i) : s ? s.value : t.get(i);
};

var r = undefined && undefined.__classPrivateFieldSet || function(i, t, e, s, n) {
  if (s === "m") throw new TypeError("Private method is not writable");
  if (s === "a" && !n) throw new TypeError("Private accessor was defined without a setter");
  if (typeof t === "function" ? i !== t || !n : !t.has(i)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return s === "a" ? n.call(i, e) : n ? n.value = e : t.set(i, e), e;
};

var d, c, h, f, p, u, v, g, b, m, w, y, x, k, _, M, z, j;

const W = n({
  category: "system",
  name: "add",
  colorType: "primary"
});

const O = [ "resets/box-sizing", "components/button", "components/icon", "components/list-box", "components/edit", "utils/typography", "utils/spacing", "utils/form", "utils/layout", "utils/elevation", "chameleon/scrollbar" ];

const C = class {
  constructor(t) {
    i(this, t);
    d.add(this);
    c.set(this, void 0);
    h.set(this, void 0);
    f.set(this, 0);
    /** Generates a unique ID for file identification */    p.set(this, (() => Math.random().toString(36).substr(2, 9)));
    /** Handles drag enter event */    g.set(this, (i => {
      var t;
      i.preventDefault();
      i.stopPropagation();
      r(this, f, (t = l(this, f, "f"), t++, t), "f");
      this.isDragging = true;
    }));
    /** Handles drag leave event */    b.set(this, (i => {
      var t;
      i.preventDefault();
      i.stopPropagation();
      r(this, f, (t = l(this, f, "f"), t--, t), "f");
      if (l(this, f, "f") === 0) {
        this.isDragging = false;
      }
    }));
    /** Handles drag over event */    m.set(this, (i => {
      i.preventDefault();
      i.stopPropagation();
    }));
    /** Handles drop event */    w.set(this, (i => {
      var t;
      i.preventDefault();
      i.stopPropagation();
      this.isDragging = false;
      r(this, f, 0, "f");
      const e = (t = i.dataTransfer) === null || t === void 0 ? void 0 : t.files;
      if (e) {
        l(this, k, "f").call(this, e);
      }
    }));
    /** Triggers file input click */    y.set(this, (() => {
      var i;
      (i = l(this, h, "f")) === null || i === void 0 ? void 0 : i.click();
    }));
    /** Handles file input change event */    x.set(this, (i => {
      const t = i.target.files;
      if (t) {
        l(this, k, "f").call(this, t);
      }
    }));
    /** Processes files and starts upload */    k.set(this, (i => {
      const t = l(this, d, "m", v).call(this, i);
      t.forEach((async i => {
        var t, e;
        const s = l(this, p, "f").call(this);
        const n = {
          id: s,
          name: i.name,
          file: i,
          pending: true,
          progress: 0
        };
        if (!this.multiple) {
          this.fileStates.clear();
        }
        this.fileStates = new Map(this.fileStates.set(s, n));
        if (this.uploadFunction) {
          try {
            const n = this.uploadFunction(i, (i => {
              const t = this.fileStates.get(s);
              if (t) {
                const e = Object.assign(Object.assign({}, t), {
                  progress: i,
                  pending: i < 100
                });
                this.fileStates = new Map(this.fileStates.set(s, e));
              }
            }));
            // Store the upload promise/object for potential cancellation
                        const a = Object.assign(Object.assign({}, this.fileStates.get(s)), {
              uploadPromise: n
            });
            this.fileStates = new Map(this.fileStates.set(s, a));
            const o = await n;
            const l = this.fileStates.get(s);
            if (l) {
              if (o.success && o.remoteId) {
                const i = Object.assign(Object.assign({}, l), {
                  remoteId: o.remoteId,
                  pending: false,
                  progress: 100
                });
                this.fileStates = new Map(this.fileStates.set(s, i));
                await ((t = this.fileUploadedCallback) === null || t === void 0 ? void 0 : t.call(this, {
                  name: l.name,
                  originalName: l.file.name,
                  remoteId: o.remoteId
                }));
              } else {
                const i = Object.assign(Object.assign({}, l), {
                  error: ((e = o.errors) === null || e === void 0 ? void 0 : e.upload) || "Upload failed",
                  pending: false
                });
                this.fileStates = new Map(this.fileStates.set(s, i));
              }
            }
          } catch (i) {
            const t = this.fileStates.get(s);
            if (t) {
              const e = Object.assign(Object.assign({}, t), {
                error: i instanceof Error ? i.message : "Unknown error occurred",
                pending: false
              });
              this.fileStates = new Map(this.fileStates.set(s, e));
            }
          }
        }
      }));
      if (l(this, h, "f")) {
        l(this, h, "f").value = "";
      }
    }));
    /** Handles file name change */    _.set(this, (async i => {
      var t;
      const {id: e, name: s} = i.detail;
      const n = this.fileStates.get(e);
      if (n) {
        const i = Object.assign(Object.assign({}, n), {
          name: s.trim(),
          isEditing: false
        });
        this.fileStates = new Map(this.fileStates.set(e, i));
        await ((t = this.fileRenamedCallback) === null || t === void 0 ? void 0 : t.call(this, {
          fileId: e,
          newName: s.trim()
        }));
      }
    }));
    /** Handles individual file cancellation or deletion */    M.set(this, (async i => {
      var t, e, s, n;
      const a = i.detail;
      const o = this.fileStates.get(a);
      if (o) {
        try {
          if (o.pending) {
            // Cancel upload in progress
            if (o.uploadPromise && typeof o.uploadPromise.cancel === "function") {
              o.uploadPromise.cancel();
            } else if (this.cancelUploadFunction) {
              await this.cancelUploadFunction(a);
            }
            await ((t = this.uploadCancelledCallback) === null || t === void 0 ? void 0 : t.call(this, a));
            this.fileStates.delete(a);
            this.fileStates = new Map(this.fileStates);
          } else {
            const i = {
              name: o.name,
              originalName: o.file.name,
              remoteId: o.remoteId
            };
            const t = await ((e = this.onBeforeDelete) === null || e === void 0 ? void 0 : e.call(this, i));
            if (t) {
              await ((s = this.fileDeletedCallback) === null || s === void 0 ? void 0 : s.call(this, i));
              this.fileStates.delete(a);
              this.fileStates = new Map(this.fileStates);
            }
          }
        } catch (i) {
          await ((n = this.fileDeletionErrorCallback) === null || n === void 0 ? void 0 : n.call(this, {
            fileName: o.name,
            error: i instanceof Error ? i.message : "Unknown error occurred"
          }));
        }
      }
    }));
    /** Handles dialog confirmation */    z.set(this, (async () => {
      var i;
      // Verificar si hay subidas en progreso
            const t = Array.from(this.fileStates.values()).some((i => i.pending));
      if (t) {
        return;
 // No permitir confirmar si hay subidas en progreso
            }
      // Obtener todos los archivos que están completamente subidos
            const e = Array.from(this.fileStates.values()).filter((i => {
        const t = !i.pending && i.remoteId && !i.error;
        return t;
      })).map((i => ({
        name: i.name,
        originalName: i.file.name,
        remoteId: i.remoteId
      })));
      if (e.length > 0) {
        await ((i = this.dialogConfirmedCallback) === null || i === void 0 ? void 0 : i.call(this, e));
      }
      // Clear file states
            this.fileStates.clear();
      this.fileStates = new Map;
      // Reset file input
            if (l(this, h, "f")) {
        l(this, h, "f").value = "";
      }
    }));
    /** Handles dialog cancellation */    j.set(this, (async () => {
      var i, t, e;
      try {
        // Cancelamos todas las subidas en progreso
        for (const [t, e] of this.fileStates.entries()) {
          if (e.pending && this.cancelUploadFunction) {
            try {
              await this.cancelUploadFunction(t);
              await ((i = this.uploadCancelledCallback) === null || i === void 0 ? void 0 : i.call(this, t));
            } catch (i) {
              // Error handling for upload cancellation
            }
          }
        }
        // Limpiamos todos los estados
                this.fileStates.clear();
        this.fileStates = new Map;
        if (l(this, h, "f")) {
          l(this, h, "f").value = "";
        }
        await ((t = this.dialogCanceledCallback) === null || t === void 0 ? void 0 : t.call(this));
      } catch (i) {
        this.fileStates.clear();
        this.fileStates = new Map;
        await ((e = this.dialogCanceledCallback) === null || e === void 0 ? void 0 : e.call(this));
      }
    }));
    this.types = [];
    this.multiple = false;
    this.canEditName = false;
    this.label = undefined;
    this.uploadFunction = undefined;
    this.cancelUploadFunction = undefined;
    this.fileUploadedCallback = undefined;
    this.dialogCanceledCallback = undefined;
    this.dialogConfirmedCallback = undefined;
    this.uploadCancelledCallback = undefined;
    this.fileRenamedCallback = undefined;
    this.fileValidationErrorCallback = undefined;
    this.fileDeletionErrorCallback = undefined;
    this.fileDeletedCallback = undefined;
    this.onBeforeDelete = undefined;
    this.fileStates = new Map;
    this.isDragging = false;
  }
  /** Initializes component with locale strings */  async componentWillLoad() {
    r(this, c, await a.getComponentStrings(this.el), "f");
  }
  /** Clears the current file selection */  async clear() {
    var i;
    for (const [t, e] of this.fileStates.entries()) {
      if (e.pending && this.cancelUploadFunction) {
        try {
          await this.cancelUploadFunction(t);
          await ((i = this.uploadCancelledCallback) === null || i === void 0 ? void 0 : i.call(this, t));
        } catch (i) {
          // Error handling for upload cancellation
        }
      }
    }
    this.fileStates.clear();
  }
  render() {
    var i, s, n, a, o, d, f, p, u, v, k, C, E, F;
    return t(e, {
      class: "widget"
    }, t("ch-theme", {
      model: O
    }), t("input", {
      type: "file",
      hidden: true,
      multiple: this.multiple,
      accept: (i = this.types) === null || i === void 0 ? void 0 : i.map((i => i.startsWith(".") ? i : `.${i}`)).join(","),
      onChange: l(this, x, "f"),
      ref: i => r(this, h, i, "f"),
      "aria-hidden": "true",
      tabIndex: -1
    }), t("div", {
      class: "file-uploader-dialog"
    }, t("div", {
      class: "dialog-content"
    }, this.isDragging || this.fileStates.size === 0 ? t("div", {
      class: {
        "file-uploader__drop-zone elevation-1": true,
        "file-uploader__drop-zone--dragging": this.isDragging
      },
      onDragEnter: l(this, g, "f"),
      onDragLeave: l(this, b, "f"),
      onDragOver: l(this, m, "f"),
      onDrop: l(this, w, "f")
    }, t("button", {
      class: "button-tertiary button-icon-and-text",
      type: "button",
      onClick: l(this, y, "f")
    }, t("ch-image", {
      class: "icon-m",
      src: W
    }), t("label", {
      class: "label"
    }, this.multiple ? (s = l(this, c, "f")) === null || s === void 0 ? void 0 : s.header.uploadButtonMultiple : (n = l(this, c, "f")) === null || n === void 0 ? void 0 : n.header.uploadButtonSingle)), t("div", {
      class: "text-container"
    }, t("div", {
      class: "label-primary-row"
    }, t("label", {
      class: "label"
    }, this.label || ((a = l(this, c, "f")) === null || a === void 0 ? void 0 : a.header.orText)), t("label", {
      class: "label"
    }, (o = l(this, c, "f")) === null || o === void 0 ? void 0 : o.header.dragAndDrop)), t("span", {
      class: "caption"
    }, this.types && this.types.length > 0 ? (d = l(this, c, "f")) === null || d === void 0 ? void 0 : d.header.acceptedFiles.replace("{0}", this.types.join(", ")) : (f = l(this, c, "f")) === null || f === void 0 ? void 0 : f.header.allFilesAccepted))) : t("div", {
      class: "file-uploader__list"
    }, t("div", {
      class: "file-uploader__list-header elevation-1 spacing-body-block-end spacing-inline-end"
    }, t("div", {
      class: "file-uploader__list-title-container"
    }, t("label", {
      class: "label"
    }, this.label || ((p = l(this, c, "f")) === null || p === void 0 ? void 0 : p.fileList.attachedFiles)), t("span", {
      class: "caption"
    }, (u = l(this, c, "f")) === null || u === void 0 ? void 0 : u.fileList.filesCount.replace("{0}", this.fileStates.size.toString()))), this.multiple && t("button", {
      class: "button-tertiary button-icon-and-text",
      type: "button",
      onClick: l(this, y, "f")
    }, t("ch-image", {
      class: "icon-m",
      src: W
    }), t("label", {
      class: "label"
    }, this.multiple ? (v = l(this, c, "f")) === null || v === void 0 ? void 0 : v.header.uploadButtonMultiple : (k = l(this, c, "f")) === null || k === void 0 ? void 0 : k.header.uploadButtonSingle))), t("ul", {
      class: "file-uploader__list-content scrollable spacing-inline-end spacing-block-end",
      "aria-live": "polite",
      "aria-label": (C = l(this, c, "f")) === null || C === void 0 ? void 0 : C.fileList.selectedFilesAriaLabel
    }, Array.from(this.fileStates.values()).map((i => t("gx-ide-file-item", {
      key: i.id,
      file: i,
      editable: this.canEditName,
      componentLocale: l(this, c, "f"),
      onFileNameChange: l(this, _, "f"),
      onFileDelete: l(this, M, "f"),
      onFileCancel: l(this, M, "f")
    })))))), t("div", {
      class: {
        "dialog-footer": true,
        "dialog-footer-with-border": this.fileStates.size > 0
      }
    }, t("div", {
      class: "buttons-spacer"
    }, t("button", {
      class: "button-secondary",
      type: "button",
      onClick: l(this, j, "f")
    }, (E = l(this, c, "f")) === null || E === void 0 ? void 0 : E.buttons.cancel), t("button", {
      class: "button-primary",
      type: "button",
      onClick: l(this, z, "f"),
      disabled: this.fileStates.size === 0 || Array.from(this.fileStates.values()).some((i => i.pending))
    }, (F = l(this, c, "f")) === null || F === void 0 ? void 0 : F.buttons.confirm)))));
  }
  static get assetsDirs() {
    return [ "gx-ide-assets/file-uploader" ];
  }
  get el() {
    return s(this);
  }
};

c = new WeakMap, h = new WeakMap, f = new WeakMap, p = new WeakMap, g = new WeakMap, 
b = new WeakMap, m = new WeakMap, w = new WeakMap, y = new WeakMap, x = new WeakMap, 
k = new WeakMap, _ = new WeakMap, M = new WeakMap, z = new WeakMap, j = new WeakMap, 
d = new WeakSet, u = function _FileUploader_isValidFile(i) {
  var t, e;
  // If no types specified, accept any file
    if (!this.types || this.types.length === 0) {
    return {
      isValid: true
    };
  }
  for (const t of this.types) {
    // Handle wildcards like 'image/*'
    if (t.includes("/*")) {
      const e = t.split("/")[0];
      if (i.type.startsWith(e)) {
        return {
          isValid: true
        };
      }
    }
    // Handle extensions like '.jpg'
     else if (t.startsWith(".")) {
      if (i.name.toLowerCase().endsWith(t.toLowerCase())) {
        return {
          isValid: true
        };
      }
    }
    // Handle specific MIME types
     else if (i.type === t || i.type === `application/${t}`) {
      return {
        isValid: true
      };
    }
  }
  return {
    isValid: false,
    error: ((e = (t = l(this, c, "f")) === null || t === void 0 ? void 0 : t.errors) === null || e === void 0 ? void 0 : e.invalidFileType) || "Invalid file type"
  };
}, v = function _FileUploader_getValidFiles(i) {
  const t = [];
  Array.from(i).forEach((i => {
    var e;
    const s = l(this, d, "m", u).call(this, i);
    if (s.isValid) {
      t.push(i);
    } else {
      (e = this.fileValidationErrorCallback) === null || e === void 0 ? void 0 : e.call(this, {
        fileName: i.name,
        error: s.error
      });
    }
  }));
  return t;
};

C.style = o;

export { C as gx_ide_file_uploader };
//# sourceMappingURL=p-e2b88bea.entry.js.map