import { defineComponent as ie, mergeModels as ue, useModel as se, useSlots as ce, ref as h, useTemplateRef as de, reactive as pe, computed as v, unref as c, watch as g, watchPostEffect as ve, createElementBlock as u, openBlock as n, withModifiers as S, createElementVNode as _, createCommentVNode as d, normalizeClass as M, createBlock as w, createVNode as z, withDirectives as fe, vModelText as me, withCtx as R, createTextVNode as he, toDisplayString as x, renderSlot as N, Fragment as ge, renderList as _e } from "vue";
/* empty css                     */
import { tap as ye } from "../../helpers/functions.js";
import ke from "../PlTooltip/PlTooltip.vue.js";
import we from "../../utils/DoubleContour.vue2.js";
/* empty css                            */
import { useLabelNotch as xe } from "../../utils/useLabelNotch.js";
import { deepEqual as I } from "../../helpers/objects.js";
import Ie from "../DropdownListItem.vue.js";
import be from "../LongText.vue.js";
/* empty css               */
import { normalizeListOptions as T } from "../../helpers/utils.js";
import Se from "../PlIcon16/PlIcon16.vue.js";
import Oe from "../PlIcon24/PlIcon24.vue.js";
import Ee from "../../utils/DropdownOverlay/DropdownOverlay.vue.js";
import { refDebounced as Ve } from "@vueuse/core";
import { useWatchFetch as H } from "../../composition/useWatchFetch.js";
import { getErrorMessage as Ae } from "../../helpers/error.js";
import $e from "../PlSvg/PlSvg.vue.js";
import Ce from "../../assets/images/required.svg.js";
const De = ["tabindex"], Me = { class: "pl-autocomplete__container" }, Re = { class: "pl-autocomplete__field" }, Be = ["disabled", "placeholder"], Fe = {
  key: 0,
  class: "input-value"
}, Le = { class: "pl-autocomplete__controls" }, Pe = {
  key: 2,
  class: "arrow-icon arrow-icon-default"
}, qe = { key: 0 }, ze = {
  key: 0,
  class: "nothing-found"
}, Ne = {
  key: 0,
  class: "pl-autocomplete__error"
}, Te = {
  key: 1,
  class: "pl-autocomplete__helper"
}, He = {
  key: 2,
  class: "pl-autocomplete__helper"
}, Ue = {
  name: "PlAutocomplete"
}, po = /* @__PURE__ */ ie({
  ...Ue,
  props: /* @__PURE__ */ ue({
    optionsSearch: {},
    label: { default: "" },
    helper: { default: void 0 },
    loadingOptionsHelper: { default: void 0 },
    error: { default: void 0 },
    placeholder: { default: "..." },
    clearable: { type: Boolean, default: !1 },
    required: { type: Boolean, default: !1 },
    disabled: { type: Boolean, default: !1 },
    arrowIcon: { default: void 0 },
    arrowIconLarge: { default: void 0 },
    optionSize: { default: "small" },
    formatValue: { type: Function, default: (a) => String(a) },
    groupPosition: { default: void 0 }
  }, {
    modelValue: { required: !0 },
    modelModifiers: {}
  }),
  emits: ["update:modelValue"],
  setup(a) {
    const r = se(a, "modelValue"), f = a, U = ce(), p = h(), O = h(), B = de("overlay"), s = h(null), t = pe({
      activeIndex: -1,
      open: !1
    }), K = () => ye(
      k.value.findIndex((e) => I(e.value, r.value)),
      (e) => e < 0 ? 0 : e
    ), W = () => t.activeIndex = K(), E = h([]), y = h(), k = v(() => T(E.value).map((e, o) => ({
      ...e,
      index: o,
      isSelected: o === j.value,
      isActive: o === t.activeIndex
    }))), b = h(!0), V = h(!1), A = v(() => f.disabled), j = v(() => E.value.findIndex((e) => I(e.value, r.value))), $ = v(() => {
      if (!b.value) {
        if (f.error)
          return Ae(f.error);
        if (V.value)
          return "Data loading error";
      }
    }), F = v(() => {
      const e = c(y), o = c(k), l = e ?? o.find((i) => I(i.value, r.value)) ?? o.find((i) => I(i.value, r.value));
      return (l == null ? void 0 : l.label) || (r.value ? f.formatValue(r.value) : "");
    }), G = v(() => !t.open && r.value ? "" : r.value ? String(F.value) : f.placeholder), J = v(() => r.value !== void 0 && r.value !== null), Q = v(() => A.value ? void 0 : "0"), L = (e) => {
      var o;
      r.value = e == null ? void 0 : e.value, y.value = e, s.value = null, t.open = !1, (o = p == null ? void 0 : p.value) == null || o.focus();
    }, X = () => {
      r.value = void 0, y.value = void 0;
    }, Y = () => {
      var e;
      return (e = O.value) == null ? void 0 : e.focus();
    }, Z = () => {
      t.open = !t.open;
    };
    g(() => t.open, (e) => {
      s.value = e ? "" : null;
    });
    const ee = () => {
      t.open = !0;
    }, oe = (e) => {
      var l, i, m;
      const o = e.relatedTarget;
      !((l = p.value) != null && l.contains(o)) && !((m = (i = B.value) == null ? void 0 : i.listRef) != null && m.contains(o)) && (s.value = null, t.open = !1);
    }, te = (e) => {
      var q;
      if (["ArrowDown", "ArrowUp", "Enter", "Escape"].includes(e.code))
        e.preventDefault();
      else
        return;
      const { open: o, activeIndex: l } = t;
      if (!o) {
        e.code === "Enter" && (t.open = !0, s.value = "");
        return;
      }
      e.code === "Escape" && (t.open = !1, s.value = null, (q = p.value) == null || q.focus());
      const i = c(k), { length: m } = i;
      if (!m)
        return;
      e.code === "Enter" && L(i.find((D) => D.index === l));
      const ae = i.findIndex((D) => D.index === l) ?? -1, ne = e.code === "ArrowDown" ? 1 : e.code === "ArrowUp" ? -1 : 0, re = Math.abs(ae + ne + m) % m;
      t.activeIndex = k.value[re].index ?? -1;
    };
    xe(p), g(() => r.value, W, { immediate: !0 }), g(
      () => t.open,
      (e) => {
        var o;
        return e ? (o = O.value) == null ? void 0 : o.focus() : "";
      }
    ), ve(() => {
      var e;
      s.value, t.activeIndex >= 0 && t.open && ((e = B.value) == null || e.scrollIntoActive());
    });
    const le = Ve(s, 300, { maxWait: 1e3 }), C = H(() => le.value, async (e) => {
      if (e !== null)
        return f.optionsSearch(e, "label");
    }), P = H(() => r.value, async (e) => {
      var o, l;
      return e != null && !I((o = y.value) == null ? void 0 : o.value, e) ? (l = await f.optionsSearch(String(e), "value")) == null ? void 0 : l[0] : y.value;
    });
    return g(() => C.value, (e) => {
      e && (E.value = e, s.value !== null && (V.value = !1));
    }), g(() => P.value, (e) => {
      e && (y.value = T([e])[0]);
    }), g(() => C.error, (e) => {
      e && (V.value = !!e);
    }), g(() => C.loading || P.loading, (e) => {
      b.value = e;
    }), (e, o) => (n(), u("div", {
      class: "pl-autocomplete__envelope",
      onClick: S(Y, ["stop"])
    }, [
      _("div", {
        ref_key: "rootRef",
        ref: p,
        tabindex: Q.value,
        class: M(["pl-autocomplete", { open: t.open, error: !!$.value, disabled: A.value }]),
        onKeydown: te,
        onFocusout: oe
      }, [
        _("div", Me, [
          _("div", Re, [
            fe(_("input", {
              ref_key: "input",
              ref: O,
              "onUpdate:modelValue": o[0] || (o[0] = (l) => s.value = l),
              type: "text",
              tabindex: "-1",
              disabled: A.value,
              placeholder: G.value,
              spellcheck: "false",
              autocomplete: "chrome-off",
              onFocus: ee
            }, null, 40, Be), [
              [me, s.value]
            ]),
            t.open ? d("", !0) : (n(), u("div", Fe, [
              z(be, null, {
                default: R(() => [
                  he(x(F.value), 1)
                ]),
                _: 1
              })
            ])),
            _("div", Le, [
              b.value ? (n(), w(c(Oe), {
                key: 0,
                name: "loading"
              })) : d("", !0),
              a.clearable && J.value ? (n(), w(c(Se), {
                key: 1,
                class: "clear",
                name: "delete-clear",
                onClick: S(X, ["stop"])
              })) : d("", !0),
              N(e.$slots, "append"),
              _("div", {
                class: "pl-autocomplete__arrow-wrapper",
                onClick: S(Z, ["stop"])
              }, [
                a.arrowIconLarge ? (n(), u("div", {
                  key: 0,
                  class: M(["arrow-icon", [`icon-24 ${a.arrowIconLarge}`]])
                }, null, 2)) : a.arrowIcon ? (n(), u("div", {
                  key: 1,
                  class: M(["arrow-icon", [`icon-16 ${a.arrowIcon}`]])
                }, null, 2)) : (n(), u("div", Pe))
              ])
            ])
          ]),
          a.label ? (n(), u("label", qe, [
            a.required ? (n(), w(c($e), {
              key: 0,
              uri: c(Ce)
            }, null, 8, ["uri"])) : d("", !0),
            _("span", null, x(a.label), 1),
            U.tooltip ? (n(), w(c(ke), {
              key: 1,
              class: "info",
              position: "top"
            }, {
              tooltip: R(() => [
                N(e.$slots, "tooltip")
              ]),
              _: 3
            })) : d("", !0)
          ])) : d("", !0),
          t.open ? (n(), w(c(Ee), {
            key: 1,
            ref: "overlay",
            root: p.value,
            class: "pl-autocomplete__options",
            tabindex: "-1",
            gap: 3
          }, {
            default: R(() => [
              (n(!0), u(ge, null, _e(k.value, (l, i) => (n(), w(Ie, {
                key: i,
                option: l,
                "is-selected": l.isSelected,
                "is-hovered": l.isActive,
                size: a.optionSize,
                onClick: S((m) => L(l), ["stop"])
              }, null, 8, ["option", "is-selected", "is-hovered", "size", "onClick"]))), 128)),
              k.value.length ? d("", !0) : (n(), u("div", ze, "Nothing found"))
            ]),
            _: 1
          }, 8, ["root"])) : d("", !0),
          z(we, {
            class: "pl-autocomplete__contour",
            "group-position": a.groupPosition
          }, null, 8, ["group-position"])
        ])
      ], 42, De),
      $.value ? (n(), u("div", Ne, x($.value), 1)) : b.value && a.loadingOptionsHelper ? (n(), u("div", Te, x(a.loadingOptionsHelper), 1)) : a.helper ? (n(), u("div", He, x(a.helper), 1)) : d("", !0)
    ]));
  }
});
export {
  po as default
};
//# sourceMappingURL=PlAutocomplete.vue.js.map
