import { defineComponent as Fe, mergeModels as ce, computed as w, ref as b, useModel as Pe, watch as D, nextTick as Z, unref as n, onUnmounted as Ee, openBlock as s, createBlock as x, mergeProps as U, toHandlers as ve, withCtx as m, createElementVNode as F, createElementBlock as f, normalizeClass as k, Fragment as O, createTextVNode as S, toDisplayString as g, createVNode as B, renderSlot as $, createCommentVNode as L, renderList as j, createSlots as He, normalizeStyle as We, withModifiers as qe, withDirectives as Ue, vModelSelect as je } from "vue";
import { useEventListener as Xe, useResizeObserver as Ke } from "../../node_modules/.pnpm/@vueuse_core@11.1.0_vue@3.5.10_typescript@5.2.2_/node_modules/@vueuse/core/index.js";
import { useColors as Ge } from "../../composables/useColors.js";
import { useCommon as he } from "../../composables/useCommon.js";
import { useInputtable as _ } from "../../composables/useInputtable.js";
import { useInteractive as ke } from "../../composables/useInteractive.js";
import { useTheme as Je } from "../../composables/useTheme.js";
import { useVirtualList as Qe } from "../../composables/useVirtualList.js";
import { checkIcon as Ye, closeIcon as Ze, selectIcon as _e } from "../../common/icons.js";
import el from "../label/Label.vue.js";
import pe from "../tag/Tag.vue.js";
import me from "../icon/Icon.vue.js";
import ll from "../menu/MenuItem.vue.js";
import tl from "../spinner/Spinner.vue.js";
import ye from "../popover/Popover.vue.js";
import "../popover/Popover.vue2.js";
import be from "../popover/PopoverContainer.vue.js";
import al from "../inputFooter/InputFooter.vue.js";
import il from "../input/Input.vue.js";
import { useThrottleFn as ol } from "../../node_modules/.pnpm/@vueuse_shared@11.1.0_vue@3.5.10_typescript@5.2.2_/node_modules/@vueuse/shared/index.js";
const sl = { class: "relative" }, rl = {
  key: 0,
  class: "text-secondary-400 dark:text-secondary-500"
}, nl = { key: 1 }, ul = {
  key: 0,
  class: "text-secondary-400 dark:text-secondary-500"
}, dl = { key: 1 }, fl = {
  key: 0,
  class: "p-2 text-center text-secondary-400"
}, cl = ["id", "name", "disabled", "multiple", "readonly"], vl = ["value", "disabled"], pl = {
  ...Ge.props("secondary"),
  ...he.props(),
  ...ke.props(),
  ..._.props(),
  placeholder: String,
  options: Array,
  multiple: Boolean,
  multipleCheckbox: Boolean,
  truncate: Boolean,
  flat: Boolean,
  native: Boolean,
  filterable: Boolean,
  clearable: Boolean,
  filterPlaceholder: {
    type: String,
    default: "Filter by..."
  },
  virtualList: Boolean,
  virtualListOffsetTop: Number,
  virtualListOffsetBottom: Number,
  virtualListItemHeight: {
    type: Number,
    default: 33
  },
  virtualListOverscan: {
    type: Number,
    default: 5
  },
  placement: String
}, ml = {
  name: "XSelect",
  validators: {
    ...he.validators()
  }
}, Ml = /* @__PURE__ */ Fe({
  ...ml,
  props: /* @__PURE__ */ ce(pl, {
    filter: { default: "" },
    filterModifiers: {}
  }),
  emits: /* @__PURE__ */ ce([..._.emits(), "close"], ["update:filter"]),
  setup(ee, { expose: ge, emit: Ce }) {
    const i = ee, z = Ce, p = w(() => i.multiple || i.multipleCheckbox), X = b(null), K = b(null), P = b(null), C = b(null), G = b(null), c = b(), I = Pe(ee, "filter"), E = b(null), A = w(() => i.disabled || i.loading || i.readonly), we = w(() => !i.loading && !i.readonly && !i.disabled && i.clearable && !J(o.value)), o = w({
      get() {
        return p.value ? i.modelValue ? Array.isArray(i.modelValue) ? i.modelValue : [i.modelValue] : [] : i.modelValue;
      },
      set(e) {
        z("update:modelValue", e);
      }
    }), Oe = w(() => i.options ? new Map(i.options.map((e) => [e, e.label.toLowerCase()])) : /* @__PURE__ */ new Map()), h = w(() => {
      if (!i.options || i.options.length === 0)
        return [];
      const e = I.value.toLowerCase(), t = I.value !== "", l = new Set(
        p.value && Array.isArray(o.value) ? o.value : []
      ), a = p.value ? null : o.value, r = Oe.value;
      return i.options.filter((u) => {
        var d;
        return !t || ((d = r.get(u)) == null ? void 0 : d.includes(e));
      }).map((u) => {
        const d = p.value ? l.has(u.value) : u.value === a;
        return {
          value: u.value,
          label: u.label,
          active: d,
          prefix: u.prefix,
          suffix: u.suffix,
          disabled: u.disabled,
          iconRight: !i.multipleCheckbox && d ? Ye : void 0,
          keepOpenOnClick: u.keepOpenOnClick,
          onClick: () => ie(u.value)
        };
      });
    }), le = w(() => h.value.filter((e) => !e.disabled)), { list: te, scrollTo: $e, containerProps: Ae, wrapperProps: Le } = Qe(
      h,
      {
        disabled: !i.virtualList,
        itemHeight: i.virtualListItemHeight,
        topOffset: i.virtualListOffsetTop || 0,
        bottomOffset: i.virtualListOffsetBottom || 0,
        overscan: i.virtualListOverscan
      }
    ), V = w(() => {
      var e;
      return (e = C.value) == null ? void 0 : e.isOpen;
    });
    D(I, (e) => {
      e && (c.value = void 0, H(-1));
    }), D(V, (e) => {
      e ? (Re(), (p.value || typeof c.value > "u") && H(-1), setTimeout(() => {
        requestAnimationFrame(() => {
          var t;
          ae(c.value || 0), i.filterable && ((t = E.value) == null || t.focus());
        });
      }, 50)) : (i.filterable && (I.value = ""), z("close"));
    });
    function Re() {
      if (p.value) {
        if (Array.isArray(o.value) && o.value.length > 0) {
          const e = h.value.findIndex((t) => t.value === o.value[0]);
          e !== -1 && (c.value = e);
        }
      } else {
        const e = h.value.findIndex((t) => t.value === o.value);
        e !== -1 && (c.value = e);
      }
    }
    function ae(e) {
      var t;
      i.virtualList ? $e(e) : P.value && ((t = P.value[e]) == null || t.$el.scrollIntoView({ block: "nearest", inline: "nearest" }));
    }
    D(c, (e) => {
      typeof e < "u" && P.value && ae(e);
    });
    function H(e, t = "down") {
      if (!le.value || le.value.length === 0) {
        c.value = void 0;
        return;
      }
      typeof e > "u" && (e = t === "down" ? -1 : 1);
      const l = h.value.length;
      let a = 0;
      if (t === "down") {
        let r = e + 1;
        for (r > l - 1 && (r = 0); h.value[r].disabled; )
          if (++r > l - 1 && (r = 0), ++a >= l) {
            c.value = void 0;
            return;
          }
        c.value = r;
      } else {
        let r = e - 1;
        for (r < 0 && (r = l - 1); h.value[r].disabled; )
          if (--r < 0 && (r = l - 1), ++a >= l) {
            c.value = void 0;
            return;
          }
        c.value = r;
      }
    }
    function ie(e) {
      var l;
      const t = (l = i.options) == null ? void 0 : l.find((a) => a.value === e);
      if (!(!t || t.disabled))
        if (t.onClick)
          t.onClick();
        else {
          if (p.value) {
            if (Array.isArray(o.value)) {
              const a = o.value.indexOf(e);
              a !== -1 ? o.value.splice(a, 1) : o.value.push(e);
            } else
              o.value = [e];
            z("update:modelValue", o.value), i.filterable && setTimeout(() => {
              var a;
              (a = E.value) == null || a.focus();
            });
          } else
            o.value = e;
          i.native || Z(() => {
            var a;
            ue(), (a = K.value) == null || a.$el.focus();
          });
        }
    }
    function J(e) {
      return !!(typeof e > "u" || e === null || e === "" || Array.isArray(e) && e.length === 0 || !Array.isArray(e) && typeof e == "object" && Object.keys(e).length === 0);
    }
    function oe(e, t) {
      if (e.stopPropagation(), A.value || !Array.isArray(o.value))
        return;
      const l = o.value.indexOf(t);
      l !== -1 && (o.value.splice(l, 1), z("update:modelValue", o.value));
    }
    function T(e) {
      var l;
      const t = (l = i.options) == null ? void 0 : l.find((a) => a.value === e);
      return t ? t.label : "";
    }
    const { focus: se, blur: xe } = ke(X), {
      errorInternal: re,
      hideFooterInternal: Ie,
      inputListeners: ne,
      reset: Q,
      validate: ue,
      setError: Ve,
      isFocused: Te,
      isInsideForm: Se
    } = _(i, { focus: se, emit: z, withListeners: !0 }), Be = w(() => {
      const { focus: e, blur: t } = n(ne);
      return {
        focus: e,
        blur: t
      };
    });
    let R = null;
    D([Te, V], ([e, t]) => {
      e || t ? R || (R = Xe(document, "keydown", ze)) : R && (R(), R = null);
    }, {
      immediate: !0
    }), Ee(() => {
      R && R();
    });
    function ze(e) {
      var t, l, a, r, u;
      if (h.value.length !== 0)
        if (e.code === "ArrowDown") {
          if (e.preventDefault(), !V.value) {
            (t = C.value) == null || t.show();
            return;
          }
          H(c.value, "down");
        } else if (e.code === "ArrowUp") {
          if (e.preventDefault(), !V.value) {
            (l = C.value) == null || l.show();
            return;
          }
          H(c.value, "up");
        } else if (e.code === "Enter" || e.code === "Space") {
          if (e.code === "Space" && i.filterable)
            return;
          if (e.preventDefault(), e.stopPropagation(), !V.value) {
            (a = C.value) == null || a.show();
            return;
          }
          if (typeof c.value < "u" && h.value[c.value]) {
            const d = h.value[c.value];
            ie(d.value), !d.keepOpenOnClick && (!p.value || i.multipleCheckbox) && ((r = C.value) == null || r.hide());
          }
        } else
          e.code === "Tab" && V.value && (e.preventDefault(), (u = C.value) == null || u.hide(), i.native || Z(() => {
            var d;
            (d = K.value) == null || d.$el.focus();
          }));
    }
    const N = b(null), de = b(null), W = b(!1), q = b(0), fe = ol(() => {
      p.value && i.truncate && Z(() => {
        const e = Ne();
        e < o.value.length ? (W.value = !0, q.value = o.value.length - e) : (W.value = !1, q.value = 0);
      });
    }, 100, !0);
    Ke(N, () => {
      fe();
    });
    function Ne() {
      if (!N.value)
        return 0;
      const e = N.value.querySelectorAll(".x-tag"), t = Array.from(e);
      let l = 0, a = 1;
      const r = N.value.offsetWidth - 30;
      for (let u = 0; u < t.length; u++) {
        const d = t[u];
        d.style.display = "flex", l += d.offsetWidth, u > 0 && (l < r ? a++ : d.style.display = "none");
      }
      return a;
    }
    D(o, (e) => {
      fe();
    }, { immediate: !0, deep: !0 });
    const { styles: Me, classes: y, className: De } = Je("Select", {}, i, { errorInternal: re });
    return ge({ focus: se, blur: xe, reset: Q, validate: ue, setError: Ve, filterRef: E }), (e, t) => (s(), x(el, U({
      ref_key: "labelRef",
      ref: K,
      tabindex: "0",
      class: ["group", [
        n(De),
        n(y).wrapper
      ]],
      style: n(Me),
      disabled: A.value,
      required: e.required,
      "is-inside-form": n(Se),
      label: e.label,
      tooltip: e.tooltip
    }, ve(Be.value)), {
      default: m(() => [
        F("div", sl, [
          e.native && !p.value ? (s(), f("div", {
            key: 0,
            class: k(n(y).box),
            onClick: t[0] || (t[0] = (l) => {
              var a;
              return (a = X.value) == null ? void 0 : a.click();
            })
          }, [
            J(o.value) ? (s(), f(O, { key: 1 }, [
              e.placeholder ? (s(), f("div", rl, g(e.placeholder), 1)) : (s(), f("div", nl, " "))
            ], 64)) : (s(), f(O, { key: 0 }, [
              S(g(T(o.value)), 1)
            ], 64))
          ], 2)) : (s(), f(O, { key: 1 }, [
            B(ye, {
              ref_key: "popoverRef",
              ref: C,
              disabled: A.value,
              placement: e.placement
            }, {
              content: m(() => [
                B(be, {
                  class: k(n(y).content)
                }, {
                  default: m(() => [
                    $(e.$slots, "content-header", {}, () => [
                      e.filterable ? (s(), f("div", {
                        key: 0,
                        class: k(n(y).search)
                      }, [
                        B(il, {
                          ref_key: "filterRef",
                          ref: E,
                          modelValue: I.value,
                          "onUpdate:modelValue": t[2] || (t[2] = (l) => I.value = l),
                          placeholder: e.filterPlaceholder,
                          "skip-form-registry": "",
                          "data-1p-ignore": "",
                          size: "sm"
                        }, null, 8, ["modelValue", "placeholder"])
                      ], 2)) : L("", !0)
                    ]),
                    F("div", U(n(Ae), {
                      class: n(y).contentBody
                    }), [
                      F("div", U(n(Le), { class: "space-y-0.5" }), [
                        (s(!0), f(O, null, j(n(te), (l) => (s(), x(ll, {
                          key: l.index,
                          ref_for: !0,
                          ref_key: "itemsRef",
                          ref: P,
                          item: l.data,
                          size: e.size,
                          disabled: l.data.disabled,
                          selected: l.index === c.value,
                          checkbox: e.multipleCheckbox && !l.data.keepOpenOnClick,
                          color: e.color,
                          filled: "",
                          onClick: () => {
                            var a;
                            return !l.data.keepOpenOnClick && (!p.value || e.multipleCheckbox) && ((a = C.value) == null ? void 0 : a.hide());
                          }
                        }, He({
                          default: m(() => [
                            $(e.$slots, "label", {
                              item: l.data
                            })
                          ]),
                          _: 2
                        }, [
                          e.$slots.prefix || l.data.prefix ? {
                            name: "prefix",
                            fn: m(() => [
                              $(e.$slots, "prefix", {
                                item: l.data
                              }, () => [
                                S(g(l.data.prefix), 1)
                              ])
                            ]),
                            key: "0"
                          } : void 0,
                          e.$slots.suffix || l.data.suffix ? {
                            name: "suffix",
                            fn: m(() => [
                              $(e.$slots, "suffix", {
                                item: l.data
                              }, () => [
                                S(g(l.data.suffix), 1)
                              ])
                            ]),
                            key: "1"
                          } : void 0
                        ]), 1032, ["item", "size", "disabled", "selected", "checkbox", "color", "onClick"]))), 128))
                      ], 16),
                      n(te).length === 0 ? (s(), f("div", fl, " No options ")) : L("", !0)
                    ], 16),
                    $(e.$slots, "content-footer")
                  ]),
                  _: 3
                }, 8, ["class"])
              ]),
              default: m(() => [
                $(e.$slots, "input", {
                  popover: C.value,
                  selected: o.value,
                  disabled: A.value,
                  label: T(o.value)
                }, () => [
                  F("div", {
                    class: k([n(y).box])
                  }, [
                    p.value && Array.isArray(o.value) && o.value.length > 0 ? (s(), f("div", {
                      key: 0,
                      ref_key: "tagsRef",
                      ref: N,
                      class: k(["flex gap-1 relative", {
                        "flex-wrap": !e.truncate,
                        "overflow-hidden": e.truncate
                      }])
                    }, [
                      (s(!0), f(O, null, j(o.value, (l, a) => {
                        var r, u, d, M;
                        return s(), x(pe, {
                          key: l,
                          size: "xs",
                          removable: "",
                          outlined: !(A.value || (u = (r = e.options) == null ? void 0 : r.find((v) => v.value === l)) != null && u.disabled),
                          disabled: A.value || ((M = (d = e.options) == null ? void 0 : d.find((v) => v.value === l)) == null ? void 0 : M.disabled),
                          style: We({ "max-width": a === 0 && G.value ? `calc(100% - ${G.value.offsetWidth + 6 + "px"})` : void 0 }),
                          onRemove: (v) => {
                            oe(v, l);
                          }
                        }, {
                          prefix: m(() => {
                            var v;
                            return [
                              $(e.$slots, "tag-prefix", {
                                item: (v = e.options) == null ? void 0 : v.find((Y) => Y.value === l)
                              })
                            ];
                          }),
                          default: m(() => [
                            S(" " + g(T(l)), 1)
                          ]),
                          _: 2
                        }, 1032, ["outlined", "disabled", "style", "onRemove"]);
                      }), 128)),
                      W.value ? (s(), f("div", {
                        key: 0,
                        ref_key: "hiddenTagsCounterRef",
                        ref: G,
                        class: k(n(y).truncateCounter),
                        onClick: t[1] || (t[1] = qe((l) => {
                          var a;
                          return (a = de.value) == null ? void 0 : a.toggle();
                        }, ["stop"]))
                      }, "+" + g(q.value), 3)) : L("", !0)
                    ], 2)) : !p.value && !J(o.value) && T(o.value) !== "" ? (s(), f(O, { key: 1 }, [
                      S(g(T(o.value)), 1)
                    ], 64)) : (s(), f(O, { key: 2 }, [
                      e.placeholder ? (s(), f("div", ul, g(e.placeholder), 1)) : (s(), f("div", dl, " "))
                    ], 64))
                  ], 2)
                ])
              ]),
              _: 3
            }, 8, ["disabled", "placement"]),
            p.value && e.truncate && W.value ? (s(), x(ye, {
              key: 0,
              ref_key: "multipleHiddenRef",
              ref: de,
              "popper-show-triggers": [],
              "popper-hide-triggers": [],
              class: "inline-block !absolute right-0",
              placement: "auto-start"
            }, {
              content: m(() => [
                B(be, { class: "p-2 flex gap-2 flex-wrap" }, {
                  default: m(() => {
                    var l;
                    return [
                      (s(!0), f(O, null, j((l = o.value) == null ? void 0 : l.slice(o.value.length - q.value), (a) => {
                        var r, u, d, M;
                        return s(), x(pe, {
                          key: a,
                          size: "xs",
                          removable: "",
                          outlined: !(A.value || (u = (r = e.options) == null ? void 0 : r.find((v) => v.value === a)) != null && u.disabled),
                          disabled: A.value || ((M = (d = e.options) == null ? void 0 : d.find((v) => v.value === a)) == null ? void 0 : M.disabled),
                          onRemove: (v) => {
                            oe(v, a);
                          }
                        }, {
                          prefix: m(() => {
                            var v;
                            return [
                              $(e.$slots, "tag-prefix", {
                                item: (v = e.options) == null ? void 0 : v.find((Y) => Y.value === a)
                              })
                            ];
                          }),
                          default: m(() => [
                            S(" " + g(T(a)), 1)
                          ]),
                          _: 2
                        }, 1032, ["outlined", "disabled", "onRemove"]);
                      }), 128))
                    ];
                  }),
                  _: 3
                })
              ]),
              _: 3
            }, 512)) : L("", !0)
          ], 64)),
          Ue(F("select", U({
            id: e.id,
            ref_key: "elRef",
            ref: X,
            "onUpdate:modelValue": t[3] || (t[3] = (l) => o.value = l),
            tabindex: "-1",
            class: e.native && !p.value ? "absolute inset-0 w-full h-full cursor-pointer opacity-0" : "hidden",
            name: e.name,
            disabled: e.disabled || e.loading,
            multiple: p.value,
            readonly: e.readonly
          }, ve(n(ne), !0)), [
            e.native ? (s(!0), f(O, { key: 0 }, j(e.options, (l, a) => (s(), f("option", {
              key: a,
              value: l.value,
              disabled: l.disabled
            }, g(l.label), 9, vl))), 128)) : L("", !0)
          ], 16, cl), [
            [je, o.value]
          ]),
          we.value ? (s(), f("button", {
            key: 2,
            type: "button",
            "aria-label": "Clean value",
            class: k(n(y).clearButton),
            onClick: t[4] || (t[4] = //@ts-ignore
            (...l) => n(Q) && n(Q)(...l))
          }, [
            B(me, {
              icon: n(Ze),
              class: k([n(y).icon, "cursor-pointer"])
            }, null, 8, ["icon", "class"])
          ], 2)) : L("", !0),
          e.$slots.input ? L("", !0) : (s(), f("div", {
            key: 3,
            class: k(n(y).iconWrapper)
          }, [
            e.loading ? (s(), x(tl, {
              key: 0,
              size: e.size
            }, null, 8, ["size"])) : $(e.$slots, "icon", { key: 1 }, () => [
              B(me, {
                icon: n(_e),
                class: k(n(y).icon)
              }, null, 8, ["icon", "class"])
            ])
          ], 2))
        ]),
        n(Ie) ? L("", !0) : (s(), x(al, {
          key: 0,
          error: n(re),
          helper: e.helper
        }, null, 8, ["error", "helper"]))
      ]),
      _: 3
    }, 16, ["style", "disabled", "required", "is-inside-form", "label", "class", "tooltip"]));
  }
});
export {
  Ml as default
};
