import { jsx, jsxs, Fragment } from "react/jsx-runtime";
import { u as useControllableState } from "../../index-vuqbEv5O.js";
import { createContext, useId, useState, useMemo, useContext, useRef, useEffect } from "react";
import { cn } from "../utils/cn.js";
import { Popover, PopoverTrigger, PopoverContent } from "../popover/popover.js";
import { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem, CommandSeparator } from "../command/command.js";
import { C as ChevronDown } from "../../chevron-down-BOJO_vp4.js";
import { P as Plus } from "../../plus-D_gcJEUB.js";
const ComboboxContext = createContext({
  data: [],
  type: "item",
  value: "",
  onValueChange: () => {
  },
  open: false,
  onOpenChange: () => {
  },
  width: 200,
  setWidth: () => {
  },
  inputValue: "",
  setInputValue: () => {
  },
  id: "",
  descriptionId: void 0
});
const Combobox = ({
  data,
  type,
  defaultValue,
  value: controlledValue,
  onValueChange: controlledOnValueChange,
  defaultOpen = false,
  open: controlledOpen,
  onOpenChange: controlledOnOpenChange,
  label,
  description,
  children,
  ...props
}) => {
  const id = useId();
  const descriptionId = description ? `${id}-description` : void 0;
  const [value, onValueChange] = useControllableState({
    defaultProp: defaultValue ?? "",
    prop: controlledValue,
    onChange: controlledOnValueChange
  });
  const [open, onOpenChange] = useControllableState({
    defaultProp: defaultOpen,
    prop: controlledOpen,
    onChange: controlledOnOpenChange
  });
  const [width, setWidth] = useState(200);
  const [inputValue, setInputValue] = useState("");
  const context = useMemo(
    () => ({
      type,
      value,
      onValueChange,
      open,
      onOpenChange,
      data,
      width,
      setWidth,
      inputValue,
      setInputValue,
      id,
      descriptionId
    }),
    [
      type,
      value,
      onValueChange,
      open,
      onOpenChange,
      data,
      width,
      setWidth,
      inputValue,
      setInputValue,
      id,
      descriptionId
    ]
  );
  const comboboxElement = /* @__PURE__ */ jsx(ComboboxContext.Provider, { value: context, children: /* @__PURE__ */ jsx(Popover, { ...props, onOpenChange, open, children }) });
  if (!label) {
    return comboboxElement;
  }
  return /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
    /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsx("label", { htmlFor: id, className: "block font-medium text-strong", children: label }),
      description && /* @__PURE__ */ jsx("p", { id: descriptionId, className: "text-sm text-subtle", children: description })
    ] }),
    comboboxElement
  ] });
};
Combobox.displayName = "Combobox";
const ComboboxTrigger = ({
  children,
  size = "default",
  ...props
}) => {
  const { value, data, type, setWidth, id, descriptionId } = useContext(ComboboxContext);
  const ref = useRef(null);
  useEffect(() => {
    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        const newWidth = entry.target.offsetWidth;
        if (newWidth) {
          setWidth?.(newWidth);
        }
      }
    });
    if (ref.current) {
      resizeObserver.observe(ref.current);
    }
    return () => {
      resizeObserver.disconnect();
    };
  }, [setWidth]);
  return /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
    "button",
    {
      ...props,
      ref,
      id,
      role: "combobox",
      "aria-describedby": descriptionId,
      "data-slot": "combobox-trigger",
      "data-size": size,
      className: cn(
        // Match Select trigger styles: filled background, no border by default, rounded, focus ring, invalid ring
        'data-[placeholder]:text-disabled [&_svg:not([class*="text-"])]:text-subtle text-strong flex w-full items-center justify-between gap-2 rounded-lg bg-input px-3 py-2 whitespace-nowrap transition-shadow outline-none cursor-pointer focus:ring-2 focus:ring-ring disabled:cursor-not-allowed disabled:bg-subtle disabled:text-disabled disabled:opacity-50 aria-invalid:ring-2 aria-invalid:ring-negative data-[size=default]:h-9 data-[size=sm]:h-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*="size-"])]:size-4',
        !value && "text-subtle",
        props.className
      ),
      "data-placeholder": !value,
      children: children ?? /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(
          "span",
          {
            className: cn(
              "truncate line-clamp-1 flex items-center gap-2",
              value ? "text-strong" : "text-subtle"
            ),
            children: value ? data.find((item) => item.value === value)?.label : `Select ${type}...`
          }
        ),
        /* @__PURE__ */ jsx(ChevronDown, { className: "opacity-50 size-4" })
      ] })
    }
  ) });
};
const ComboboxContent = ({
  popoverOptions,
  ...props
}) => {
  const { width } = useContext(ComboboxContext);
  return /* @__PURE__ */ jsx(
    PopoverContent,
    {
      className: cn(
        "p-0 bg-default text-default border-default shadow-lg rounded-lg",
        "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
        popoverOptions?.className
      ),
      style: { width },
      ...popoverOptions,
      children: /* @__PURE__ */ jsx(
        Command,
        {
          className: "bg-transparent [&_[cmdk-list]]:max-h-[300px]",
          ...props
        }
      )
    }
  );
};
const ComboboxInput = ({
  value: controlledValue,
  defaultValue,
  onValueChange: controlledOnValueChange,
  ...props
}) => {
  const { type, inputValue, setInputValue } = useContext(ComboboxContext);
  const [value, onValueChange] = useControllableState({
    defaultProp: defaultValue ?? inputValue,
    prop: controlledValue,
    onChange: (newValue) => {
      setInputValue(newValue);
      controlledOnValueChange?.(newValue);
    }
  });
  return /* @__PURE__ */ jsx(
    CommandInput,
    {
      onValueChange,
      placeholder: `Search ${type}...`,
      value,
      ...props
    }
  );
};
const ComboboxList = (props) => /* @__PURE__ */ jsx(CommandList, { ...props });
const ComboboxEmpty = ({ children, ...props }) => {
  const { type } = useContext(ComboboxContext);
  return /* @__PURE__ */ jsx(CommandEmpty, { className: "py-6 text-center text-base text-subtle", ...props, children: children ?? `No ${type} found.` });
};
const ComboboxGroup = (props) => /* @__PURE__ */ jsx(CommandGroup, { ...props });
const ComboboxItem = (props) => {
  const { onValueChange, onOpenChange } = useContext(ComboboxContext);
  return /* @__PURE__ */ jsx(
    CommandItem,
    {
      onSelect: (currentValue) => {
        onValueChange(currentValue);
        onOpenChange(false);
      },
      ...props
    }
  );
};
const ComboboxSeparator = (props) => /* @__PURE__ */ jsx(CommandSeparator, { ...props });
const ComboboxCreateNew = ({
  onCreateNew,
  children,
  className
}) => {
  const { inputValue, type, onValueChange, onOpenChange } = useContext(ComboboxContext);
  if (!inputValue.trim()) {
    return null;
  }
  const handleCreateNew = () => {
    onCreateNew(inputValue.trim());
    onValueChange(inputValue.trim());
    onOpenChange(false);
  };
  return /* @__PURE__ */ jsx(
    "button",
    {
      className: cn(
        'relative flex w-full cursor-pointer select-none items-center gap-2 rounded-sm px-2 py-1.5 text-base outline-none hover:bg-subtle focus:bg-subtle text-default [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*="size-"])]:size-4',
        className
      ),
      onClick: handleCreateNew,
      type: "button",
      children: children ? children(inputValue) : /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(Plus, { className: "size-4 text-subtle" }),
        /* @__PURE__ */ jsx("span", { children: `Create new ${type}: "${inputValue}"` })
      ] })
    }
  );
};
export {
  Combobox,
  ComboboxContent,
  ComboboxCreateNew,
  ComboboxEmpty,
  ComboboxGroup,
  ComboboxInput,
  ComboboxItem,
  ComboboxList,
  ComboboxSeparator,
  ComboboxTrigger
};
