import { defineComponent as te, ref as y, computed as oe, watch as ne, openBlock as d, createElementBlock as f, normalizeClass as b, unref as s, createVNode as x, normalizeStyle as se, withCtx as ie, createElementVNode as l, mergeProps as ae, toHandlers as le, renderSlot as k, toDisplayString as _, createBlock as g, createCommentVNode as w, Fragment as de, renderList as ce } from "vue";
import { useDropZone as ue } from "../../node_modules/.pnpm/@vueuse_core@11.1.0_vue@3.5.10_typescript@5.2.2_/node_modules/@vueuse/core/index.js";
import { useCommon as pe } from "../../composables/useCommon.js";
import { useInteractive as U } from "../../composables/useInteractive.js";
import { useInputtable as I } from "../../composables/useInputtable.js";
import { useTheme as me } from "../../composables/useTheme.js";
import { uploadIcon as fe, fileIcon as ge, closeIcon as he } from "../../common/icons.js";
import ve from "../label/Label.vue.js";
import O from "../inputFooter/InputFooter.vue.js";
import ye from "../progress/Progress.vue.js";
import S from "../icon/Icon.vue.js";
const be = ["id", "disabled", "name", "accept", "multiple", "readonly"], xe = { class: "text-secondary-500 dark:text-secondary-400" }, ke = { class: "flex items-center" }, _e = ["src"], we = { class: "truncate flex-1 pr-2" }, Se = { class: "font-medium truncate" }, Ie = { class: "text-xs text-secondary-500" }, $e = ["onClick"], Ve = {
  ...pe.validators(),
  variant: ["box"]
}, Ce = {
  ...U.props(),
  ...I.props(),
  placeholder: String,
  accept: String,
  multiple: Boolean,
  maxFiles: [Number, String],
  maxFileSize: [Number, String],
  variant: {
    type: String,
    default: "box"
  },
  // URL to submit data to.
  action: String,
  // Additional HTTP headers
  headers: Object,
  method: {
    type: String,
    default: "POST"
  },
  withCredentials: Boolean
}, Ee = {
  name: "XUpload",
  validators: Ve
}, Fe = /* @__PURE__ */ te({
  ...Ee,
  props: Ce,
  emits: [...I.emits(), "upload", "remove"],
  setup(j, { expose: D, emit: q }) {
    const o = j, u = q, $ = y(null), p = oe(() => !!o.action), i = y([]);
    ne(i, (e) => {
      u("update:modelValue", e);
    }, { deep: !0, immediate: !0 });
    const { focus: V, blur: P } = U($);
    function h(e) {
      if (!e)
        return !1;
      if (!o.multiple && e.length > 1 || o.maxFiles && e.length > Number(o.maxFiles))
        return m.value = "Too many files", !1;
      if (o.maxFileSize) {
        for (let t = 0; t < e.length; t++)
          if (e[t].size > Number(o.maxFileSize))
            return m.value = "File size is too large", !1;
      }
      if (o.accept) {
        const t = o.accept.split(",").map((r) => r.trim());
        for (let r = 0; r < e.length; r++) {
          const n = e[r];
          if (!t.some((c) => n.type === c || n.name.endsWith(c)))
            return m.value = "Invalid file type", !1;
        }
      }
      return !0;
    }
    function T(e) {
      const r = e.target.files;
      h(r) && u("change", e);
    }
    function F(e) {
      const r = e.target.files;
      h(r) && (N(r), o.validateOnInput && !K.value && v(i.value), u("input", e));
    }
    const C = y(null);
    function M(e) {
      h(e) && N(e);
    }
    const { isOverDropZone: E } = ue(C, {
      onDrop: M,
      multiple: o.multiple,
      preventDefaultForUnhandled: !1
    });
    function N(e) {
      i.value = e ? Array.from(e).map((t) => ({
        file: t,
        completed: !p.value,
        progress: p.value ? 0 : 100,
        error: ""
      })) : [], p.value && W();
    }
    function Z(e) {
      const t = i.value.findIndex((r) => r.file === e);
      t !== -1 && (u("remove", i.value[t]), i.value.splice(t, 1));
    }
    function B(e) {
      const t = ["jpg", "jpeg", "png", "gif", "webp", "svg"];
      return e.type.startsWith("image") || t.some((r) => e.name.endsWith(r));
    }
    function z(e) {
      return URL.createObjectURL(e);
    }
    function A(e) {
      return e < 1024 ? `${e} B` : e < 1024 * 1024 ? `${(e / 1024).toFixed(2)} KB` : e < 1024 * 1024 * 1024 ? `${(e / 1024 / 1024).toFixed(2)} MB` : `${(e / 1024 / 1024 / 1024).toFixed(2)} GB`;
    }
    async function H(e) {
      return new Promise((t, r) => {
        if (!o.action)
          r(new Error("No action provided"));
        else {
          const n = new XMLHttpRequest(), c = new FormData();
          c.append("file", e.file), n.open(o.method, o.action, !0), o.headers && typeof o.headers == "object" && Object.keys(o.headers).forEach((a) => {
            n.setRequestHeader(a, o.headers[a]);
          }), n.upload.addEventListener("progress", (a) => {
            if (a.lengthComputable) {
              const L = a.loaded / a.total * 100;
              e.progress = L, console.log(`Upload progress: ${L}%`);
            }
          }), n.addEventListener("load", () => {
            if (n.status === 200) {
              e.completed = !0;
              try {
                e.response = JSON.parse(n.responseText);
              } catch {
                e.response = n.responseText;
              }
              t(n.responseText);
            } else {
              const a = `Upload failed. Status: ${n.status}`;
              e.error = a, r(new Error(a));
            }
          }), n.addEventListener("error", () => {
            e.error = "An error occurred during the upload.", r(new Error("An error occurred during the upload."));
          }), n.send(c);
        }
      });
    }
    async function W() {
      if (!o.action && !i.value)
        return;
      const e = [];
      for (let t = 0; t < i.value.length; t++)
        e.push(H(i.value[t]));
      await Promise.all(e), v(i.value);
    }
    const {
      errorInternal: m,
      hideFooterInternal: X,
      isInsideForm: G,
      inputListeners: J,
      isFirstValidation: K,
      reset: Q,
      validate: v,
      setError: Y
    } = I(o, { focus: V, emit: u }), { styles: ee, classes: R, className: re } = me("Upload", {}, o);
    return D({ focus: V, blur: P, reset: Q, validate: v, setError: Y }), (e, t) => (d(), f("div", {
      class: b([
        s(re),
        s(R).wrapper
      ])
    }, [
      x(ve, {
        style: se(s(ee)),
        disabled: e.disabled,
        required: e.required,
        "is-inside-form": s(G),
        label: e.label,
        tooltip: e.tooltip
      }, {
        default: ie(() => [
          l("input", ae({
            id: e.id,
            ref_key: "elRef",
            ref: $,
            type: "file",
            class: [
              "sr-only",
              s(R).input
            ],
            disabled: e.disabled,
            name: e.name,
            accept: e.accept,
            multiple: e.multiple,
            readonly: e.readonly
          }, le({
            ...s(J),
            input: F,
            change: T
          }, !0)), null, 16, be),
          k(e.$slots, "box", { isOver: s(E) }, () => [
            l("div", {
              ref_key: "dropZoneRef",
              ref: C,
              class: b(["border border-dashed rounded-md flex items-center justify-center gap-2 p-4 cursor-pointer transition-colors duration-500 hover:border-primary-500 dark:hover:border-primary-400", {
                "border-primary-500 dark:border-primary-400": s(E)
              }])
            }, [
              x(S, { icon: s(fe) }, null, 8, ["icon"]),
              l("span", xe, _(e.placeholder), 1),
              t[0] || (t[0] = l("span", { class: "text-xs text-secondary-400 dark:text-secondary-500" }, "or drag and drop", -1))
            ], 2)
          ]),
          s(X) ? w("", !0) : (d(), g(O, {
            key: 0,
            error: s(m),
            helper: e.helper
          }, null, 8, ["error", "helper"]))
        ]),
        _: 3
      }, 8, ["style", "disabled", "required", "is-inside-form", "label", "tooltip"]),
      k(e.$slots, "files", { files: i.value }, () => [
        (d(!0), f(de, null, ce(i.value, (r, n) => (d(), f("div", {
          key: n,
          class: "border rounded-md p-2 bg-secondary-100 my-2"
        }, [
          l("div", ke, [
            l("div", {
              class: b(["rounded-md w-9 h-9 flex items-center justify-center mr-2 border", {
                "p-2 bg-white": !B(r.file)
              }])
            }, [
              B(r.file) ? (d(), f("img", {
                key: 0,
                src: z(r.file),
                class: "w-full h-full object-cover rounded-md"
              }, null, 8, _e)) : (d(), g(S, {
                key: 1,
                icon: s(ge)
              }, null, 8, ["icon"]))
            ], 2),
            l("div", we, [
              l("div", Se, _(r.file.name), 1),
              l("div", Ie, _(A(r.file.size)), 1)
            ]),
            l("button", {
              type: "button",
              class: "shrink-0",
              onClick: (c) => Z(r.file)
            }, [
              k(e.$slots, "removeIcon", {}, () => [
                x(S, { icon: s(he) }, null, 8, ["icon"])
              ])
            ], 8, $e)
          ]),
          p.value ? (d(), g(ye, {
            key: 0,
            percentage: r.progress,
            class: "mt-1",
            color: r.error ? "warning" : "success"
          }, null, 8, ["percentage", "color"])) : w("", !0),
          r.error ? (d(), g(O, {
            key: 1,
            error: r.error
          }, null, 8, ["error"])) : w("", !0)
        ]))), 128))
      ])
    ], 2));
  }
});
export {
  Fe as default
};
