import { jsx as s, jsxs as k, Fragment as De } from "react/jsx-runtime";
import { useFormFieldControl as be } from "../form-field/index.mjs";
import { Children as $, isValidElement as O, createContext as L, useState as D, useId as b, useEffect as M, Fragment as ae, useContext as F, useRef as Ne, useLayoutEffect as Pe } from "react";
import { Popover as P } from "../popover/index.mjs";
import { u as Ce, a as x } from "../downshift.esm-Ncwetv0s.mjs";
import { a as w, c as ie } from "../index-BmAFn37q.mjs";
import { useMergeRefs as G } from "@spark-ui/hooks/use-merge-refs";
import { Check as Te } from "@spark-ui/icons/Check";
import { I as R } from "../Icon-D1RueiPY.mjs";
import { ArrowHorizontalDown as Se } from "@spark-ui/icons/ArrowHorizontalDown";
import { V as Ee } from "../VisuallyHidden-ByNP7ZUI.mjs";
const ke = ({
  itemsMap: e,
  defaultValue: o,
  value: t,
  onValueChange: n,
  open: i,
  onOpenChange: l,
  defaultOpen: d,
  multiple: a,
  id: u,
  labelId: f
}) => {
  const c = [...e.values()], p = Ce({
    selectedItems: t != null && a ? c.filter(
      (r) => a ? t.includes(r.value) : t === r.value
    ) : void 0,
    initialSelectedItems: o != null && a ? c.filter(
      (r) => a ? o.includes(r.value) : o === r.value
    ) : void 0,
    onSelectedItemsChange: ({ selectedItems: r }) => {
      r != null && a && n?.(r.map((m) => m.value));
    }
  });
  return {
    ...x({
      items: c,
      isItemDisabled: (r) => r.disabled,
      itemToString: (r) => r ? r.text : "",
      // a11y attributes
      id: u,
      labelId: f,
      // Controlled open state
      isOpen: i,
      // undefined must be passed for stateful behaviour (uncontrolled)
      onIsOpenChange: ({ isOpen: r }) => {
        r != null && l?.(r);
      },
      initialIsOpen: d ?? !1,
      stateReducer: (r, { changes: m, type: v }) => {
        if (!a) return m;
        const { selectedItems: g, removeSelectedItem: C, addSelectedItem: T } = p;
        switch (v) {
          case x.stateChangeTypes.ToggleButtonKeyDownEnter:
          case x.stateChangeTypes.ToggleButtonKeyDownSpaceButton:
          case x.stateChangeTypes.ItemClick:
            return m.selectedItem != null && (g.some(
              (S) => S.value === m.selectedItem?.value
            ) ? C(m.selectedItem) : T(m.selectedItem)), {
              ...m,
              isOpen: !0,
              // keep the menu open after selection.
              highlightedIndex: r.highlightedIndex
              // preserve highlighted index position
            };
          default:
            return m;
        }
      },
      // Controlled mode (single selection)
      selectedItem: t != null && !a ? e.get(t) || null : void 0,
      initialSelectedItem: (o != null || t != null) && !a ? e.get(o) || null : void 0,
      onSelectedItemChange: ({ selectedItem: r }) => {
        r?.value != null && !a && n?.(r?.value);
      },
      /**
       * 1. Downshift default behaviour is to scroll into view the highlighted item when the dropdown opens. This behaviour is not stable and scrolls the dropdown to the bottom of the screen.
       */
      scrollIntoView: (r) => {
        r && r.scrollIntoView({ block: "nearest" });
      }
    }),
    ...p,
    /** There is a Downshift bug in React 19, it duplicates some selectedItems */
    selectedItems: [...new Set(p.selectedItems)]
  };
};
function $e(e, o) {
  let t = 0;
  for (const [n] of e.entries()) {
    if (n === o)
      return t;
    t++;
  }
  return -1;
}
const Oe = (e, o) => {
  let t = 0;
  for (const n of e.keys()) {
    if (t === o) return n;
    t++;
  }
}, Le = (e, o) => {
  const t = Oe(e, o);
  return t !== void 0 ? e.get(t) : void 0;
}, z = (e) => e ? e.type.displayName : "", de = (e, o = []) => ($.forEach(e, (t) => {
  if (O(t)) {
    if (z(t) === "Dropdown.Item") {
      const n = t.props;
      o.push({
        value: n.value,
        disabled: !!n.disabled,
        text: A(n.children)
      });
    }
    t.props.children && de(t.props.children, o);
  }
}), o), A = (e, o = "") => typeof e == "string" ? e : ($.forEach(e, (t) => {
  O(t) && (z(t) === "Dropdown.ItemText" && (o = t.props.children), t.props.children && A(t.props.children, o));
}), o), se = (e) => {
  const o = /* @__PURE__ */ new Map();
  return de(e).forEach((t) => {
    o.set(t.value, t);
  }), o;
}, le = (e, o) => $.toArray(e).some((t) => O(t) ? z(t) === o ? !0 : t.props.children ? le(t.props.children, o) : !1 : !1), ce = L(null), N = ":dropdown", Me = ({
  children: e,
  defaultValue: o,
  value: t,
  onValueChange: n,
  open: i,
  onOpenChange: l,
  defaultOpen: d,
  multiple: a = !1,
  disabled: u = !1,
  readOnly: f = !1,
  state: c
}) => {
  const [p, I] = D(se(e)), [h, r] = D(
    le(e, "Dropdown.Popover")
  ), [m, v] = D("mouse"), g = be(), C = g.state || c, T = `${N}-label-${b()}`, Z = `${N}-input-${b()}`, S = g.id || Z, we = g.labelId || T, ge = g.disabled ?? u, Ie = g.readOnly ?? f, ee = ke({
    itemsMap: p,
    defaultValue: o,
    value: t,
    onValueChange: n,
    open: i,
    onOpenChange: l,
    defaultOpen: d,
    multiple: a,
    id: S,
    labelId: we
  });
  M(() => {
    const te = se(e), oe = [...p.values()], E = [...te.values()];
    (oe.length !== E.length || oe.some((ne, re) => {
      const ve = ne.value !== E[re]?.value, xe = ne.text !== E[re]?.text;
      return ve || xe;
    })) && I(te);
  }, [e]);
  const [he, ye] = h ? [P, { open: !0 }] : [ae, {}];
  return /* @__PURE__ */ s(
    ce.Provider,
    {
      value: {
        multiple: a,
        disabled: ge,
        readOnly: Ie,
        ...ee,
        itemsMap: p,
        highlightedItem: Le(p, ee.highlightedIndex),
        hasPopover: h,
        setHasPopover: r,
        state: C,
        lastInteractionType: m,
        setLastInteractionType: v
      },
      children: /* @__PURE__ */ s(he, { ...ye, children: e })
    }
  );
}, y = () => {
  const e = F(ce);
  if (!e)
    throw Error("useDropdownContext must be used within a Dropdown provider");
  return e;
}, pe = ({ children: e, ...o }) => /* @__PURE__ */ s(Me, { ...o, children: e });
pe.displayName = "Dropdown";
const B = ({ className: e, ref: o }) => /* @__PURE__ */ s("div", { ref: o, className: w("my-md border-b-sm border-outline", e) });
B.displayName = "Dropdown.Divider";
const ue = L(null), Fe = ({ children: e }) => {
  const o = `${N}-group-label-${b()}`;
  return /* @__PURE__ */ s(ue.Provider, { value: { labelId: o }, children: e });
}, me = () => {
  const e = F(ue);
  if (!e)
    throw Error("useDropdownGroupContext must be used within a DropdownGroup provider");
  return e;
}, H = ({ children: e, ref: o, ...t }) => /* @__PURE__ */ s(Fe, { children: /* @__PURE__ */ s(Ge, { ref: o, ...t, children: e }) }), Ge = ({ children: e, className: o, ref: t }) => {
  const { labelId: n } = me();
  return /* @__PURE__ */ s("div", { ref: t, role: "group", "aria-labelledby": n, className: w(o), children: e });
};
H.displayName = "Dropdown.Group";
const fe = L(null), Re = ({
  value: e,
  disabled: o = !1,
  children: t
}) => {
  const { multiple: n, itemsMap: i, selectedItem: l, selectedItems: d } = y(), [a, u] = D(void 0), f = $e(i, e), c = { disabled: o, value: e, text: A(t) }, p = n ? d.some((I) => I.value === e) : l?.value === e;
  return /* @__PURE__ */ s(
    fe.Provider,
    {
      value: { textId: a, setTextId: u, isSelected: p, itemData: c, index: f, disabled: o },
      children: t
    }
  );
}, V = () => {
  const e = F(fe);
  if (!e)
    throw Error("useDropdownItemContext must be used within a DropdownItem provider");
  return e;
}, j = ({ children: e, ref: o, ...t }) => {
  const { value: n, disabled: i } = t;
  return /* @__PURE__ */ s(Re, { value: n, disabled: i, children: /* @__PURE__ */ s(Ae, { ref: o, ...t, children: e }) });
}, ze = ie("px-lg py-md text-body-1", {
  variants: {
    selected: {
      true: "font-bold"
    },
    disabled: {
      true: "opacity-dim-3 cursor-not-allowed",
      false: "cursor-pointer"
    },
    highlighted: {
      true: ""
    },
    interactionType: {
      mouse: "",
      keyboard: ""
    }
  },
  compoundVariants: [
    {
      highlighted: !0,
      interactionType: "mouse",
      class: "bg-surface-hovered"
    },
    {
      highlighted: !0,
      interactionType: "keyboard",
      class: "u-outline"
    }
  ]
}), Ae = ({
  className: e,
  disabled: o = !1,
  value: t,
  children: n,
  ref: i
}) => {
  const { getItemProps: l, highlightedItem: d, lastInteractionType: a } = y(), { textId: u, index: f, itemData: c, isSelected: p } = V(), I = d?.value === t, { ref: h, ...r } = l({ item: c, index: f }), m = G(i, h);
  return /* @__PURE__ */ s(
    "li",
    {
      ref: m,
      className: w(
        ze({
          selected: p,
          disabled: o,
          highlighted: I,
          interactionType: a,
          className: e
        })
      ),
      ...r,
      "aria-selected": p,
      "aria-labelledby": u,
      children: n
    },
    t
  );
};
j.displayName = "Dropdown.Item";
const K = ({
  className: e,
  children: o,
  label: t,
  ref: n
}) => {
  const { disabled: i, isSelected: l } = V(), d = o || /* @__PURE__ */ s(R, { size: "sm", children: /* @__PURE__ */ s(Te, { "aria-label": t }) });
  return /* @__PURE__ */ s(
    "span",
    {
      ref: n,
      className: w("min-h-sz-16 min-w-sz-16 flex", i && "opacity-dim-3", e),
      children: l && d
    }
  );
};
K.displayName = "Dropdown.ItemIndicator";
const U = ({ children: e, className: o, ref: t, ...n }) => {
  const { isOpen: i, getMenuProps: l, hasPopover: d, setLastInteractionType: a } = y(), { ref: u, ...f } = l({
    onMouseMove: () => {
      a("mouse");
    }
  }), c = Ne(null), p = G(t, u, c);
  return Pe(() => {
    d && c.current && c.current.parentElement && (c.current.parentElement.style.pointerEvents = i ? "" : "none", c.current.style.pointerEvents = i ? "" : "none");
  }, [i, d]), /* @__PURE__ */ s(
    "ul",
    {
      ref: p,
      className: w(
        o,
        "flex flex-col",
        i ? "pointer-events-auto! block" : "pointer-events-none invisible absolute opacity-0",
        d && "p-lg"
      ),
      ...n,
      ...f,
      "data-spark-component": "dropdown-items",
      children: e
    }
  );
};
U.displayName = "Dropdown.Items";
const W = ({ children: e, ref: o }) => {
  const t = `${N}-item-text-${b()}`, { setTextId: n } = V();
  return M(() => (n(t), () => n(void 0))), /* @__PURE__ */ s("span", { id: t, className: w("inline"), ref: o, children: e });
};
W.displayName = "Dropdown.ItemText";
const X = ({ children: e, className: o, ref: t }) => {
  const { labelId: n } = me();
  return /* @__PURE__ */ s(
    "div",
    {
      ref: t,
      id: n,
      className: w("px-md py-sm text-body-2 text-neutral italic", o),
      children: e
    }
  );
};
X.displayName = "Dropdown.Label";
const _ = ({ children: e }) => /* @__PURE__ */ s(R, { size: "sm", className: "shrink-0", children: e });
_.displayName = "Dropdown.LeadingIcon";
const q = ({
  children: e,
  matchTriggerWidth: o = !0,
  sideOffset: t = 4,
  className: n,
  elevation: i = "dropdown",
  ref: l,
  ...d
}) => {
  const a = y();
  return M(() => (a.setHasPopover(!0), () => a.setHasPopover(!1)), []), /* @__PURE__ */ s(
    P.Content,
    {
      ref: l,
      inset: !0,
      asChild: !0,
      matchTriggerWidth: o,
      elevation: i,
      className: w("relative", n),
      sideOffset: t,
      onOpenAutoFocus: (u) => {
        u.preventDefault();
      },
      ...d,
      "data-spark-component": "dropdown-popover",
      children: e
    }
  );
};
q.displayName = "Dropdown.Popover";
const J = ({ children: e, ...o }) => /* @__PURE__ */ s(P.Portal, { ...o, children: e });
J.displayName = "Dropdown.Portal";
const Be = ie(
  [
    "flex w-full items-center justify-between",
    "min-h-sz-44 rounded-lg bg-surface text-on-surface px-lg",
    "text-body-1",
    // outline styles
    "ring-1 outline-hidden ring-inset focus:ring-2 focus:ring-focus"
  ],
  {
    variants: {
      state: {
        undefined: "ring-outline",
        error: "ring-error",
        alert: "ring-alert",
        success: "ring-success"
      },
      disabled: {
        true: "disabled:bg-on-surface/dim-5 cursor-not-allowed text-on-surface/dim-3"
      },
      readOnly: {
        true: "disabled:bg-on-surface/dim-5 cursor-not-allowed text-on-surface/dim-3"
      }
    },
    compoundVariants: [
      {
        disabled: !1,
        state: void 0,
        class: "default:hover:ring-outline-high"
      }
    ]
  }
), Q = ({
  "aria-label": e,
  children: o,
  className: t,
  ref: n
}) => {
  const {
    getToggleButtonProps: i,
    getDropdownProps: l,
    getLabelProps: d,
    hasPopover: a,
    disabled: u,
    readOnly: f,
    state: c,
    setLastInteractionType: p
  } = y(), [I, h] = a ? [P.Trigger, { asChild: !0 }] : [ae, {}], { ref: r, ...m } = i({
    ...l(),
    onKeyDown: () => {
      p("keyboard");
    }
  }), v = m["aria-expanded"], g = G(n, r);
  return /* @__PURE__ */ k(De, { children: [
    e && /* @__PURE__ */ s(Ee, { children: /* @__PURE__ */ s("label", { ...d(), children: e }) }),
    /* @__PURE__ */ s(I, { ...h, children: /* @__PURE__ */ k(
      "button",
      {
        type: "button",
        ref: g,
        disabled: u || f,
        className: Be({ className: t, state: c, disabled: u, readOnly: f }),
        ...m,
        "data-spark-component": "dropdown-trigger",
        children: [
          /* @__PURE__ */ s("span", { className: "gap-md flex items-center justify-start", children: o }),
          /* @__PURE__ */ s(
            R,
            {
              className: w("ml-md shrink-0 rotate-0 transition duration-100 ease-in", {
                "rotate-180": v
              }),
              size: "sm",
              children: /* @__PURE__ */ s(Se, {})
            }
          )
        ]
      }
    ) })
  ] });
};
Q.displayName = "Dropdown.Trigger";
const Y = ({ children: e, className: o, placeholder: t, ref: n }) => {
  const { selectedItem: i, multiple: l, selectedItems: d } = y(), a = !!(l ? d.length : i), u = l ? d[0]?.text : i?.text, f = d.length > 1 ? `, +${d.length - 1}` : "";
  return /* @__PURE__ */ k("span", { ref: n, className: w("flex shrink items-center text-left", o), children: [
    /* @__PURE__ */ s(
      "span",
      {
        className: w(
          "line-clamp-1 flex-1 overflow-hidden break-all text-ellipsis",
          !a && "text-on-surface/dim-1"
        ),
        children: a ? e || u : t
      }
    ),
    f && /* @__PURE__ */ s("span", { children: f })
  ] });
};
Y.displayName = "Dropdown.Value";
const He = Object.assign(pe, {
  Group: H,
  Item: j,
  Items: U,
  ItemText: W,
  ItemIndicator: K,
  Label: X,
  Popover: q,
  Divider: B,
  Trigger: Q,
  Value: Y,
  LeadingIcon: _,
  Portal: J
});
He.displayName = "Dropdown";
H.displayName = "Dropdown.Group";
U.displayName = "Dropdown.Items";
j.displayName = "Dropdown.Item";
W.displayName = "Dropdown.ItemText";
K.displayName = "Dropdown.ItemIndicator";
X.displayName = "Dropdown.Label";
q.displayName = "Dropdown.Popover";
B.displayName = "Dropdown.Divider";
Q.displayName = "Dropdown.Trigger";
Y.displayName = "Dropdown.Value";
_.displayName = "Dropdown.LeadingIcon";
J.displayName = "Dropdown.Portal";
export {
  He as Dropdown,
  Me as DropdownProvider,
  y as useDropdownContext
};
//# sourceMappingURL=index.mjs.map
