var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/layout/ListBox.tsx
var ListBox_exports = {};
__export(ListBox_exports, {
  ListBox: () => ListBox,
  ListBoxItem: () => ListBoxItem,
  ListBoxMultiple: () => ListBoxMultiple,
  ListBoxMultipleUncontrolled: () => ListBoxMultipleUncontrolled,
  ListBoxPrimitive: () => ListBoxPrimitive,
  ListBoxUncontrolled: () => ListBoxUncontrolled
});
module.exports = __toCommonJS(ListBox_exports);
var import_react2 = __toESM(require("react"), 1);
var import_clsx = require("clsx");

// src/utils/match.ts
var match = (key, values) => {
  return values[key];
};

// src/hooks/useOverwritableState.ts
var import_react = require("react");

// src/utils/resolveSetState.ts
function resolveSetState(action, prev) {
  return typeof action === "function" ? action(prev) : action;
}

// src/hooks/useOverwritableState.ts
var useOverwritableState = (initialValue, onChange) => {
  const [state, setState] = (0, import_react.useState)(initialValue);
  (0, import_react.useEffect)(() => {
    setState(initialValue);
  }, [initialValue]);
  const onChangeWrapper = (action) => {
    const resolved = resolveSetState(action, state);
    setState(resolved);
    onChange?.(state);
  };
  return [state, onChangeWrapper];
};

// src/components/layout/ListBox.tsx
var import_jsx_runtime = require("react/jsx-runtime");
var ListBoxContext = (0, import_react2.createContext)(null);
function useListBoxContext() {
  const ctx = (0, import_react2.useContext)(ListBoxContext);
  if (!ctx) {
    throw new Error("ListBoxItem must be used within a ListBoxPrimitive");
  }
  return ctx;
}
var ListBoxItem = (0, import_react2.forwardRef)(
  function ListBoxItem2({ value, disabled = false, children, className, ...rest }, ref) {
    const {
      registerItem,
      unregisterItem,
      highlightedId,
      setHighlightedId,
      onItemClick,
      isSelected
    } = useListBoxContext();
    const itemRef = (0, import_react2.useRef)(null);
    const id = import_react2.default.useId();
    (0, import_react2.useEffect)(() => {
      registerItem({ id, value, disabled, ref: itemRef });
      return () => unregisterItem(id);
    }, [id, value, disabled, registerItem, unregisterItem]);
    const isHighlighted = highlightedId === id;
    const selected = isSelected(value);
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      "li",
      {
        ref: (node) => {
          itemRef.current = node;
          if (typeof ref === "function") ref(node);
          else if (ref) ref.current = node;
        },
        id,
        role: "option",
        "aria-disabled": disabled,
        "aria-selected": selected,
        "data-highlighted": isHighlighted ? "" : void 0,
        "data-selected": selected ? "" : void 0,
        "data-disabled": disabled ? "" : void 0,
        className: (0, import_clsx.clsx)(
          "flex-row-1 items-center px-2 py-1 rounded-md",
          "data-highlighted:bg-primary/20",
          "data-disabled:text-disabled data-disabled:cursor-not-allowed",
          "not-data-disabled:cursor-pointer",
          className
        ),
        onClick: () => {
          if (!disabled) onItemClick(id);
        },
        onMouseEnter: () => {
          if (!disabled) {
            setHighlightedId(id);
          }
        },
        ...rest,
        children: children ?? value
      }
    );
  }
);
var ListBoxPrimitive = (0, import_react2.forwardRef)(
  function ListBoxPrimitive2({
    value,
    onSelectionChanged,
    onItemClicked,
    isSelection = false,
    isMultiple = false,
    orientation = "vertical",
    ...props
  }, ref) {
    const itemsRef = (0, import_react2.useRef)([]);
    const [highlightedIndex, setHighlightedIndex] = (0, import_react2.useState)(void 0);
    const registerItem = (0, import_react2.useCallback)((item) => {
      itemsRef.current.push(item);
      itemsRef.current.sort((a, b) => {
        const aEl = a.ref.current;
        const bEl = b.ref.current;
        if (!aEl || !bEl) return 0;
        return aEl.compareDocumentPosition(bEl) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;
      });
    }, []);
    const unregisterItem = (0, import_react2.useCallback)((id) => {
      itemsRef.current = itemsRef.current.filter((i) => i.id !== id);
    }, []);
    const isSelected = (0, import_react2.useCallback)(
      (val) => (value ?? []).includes(val),
      [value]
    );
    const onItemClickedHandler = (0, import_react2.useCallback)(
      (id) => {
        const index = itemsRef.current.findIndex((i) => i.id === id);
        if (index === -1) {
          console.error("ListBoxItem provided an invalid id");
          return;
        }
        const item = itemsRef.current[index];
        const val = item.value;
        onItemClicked?.(val);
        setHighlightedIndex(index);
        if (!isSelection) return;
        if (!isMultiple) {
          onSelectionChanged?.([val]);
        } else {
          if (isSelected(val)) {
            onSelectionChanged?.((value ?? []).filter((v) => v !== val));
          } else {
            onSelectionChanged?.([...value ?? [], val]);
          }
        }
      },
      [onItemClicked, isSelection, isMultiple, onSelectionChanged, isSelected, value]
    );
    const setHighlightedId = (0, import_react2.useCallback)((id) => {
      const index = itemsRef.current.findIndex((i) => i.id === id);
      if (index !== -1) {
        setHighlightedIndex(index);
      }
    }, []);
    (0, import_react2.useEffect)(() => {
      if (highlightedIndex !== void 0) {
        itemsRef.current[highlightedIndex]?.ref.current?.scrollIntoView({ block: "nearest", behavior: "auto" });
      }
    }, [highlightedIndex]);
    const highlightedItem = itemsRef.current[highlightedIndex];
    const ctxValue = {
      registerItem,
      unregisterItem,
      highlightedId: highlightedItem?.id,
      setHighlightedId,
      onItemClick: onItemClickedHandler,
      isSelected
    };
    const moveHighlight = (delta) => {
      if (itemsRef.current.length === 0) return;
      let nextIndex = highlightedIndex ?? -1;
      for (let i = 0; i < itemsRef.current.length; i++) {
        nextIndex = (nextIndex + delta + itemsRef.current.length) % itemsRef.current.length;
        if (!itemsRef.current[nextIndex].disabled) break;
      }
      setHighlightedIndex(nextIndex);
    };
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ListBoxContext.Provider, { value: ctxValue, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      "ul",
      {
        ref,
        ...props,
        onFocus: (event) => {
          if (highlightedIndex === void 0) {
            const firstEnabled = itemsRef.current.findIndex((i) => !i.disabled);
            setHighlightedIndex(firstEnabled !== -1 ? firstEnabled : void 0);
          }
          props.onFocus?.(event);
        },
        onBlur: (event) => {
          setHighlightedIndex(void 0);
          props.onBlur?.(event);
        },
        onKeyDown: (event) => {
          switch (event.key) {
            case match(orientation, {
              vertical: "ArrowDown",
              horizontal: "ArrowUp"
            }):
              moveHighlight(1);
              event.preventDefault();
              break;
            case match(orientation, {
              vertical: "ArrowUp",
              horizontal: "ArrowDown"
            }):
              moveHighlight(-1);
              event.preventDefault();
              break;
            case "Home":
              setHighlightedIndex(itemsRef.current.findIndex((i) => !i.disabled));
              event.preventDefault();
              break;
            case "End":
              for (let i = itemsRef.current.length - 1; i >= 0; i--) {
                if (!itemsRef.current[i].disabled) {
                  setHighlightedIndex(i);
                  break;
                }
              }
              event.preventDefault();
              break;
            case "Enter":
            case " ":
              if (highlightedIndex !== void 0) {
                event.preventDefault();
                onItemClickedHandler(itemsRef.current[highlightedIndex].id);
              }
              break;
          }
          props.onKeyDown?.(event);
        },
        role: "listbox",
        "aria-multiselectable": isSelection ? isMultiple : void 0,
        "aria-orientation": orientation,
        tabIndex: 0,
        children: props.children
      }
    ) });
  }
);
var ListBoxMultiple = ({ ...props }) => {
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ListBoxPrimitive, { ...props });
};
var ListBoxMultipleUncontrolled = ({
  value: initialValue,
  onSelectionChanged,
  ...props
}) => {
  const [value, setValue] = useOverwritableState(initialValue, onSelectionChanged);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    ListBoxMultiple,
    {
      ...props,
      value,
      onSelectionChanged: setValue
    }
  );
};
var ListBox = (0, import_react2.forwardRef)(function ListBox2({
  value,
  onSelectionChanged,
  ...props
}, ref) {
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    ListBoxPrimitive,
    {
      ref,
      value: value !== void 0 ? [value] : void 0,
      onSelectionChanged: (newValue) => {
        onSelectionChanged(newValue[0] ?? value);
      },
      isMultiple: false,
      ...props
    }
  );
});
var ListBoxUncontrolled = ({
  value: initialValue,
  onSelectionChanged,
  ...props
}) => {
  const [value, setValue] = useOverwritableState(initialValue, onSelectionChanged);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    ListBox,
    {
      ...props,
      value,
      onSelectionChanged: setValue
    }
  );
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ListBox,
  ListBoxItem,
  ListBoxMultiple,
  ListBoxMultipleUncontrolled,
  ListBoxPrimitive,
  ListBoxUncontrolled
});
//# sourceMappingURL=ListBox.cjs.map