import { jsx, jsxs } from "react/jsx-runtime";
import { s as sprintf } from "../../sprintf-DmNrJSYG.js";
import { _ as __, a as _n } from "../../default-i18n-CnQeC5Pl.js";
import { BaseControl } from "../base-control/base-control.js";
import { $ as $d2f53cda644affe3$export$2f2b9559550c7bbc, a as $440f4836bcb56932$export$b94867ecbd698f21 } from "../../SearchField-CHYnN-jt.js";
import { $ as $d2b4bc8c273e7be6$export$353f5b6fc5456de1 } from "../../Button-BXjXzdW_.js";
import { $ as $3985021b0ad6602f$export$f5b8910cec6cf069 } from "../../Input-CNNksOWg.js";
import { $ as $01b77f81d0f07f68$export$b04be29aa201d4f5 } from "../../Label-D8a3eYb-.js";
import { $ as $eed445e0843c11d0$export$41f133550aa26f48 } from "../../ListBox-Dd37zMvs.js";
import { $ as $07b14b47974efb58$export$5b6b19405a83ff9d } from "../../Dialog-D8bjn-nh.js";
import { $ as $82d7e5349645de74$export$ef9b1a59e592288f, a as $82d7e5349645de74$export$e288731fd71264f0, S as SelectClearButton, O as OptionItemBase } from "../../shared-DwjRce5e.js";
import { useRef, cloneElement } from "react";
import { icons } from "../../icons/icons.js";
import "../../react-jsx-parser.min-B_hvYYa1.js";
import { Spinner } from "../../icons/spinner.js";
import { RichLabel } from "../rich-label/rich-label.js";
import { unescapeHTML } from "../../utilities/text-helpers.js";
import { c as cva } from "../../index-BHpUy2Ix.js";
import { TriggeredPopover } from "../popover/popover.js";
import { DraggableList } from "../draggable-list/draggable-list.js";
import { DraggableListItem } from "../draggable-list/draggable-list-item.js";
import { c as clsx } from "../../clsx-DgYk2OaC.js";
import { $ as $f86e6c1ec7da6ebb$export$bc3384a35de93d66 } from "../../useAsyncList-D52mQcrH.js";
/**
 * Async multi-select menu.
 *
 * @component
 * @param {Object} props - Component props.
 * @param {string} [props.label] - Label of the component.
 * @param {string} [props.help] - Help text of the component.
 * @param {string} [props.icon] - Icon of the component.
 * @param {string} [props.subtitle] - Subtitle of the component.
 * @param {JSX.Element|JSX.Element[]} [props.actions] - Actions to show to the right of the label.
 * @param {boolean} [props.inline] - Whether the Select menu is displayed inline with the label, to the right.
 * @param {{label: string, value: string, metadata: Object<string, any>?}[]} props.value - Current value of the select.
 * @param {Function} props.onChange - Function to call when the value changes.
 * @param {boolean} [props.clearable=false] - Whether the select is clearable.
 * @param {boolean} [props.disabled=false] - Whether the select is disabled.
 * @param {string} [props.placeholder] - Placeholder text to show when no value is selected.
 * @param {Function} [props.getLabel] - Function to get the label for the item from the fetched data. `(item: Object<string, any>) => string`
 * @param {Function} [props.getValue] - Function to get the value for the item from the fetched data. `(item: Object<string, any>) => string`
 * @param {Function} [props.getMeta] - Function to get the metadata for the item from the fetched data. `(item: Object<string, any>) => Object<string, any>` (optional)
 * @param {Function} [props.getIcon] - Function to get the icon for the item from the fetched data. `(item: Object<string, any>) => JSX.Element | string`
 * @param {Function} [props.getSubtitle] - Function to get the subtitle for the item from the fetched data. `(item: Object<string, any>) => string`
 * @param {Function} [props.getData] - Function to pre-process the fetched data before it is used in the select. `(data: Object<string, any>[]) => Object<string, any>[]`
 * @param {Function} [props.fetchUrl] - Function to get the URL for fetching data. Provides typed search text if entered. `(searchText: string) => string`
 * @param {Object} [props.fetchConfig] - Configuration object for the fetch request, passed to the `fetch` function.
 * @param {Function} [props.fetchFunction] - Allows overriding the default fetch function. `fetchFunction: (url: string, fetchOptions: Object<string, any>, searchText?: string) => Promise<Object<string, any>>`
 * @param {Function} [props.processLoadedOptions] - Allows processing the options fetched from the source. `(options: Object<string, any>[]) => Object<string, any>[]`
 * @param {JSX.Element} [props.customMenuOption] - If provided, replaces the default item in the dropdown menu. `({ value: string, label: string, subtitle: string, metadata: any }) => JSX.Element`
 * @param {JSX.Element} [props.customValueDisplay] - If provided, replaces the default current value display of each selected item. `({ value: string, label: string, subtitle: string, metadata: any }) => JSX.Element`
 * @param {JSX.Element} [props.customDropdownArrow] - If provided, replaces the default dropdown arrow indicator.
 * @param {string} props.className - Classes to pass to the select menu.
 * @param {boolean} [props.noMinWidth=false] - If `true`, the select menu will not have a minimum width.
 * @param {boolean} [props.flat] - If `true`, component will look more flat. Useful for nested layer of controls.
 * @param {boolean} [props.noReorder] - If `true`, the option for reordering selected items is disabled.
 * @param {SelectSize} [props.size='default'] - Sets the size of the input field.
 * @param {boolean} [props.hidden] - If `true`, the component is not rendered.
 *
 * @typedef {'small' | 'medium' | 'default' | 'large'} SelectSize
 *
 * @returns {JSX.Element} The AsyncMultiSelect component.
 *
 * @example
 * const [value, setValue] = useState(null);
 *
 * <AsyncMultiSelect
 * 	label='Select items'
 * 	value={value}
 * 	onChange={setValue}
 * 	fetchUrl={(searchText) => `https://api.example.com/items?search=${searchText}`}
 * 	getLabel={(item) => item?.label}
 * 	getValue={(item) => item?.id}
 * 	getIcon={() => icons.emptyCircle}
 * />
 *
 * @preserve
 */
const AsyncMultiSelect = (props) => {
  const {
    label,
    help,
    icon,
    subtitle,
    actions,
    inline,
    value,
    onChange,
    clearable,
    disabled,
    placeholder = __("Select...", "eightshift-ui-components"),
    fetchUrl,
    fetchConfig = {},
    fetchFunction,
    getLabel = (item) => item?.label,
    getValue = (item) => item?.value,
    getMeta,
    getIcon,
    getSubtitle,
    getData = (data) => data,
    customMenuOption,
    customValueDisplay,
    customDropdownArrow,
    className,
    flat,
    size = "default",
    noMinWidth = false,
    noReorder,
    hidden,
    processLoadedOptions,
    ...rest
  } = props;
  const list = $f86e6c1ec7da6ebb$export$bc3384a35de93d66({
    initialSelectedKeys: Array.isArray(value) ? value.map((item) => item?.value) : [],
    getKey: (item) => item.value,
    async load({ signal, filterText }) {
      let json = [];
      if (fetchFunction) {
        const res = await fetchFunction(filterText, signal);
        json = processLoadedOptions ? processLoadedOptions(getData(res)) : getData(res);
      } else {
        const res = await fetch(fetchUrl(filterText), { ...fetchConfig, signal });
        json = processLoadedOptions ? processLoadedOptions(getData(await res.json())) : getData(res);
      }
      const output = json?.map((item, index) => {
        const id = getValue?.(item) ?? index;
        const entry = { ...item, label: unescapeHTML(getLabel?.(item) ?? ""), value: id };
        if (getMeta) {
          entry.meta = getMeta(item);
        }
        if (getSubtitle) {
          entry.subtitle = unescapeHTML(getSubtitle(item));
        }
        return entry;
      });
      if (filterText.length > 0) {
        return {
          items: output
        };
      }
      const extra = value?.map((val) => {
        if (output?.find((item) => item.value === val?.value)) {
          return null;
        }
        return val;
      })?.filter(Boolean) ?? [];
      return {
        items: [...output, ...extra]
      };
    }
  });
  const handleSelectionChange = (rawSelected) => {
    const selected = list.filterText.length > 0 ? /* @__PURE__ */ new Set([...value?.map((item) => item?.value) ?? [], ...rawSelected]) : rawSelected;
    list.filterText = "";
    if (selected === null || selected === void 0) {
      onChange(null);
      return;
    }
    if (selected.size === 0) {
      onChange([]);
      return;
    }
    const selectedValues = [...selected].map((item) => {
      const option = list.items.find((option2) => option2.value === item) || value.find((option2) => option2.value === item);
      if (!option) {
        return null;
      }
      return {
        ...option
      };
    }).filter(Boolean);
    onChange(
      selectedValues.map((item) => ({
        label: item?.label,
        value: item?.value,
        subtitle: item?.subtitle,
        meta: item?.meta
      }))
    );
  };
  const ref = useRef();
  const currentValueKeys = value?.map((item) => item?.value ?? item);
  const selectClass = cva(
    [
      "es:relative",
      "es:flex es:items-center es:gap-px",
      "es:leading-none",
      "es:rounded-lg es:hover:rounded-xl es:has-focus-visible:rounded-2xl es:group-open:rounded-2xl",
      "es:transition-plus",
      "es:any-focus:outline-hidden",
      "es:inset-ring",
      "es:has-focus-visible:ring-2 es:has-focus-visible:ring-accent-500/30",
      "es:has-focus-visible:text-accent-950 es:has-focus-visible:inset-ring-accent-500",
      "es:pr-8",
      "es:focus:placeholder:text-surface-400",
      !noMinWidth && "es:min-w-48",
      !inline && "es:w-fill",
      className
    ],
    {
      variants: {
        size: {
          small: ["es:min-h-8", "es:px-2.5"],
          medium: ["es:min-h-9", "es:px-3"],
          default: ["es:min-h-10", "es:px-3"],
          large: ["es:min-h-12", "es:px-4"]
        },
        disabled: {
          false: "es:selection:bg-surface-100 es:selection:text-accent-800",
          true: "es:selection:bg-secondary-200 es:selection:text-secondary-600"
        }
      },
      compoundVariants: [
        {
          flat: false,
          disabled: false,
          class: [
            "es:bg-white",
            "es:bg-linear-to-b es:from-secondary-100/0 es:to-secondary-100/50 es:from-25%",
            "es:hover:from-surface-100/0 es:hover:to-surface-100/50",
            "es:inset-ring-secondary-400/50 es:hover:inset-ring-surface-300 es:focus:inset-ring-surface-400",
            "es:inset-shadow-sm es:inset-shadow-secondary-100/50",
            "es:hover:placeholder:text-surface-400",
            "es:placeholder:text-secondary-400",
            "es:shadow-xs es:shadow-black/5"
          ]
        },
        {
          flat: true,
          disabled: false,
          class: [
            "es:inset-ring-secondary-100",
            "es:focus:text-accent-950",
            "es:placeholder:text-secondary-500/80",
            "es:bg-secondary-100 es:focus:bg-surface-50",
            "es:inset-ring-secondary-200/15 es:hover:inset-ring-secondary-200/65 es:focus:inset-ring-surface-200"
          ]
        },
        { disabled: true, class: ["es:bg-secondary-50 es:inset-ring-secondary-200 es:text-secondary-400"] },
        { readOnly: true, flat: false, class: ["es:bg-secondary-50 es:inset-ring-secondary-300 es:text-secondary-400"] },
        { readOnly: true, flat: true, class: ["es:bg-secondary-50 es:inset-ring-secondary-300/60 es:text-secondary-400"] }
      ],
      defaultVariants: { disabled: false, flat: false, size: "default" }
    }
  );
  if (hidden) {
    return null;
  }
  return /* @__PURE__ */ jsx(
    $82d7e5349645de74$export$ef9b1a59e592288f,
    {
      selectionMode: "multiple",
      isDisabled: disabled,
      value: currentValueKeys,
      onChange: (selected) => handleSelectionChange(selected),
      placeholder,
      ...rest,
      className: clsx("es:group es:w-fill", rest?.className),
      children: /* @__PURE__ */ jsxs(
        BaseControl,
        {
          label,
          icon,
          subtitle,
          actions,
          help,
          inline,
          labelAs: $01b77f81d0f07f68$export$b04be29aa201d4f5,
          children: [
            /* @__PURE__ */ jsxs(
              "div",
              {
                className: selectClass({ disabled, flat, size }),
                ref,
                children: [
                  /* @__PURE__ */ jsxs($d2b4bc8c273e7be6$export$353f5b6fc5456de1, { className: "es:any-focus:outline-hidden es:text-start es:size-full es:inline-block es:group es:overflow-x-clip", children: [
                    /* @__PURE__ */ jsx($82d7e5349645de74$export$e288731fd71264f0, { className: "es:select-none es:pointer-events-none", children: ({ isPlaceholder, selectedItems }) => {
                      const [selectedItem] = selectedItems;
                      if (!currentValueKeys?.length || isPlaceholder) {
                        return /* @__PURE__ */ jsx("span", { className: "es:select-none es:pointer-events-none es:pr-6 es:text-sm es:text-surface-500", children: placeholder });
                      }
                      let icon2 = getIcon ? getIcon(selectedItem) : selectedItem?.icon ?? null;
                      if (typeof selectedItem?.icon === "string") {
                        icon2 = icons?.[selectedItem.icon] ?? null;
                      }
                      if (selectedItems.length > 1) {
                        return /* @__PURE__ */ jsx(
                          RichLabel,
                          {
                            icon: icons.multiple,
                            label: sprintf(_n("%s item", "%s items", selectedItems.length, "eightshift-ui-components"), selectedItems.length),
                            subtitle: selectedItems.map((item) => item?.label ?? item).join(", "),
                            subtitleClassName: "es:line-clamp-1 es:max-w-56"
                          }
                        );
                      }
                      if (!isPlaceholder && value && customValueDisplay) {
                        return customValueDisplay(selectedItem);
                      }
                      return /* @__PURE__ */ jsx(
                        RichLabel,
                        {
                          icon: icon2,
                          label: selectedItem?.label,
                          subtitle: selectedItem?.subtitle,
                          className: clsx("es:pr-6 es:grow es:w-full", disabled && "es:grayscale es:pointer-events-none"),
                          iconClassName: "es:pointer-events-none es:select-none",
                          labelClassName: "es:line-clamp-1",
                          subtitleClassName: "es:line-clamp-1"
                        }
                      );
                    } }),
                    /* @__PURE__ */ jsxs(
                      "div",
                      {
                        className: clsx("es:absolute es:bottom-0 es:right-3 es:top-0 es:my-auto es:flex es:items-center", disabled ? "es:text-secondary-300" : "es:text-secondary-500"),
                        "aria-hidden": "true",
                        children: [
                          !customDropdownArrow && cloneElement(icons.dropdownCaret, {
                            className: "es:w-4 es:stroke-[1.2] es:group-aria-expanded:-scale-y-100 es:transition-transform es:duration-200"
                          }),
                          customDropdownArrow && /* @__PURE__ */ jsx(
                            "div",
                            {
                              "aria-hidden": "true",
                              className: "es:group-aria-expanded:-scale-y-100 es:transition-transform es:duration-200",
                              children: customDropdownArrow
                            }
                          )
                        ]
                      }
                    )
                  ] }),
                  clearable && /* @__PURE__ */ jsx(SelectClearButton, { multi: true }),
                  /* @__PURE__ */ jsxs(
                    TriggeredPopover,
                    {
                      "aria-label": __("Item order", "eightshift-ui-components"),
                      triggerButtonIcon: icons.reorder,
                      triggerButtonProps: {
                        size: "small",
                        type: "ghost",
                        className: "es:icon:opacity-80 es:size-7!",
                        "aria-label": __("Reorder", "eightshift-ui-components"),
                        tooltip: true,
                        slot: null
                      },
                      className: "es:grid es:grid-cols-1 es:grid-rows-[auto_minmax(0,1fr)] es:p-0!",
                      wrapperClassName: "es:w-72 es:px-1.5 es:h-fit es:from-surface-300/35 es:to-surface-300/35 es:overflow-clip",
                      hidden: noReorder || disabled || value?.length < 2,
                      children: [
                        /* @__PURE__ */ jsx("span", { className: 'es:text-lg es:mx-auto es:my-1 es:font-variation-["wdth"_140,"wght"_320] es:text-surface-600', children: __("Item order", "eightshift-ui-components") }),
                        /* @__PURE__ */ jsx(
                          DraggableList,
                          {
                            items: value,
                            onChange: (value2) => {
                              handleSelectionChange(new Set(value2?.map((item) => item?.value ?? item)));
                            },
                            className: "es:contents",
                            itemContainerClassName: "es:h-full es:max-h-60 es:overflow-y-auto es:pb-1.5 es:mt-0",
                            itemClassName: "es:z-999999",
                            children: (item) => {
                              const realItem = list.getItem(item?.value);
                              let icon2 = getIcon ? getIcon(realItem) : realItem?.icon ?? null;
                              if (typeof realItem?.icon === "string") {
                                icon2 = icons?.[realItem.icon] ?? null;
                              }
                              return /* @__PURE__ */ jsx(
                                DraggableListItem,
                                {
                                  icon: icon2,
                                  label: realItem?.label,
                                  subtitle: realItem?.subtitle,
                                  iconClassName: "es:pointer-events-none es:select-none",
                                  labelClassName: "es:line-clamp-1",
                                  subtitleClassName: "es:line-clamp-1",
                                  className: clsx("es:min-h-8 es:flex es:items-center es:justify-between", realItem?.icon ? "es:pl-1" : "es:pl-2")
                                }
                              );
                            }
                          }
                        )
                      ]
                    }
                  )
                ]
              }
            ),
            /* @__PURE__ */ jsx(
              $07b14b47974efb58$export$5b6b19405a83ff9d,
              {
                className: ({ isEntering, isExiting }) => clsx(
                  "es:w-(--trigger-width) es:min-w-72",
                  "es:outline-hidden",
                  "es:rounded-b-xl es:rounded-t-3xl",
                  "es:overflow-clip es:grid es:grid-cols-1",
                  "es:grid-rows-[auto_minmax(0,1fr)]",
                  "es:has-last-selected:rounded-b-20!",
                  "es:inset-ring es:inset-ring-surface-500/10",
                  "es:inset-shadow-sm es:inset-shadow-white/30",
                  !list?.items?.length ? "es:bg-surface-50/50" : "es:bg-surface-300/50",
                  !list?.items?.length ? "es:backdrop-blur-sm" : "es:backdrop-blur-md",
                  !list?.items?.length ? "es:backdrop-brightness-105" : "es:backdrop-brightness-110",
                  "es:backdrop-saturate-125",
                  "es:shadow-lg es:shadow-black/10",
                  "es:transition-plus",
                  "es:motion-duration-300 es:motion-ease-spring-bouncy",
                  "es:placement-bottom:origin-top-left es:placement-top:origin-bottom-left",
                  isEntering && "es:motion-scale-x-in-95 es:motion-scale-y-in-85 es:motion-opacity-in-0 es:motion-blur-in-[2px]",
                  isEntering && "es:placement-top:motion-translate-y-in-[0.5rem] es:placement-bottom:motion-translate-y-in-[-0.5rem]",
                  isExiting && "es:motion-scale-x-out-95 es:motion-scale-y-out-85 es:motion-opacity-out-0 es:motion-blur-out-xs",
                  isExiting && "es:placement-top:motion-translate-y-out-[0.5rem] es:placement-bottom:motion-translate-y-out-[-0.5rem]"
                ),
                placement: "bottom left",
                maxHeight: 260,
                triggerRef: ref,
                children: /* @__PURE__ */ jsxs(
                  $d2f53cda644affe3$export$2f2b9559550c7bbc,
                  {
                    inputValue: list.filterText,
                    onInputChange: list.setFilterText,
                    children: [
                      /* @__PURE__ */ jsxs(
                        $440f4836bcb56932$export$b94867ecbd698f21,
                        {
                          "aria-label": __("Search", "eightshift-ui-components"),
                          className: "es:flex es:items-center es:relative",
                          children: [
                            /* @__PURE__ */ jsx(
                              $3985021b0ad6602f$export$f5b8910cec6cf069,
                              {
                                placeholder: __("Search...", "eightshift-ui-components"),
                                className: clsx(
                                  "es:peer es:size-full es:h-9.5 es:outline-hidden es:pl-3.5 es:pr-9 es:shadow-none es:text-13 es:placeholder:text-surface-500 es:[&::-webkit-search-cancel-button]:hidden",
                                  "es:bg-accent-900/8 es:m-1.5 es:rounded-3xl es:border-none",
                                  "es:inset-ring es:inset-ring-accent-950/7 es:focus:inset-ring-accent-950/20",
                                  "es:text-accent-950 es:placeholder:text-accent-700/50",
                                  "es:transition"
                                )
                              }
                            ),
                            /* @__PURE__ */ jsx(
                              $d2b4bc8c273e7be6$export$353f5b6fc5456de1,
                              {
                                "aria-label": __("Clear", "eightshift-ui-components"),
                                className: clsx(
                                  "es:absolute es:right-3 es:top-0 es:bottom-0 es:my-auto es:border-none es:bg-transparent",
                                  "es:flex es:size-7 es:items-center es:justify-center es:rounded-3xl es:text-sm es:text-surface-700 es:transition es:hover:bg-accent-50 es:hover:text-accent-800 es:any-focus:outline-hidden es:focus:ring-2 es:focus:ring-accent-500/50 es:disabled:text-secondary-300 es:cursor-pointer",
                                  "es:peer-placeholder-shown:opacity-0"
                                ),
                                children: icons.clearAlt
                              }
                            )
                          ]
                        }
                      ),
                      list.isLoading && /* @__PURE__ */ jsx("div", { className: "es:p-3 es:min-h-16 es:flex es:items-center es:justify-center", children: /* @__PURE__ */ jsx(Spinner, {}) }),
                      /* @__PURE__ */ jsx(
                        $eed445e0843c11d0$export$41f133550aa26f48,
                        {
                          className: clsx("es:space-y-0.75 es:p-1.5 es:pt-0 es:any-focus:outline-hidden es:h-full es:overflow-y-auto es:rounded-t-xl", list?.isLoading && "es:hidden"),
                          items: list.items,
                          selectedKeys: list.selectedKeys,
                          selectionMode: "multiple",
                          selectionBehavior: "toggle",
                          onSelectionChange: (selected) => {
                            list.setSelectedKeys(selected);
                            handleSelectionChange(selected);
                          },
                          renderEmptyState: () => /* @__PURE__ */ jsx(
                            RichLabel,
                            {
                              icon: icons.searchEmpty,
                              label: __("No results", "eightshift-ui-components"),
                              subtitle: __("Try a different search term", "eightshift-ui-components"),
                              className: "es:min-h-14 es:p-2 es:w-fit es:mx-auto es:motion-preset-slide-up es:motion-ease-spring-bouncy es:motion-duration-200 es:shrink-0",
                              iconClassName: "es:text-accent-700 es:icon:size-7!",
                              noColor: true
                            }
                          ),
                          children: (item) => {
                            let icon2 = getIcon ? getIcon(item) : item?.icon ?? null;
                            if (typeof item?.icon === "string") {
                              icon2 = icons?.[item.icon] ?? null;
                            }
                            return /* @__PURE__ */ jsxs(
                              OptionItemBase,
                              {
                                id: item?.value,
                                className: item?.className,
                                selectIndicator: true,
                                children: [
                                  customMenuOption && customMenuOption(item),
                                  !customMenuOption && /* @__PURE__ */ jsx(
                                    RichLabel,
                                    {
                                      icon: icon2,
                                      label: item?.label,
                                      subtitle: item?.subtitle,
                                      labelClassName: "es:line-clamp-1",
                                      subtitleClassName: "es:line-clamp-1",
                                      noColor: true
                                    }
                                  )
                                ]
                              }
                            );
                          }
                        }
                      )
                    ]
                  }
                )
              }
            )
          ]
        }
      )
    }
  );
};
export {
  AsyncMultiSelect
};
