import { jsxs as H, jsx as g, Fragment as de } from "react/jsx-runtime";
import { useRef as D, useCallback as pe, useEffect as me, useState as U, forwardRef as be, cloneElement as fe } from "react";
import { l as ve } from "./chevron-down.es-PCIIj6oG.mjs";
import { L as V } from "./listbox-u6__DsLw.mjs";
import { i as _e } from "./text-field-PKAaXO1N.mjs";
import { c as xe } from "./bind-CU-R61T-.mjs";
const he = {
  "purpur-autocomplete": "_purpur-autocomplete_dgjyz_1",
  "purpur-autocomplete__listbox": "_purpur-autocomplete__listbox_dgjyz_4",
  "purpur-autocomplete__chevron-button": "_purpur-autocomplete__chevron-button_dgjyz_9",
  "purpur-autocomplete__chevron-icon": "_purpur-autocomplete__chevron-icon_dgjyz_15",
  "purpur-autocomplete__chevron-icon--up": "_purpur-autocomplete__chevron-icon--up_dgjyz_20"
}, ye = (c) => D(c), Ce = (c, b) => {
  const n = pe(
    (v) => {
      c && !c.contains(v.target) && b();
    },
    [b, c]
  );
  me(() => (document.addEventListener("mousedown", n), () => {
    document.removeEventListener("mousedown", n);
  }), [n]);
}, ge = ({
  combobox: c,
  comboboxButtonAriaLabel: b,
  highlightFirstOption: n,
  defaultInputValue: v,
  inputValue: i,
  filterOption: I,
  id: u,
  listboxLabel: S,
  listboxMaxHeight: d,
  onInputBlur: _,
  onInputChange: L,
  onInputFocus: $,
  onInputKeyDown: R,
  onInputMouseDown: T,
  openOnFocus: k,
  noOptionsText: E,
  onSelect: j,
  options: a,
  selectedOption: t,
  ["data-testid"]: x
}) => {
  const [h, K] = U(
    ((typeof i == "string" ? i : v) || t?.label) ?? ""
  ), Y = typeof i == "string" ? i : h, [r, f] = U(n ? a[0] : void 0), A = D(null), F = ye(null), N = D(null), B = D({}), [q, G] = U(!1);
  function P(e) {
    return x ? `${x}-${e}` : void 0;
  }
  const y = () => {
    G(!1), f(void 0);
  };
  Ce(F.current, y);
  const C = ({ eventType: e }) => {
    G(!0), t && requestAnimationFrame(() => {
      f({ ...t, isSetByClickEvent: e === "CLICK" }), M(B.current[t.id]);
    });
  }, ee = (e) => {
    if (I)
      return a.filter((s) => I(e, s));
    if (!e)
      return a;
    const o = e.toUpperCase().split(" ") || [];
    return a.filter(
      (s) => o.every(
        (m) => (s.value || s.label).toUpperCase().includes(m)
      )
    );
  }, J = (e) => t && t?.label === e ? a : ee(e), l = J(Y), z = (e) => {
    L?.(e), K(e);
  }, M = (e) => {
    if (e) {
      const o = e.getBoundingClientRect(), s = N.current?.getBoundingClientRect() || { top: 0, bottom: 0 };
      (o.top < s.top || o.bottom > s.bottom) && e.scrollIntoView({ block: "nearest" });
    }
  }, Q = (e) => {
    e && (A.current?.focus(), z(e.label), j?.(e)), y();
  }, te = (e) => {
    const o = n && !r ? 0 : l.findIndex((m) => m && r?.id === m.id), s = l.length;
    return e === "ArrowDown" ? l[(o ?? -1) + 1] || l[0] : l[(o ?? s) - 1] || l[s - 1];
  }, p = q && (!!l.length || !!E), oe = (e) => {
    !p && C({ eventType: "KEYBOARD" });
    const o = te(e);
    f(o), o && M(B.current[o.id]);
  }, ne = (e) => {
    switch (R?.(e), e.key) {
      case "ArrowUp":
      case "ArrowDown":
        e.preventDefault(), oe(e.key);
        break;
      case "Enter": {
        const o = r || (n ? a[0] : void 0);
        p && Q(o), !p && C({ eventType: "KEYBOARD" });
        break;
      }
      case "Escape":
      case "Tab":
        y();
        break;
    }
  }, se = (e) => {
    const o = J(e.target.value);
    z(e.target.value), f(void 0), !p && C({ eventType: "KEYBOARD" }), n && o[0] && M(B.current[o[0].id]);
  }, re = (e) => {
    T?.(e), p ? y() : C({ eventType: "CLICK" });
  }, ce = (e) => {
    $?.(e), !q && k && C({ eventType: "KEYBOARD" }), A.current?.select();
  }, ie = (e) => {
    _?.(e), setTimeout(() => {
      !A.current?.contains(document.activeElement) && !N.current?.contains(document.activeElement) && (y(), c && z(t ? t.label : ""));
    });
  }, ue = {
    maxHeight: typeof d == "number" ? `${d}px` : d
  }, W = {
    "aria-label": S,
    "aria-expanded": p,
    "data-testid": P("listbox"),
    id: `${u}-listbox`,
    ref: N,
    onMouseLeave: () => f(void 0),
    style: d ? ue : void 0
  }, X = (e) => `${u}-listbox-item-${e.id}`, ae = (e, o) => {
    const s = () => e.id !== r?.id && f({ ...e, isSetByClickEvent: !0 }), m = (e.id === r?.id || !!n && !r && o === 0) && !r?.isSetByClickEvent;
    return {
      "data-testid": P(`listbox-item-${e.id}`),
      id: X(e),
      key: e.id,
      onMouseMove: s,
      onMouseUp: () => Q(e),
      ref: (Z) => {
        Z && (B.current[e.id] = Z);
      },
      tabIndex: -1,
      selected: e.id === t?.id,
      disabled: e.disabled,
      highlighted: m,
      hovered: e.id === r?.id && !!r?.isSetByClickEvent
    };
  }, le = {
    "aria-activedescendant": r ? X(r) : void 0,
    "aria-autocomplete": "list",
    "aria-controls": W.id,
    "data-testid": P("input"),
    autoComplete: "off",
    id: `${u}-input`,
    onChange: se,
    onMouseDown: re,
    onFocus: ce,
    onKeyDown: ne,
    onBlur: ie,
    ref: A,
    role: "combobox",
    value: Y
  };
  return {
    id: u,
    inputProps: le,
    internalRef: F,
    optionsToShow: l,
    showListbox: p,
    noOptionsText: E,
    combobox: c,
    comboboxButtonAriaLabel: b,
    getListBoxItemProps: ae,
    listboxProps: W
  };
}, O = xe.bind(he), w = "purpur-autocomplete", we = ({ className: c, renderInput: b, renderOption: n, ...v }, i) => {
  const {
    id: I,
    inputProps: u,
    internalRef: S,
    optionsToShow: d,
    showListbox: _,
    noOptionsText: L,
    combobox: $,
    comboboxButtonAriaLabel: R,
    getListBoxItemProps: T,
    listboxProps: k
  } = ge(v), E = (t, x) => {
    const { key: h, ...K } = T(t, x);
    return /* @__PURE__ */ g(V.Item, { ...K, children: n ? n?.(t) : t.label }, h);
  }, j = (t) => {
    S.current = t, typeof i == "function" ? i(t) : i && (i.current = t);
  }, a = () => {
    const t = b(u);
    if ($ && R && L && t && _e(t)) {
      const h = /* @__PURE__ */ H(de, { children: [
        t.props.endAdornment,
        /* @__PURE__ */ g(
          "button",
          {
            "data-testid": "chevron button",
            type: "button",
            className: O(`${w}__chevron-button`),
            onClick: () => {
              u.onFocus(void 0), u.onMouseDown(void 0);
            },
            "aria-label": R,
            "aria-expanded": _,
            "aria-controls": k.id,
            children: /* @__PURE__ */ g(
              ve,
              {
                size: "sm",
                className: O(`${w}__chevron-icon`, {
                  [`${w}__chevron-icon--up`]: _
                })
              }
            )
          }
        )
      ] });
      return fe(t, { endAdornment: h });
    }
    return t;
  };
  return /* @__PURE__ */ H("div", { id: I, ref: j, className: O([w, c]), children: [
    a(),
    _ && /* @__PURE__ */ g(V, { ...k, className: O(`${w}__listbox`), children: d.length ? d.filter((t) => !!t).map(E) : /* @__PURE__ */ g(V.Item, { noninteractive: !0, children: L }) })
  ] });
}, Ie = be(we);
Ie.displayName = "Autocomplete";
export {
  Ie as A,
  ge as u
};
//# sourceMappingURL=autocomplete-0kGG_STe.mjs.map
