"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { Listbox, ListboxButton, ListboxOptions, ListboxOption } from "@headlessui/react";
import { forwardRef, createContext, Fragment, useContext } from "react";
import { ExperimentalChip } from "./Chip.js";
import { ExperimentalLegacyMenu } from "./LegacyMenu.js";
import { ExperimentalTransition } from "./Transition.js";
import { genericForwardRef } from "../utils/genericForwardRef.js";
import { useControlled } from "./hooks/useControlled.js";
import { classNames } from "../utils/classNames.js";
import { CaretDownInteractive } from "../icons/CaretDownInteractive.js";
import { useI18n } from "../i18n/useI18n.js";
const ExperimentalSelectChipContext = createContext({
  clearable: false,
  multiple: false
});
const ExperimentalSelectChipRoot = genericForwardRef(
  ({
    label,
    value: controlledValue,
    valueIdKey,
    valueLabelKey,
    valueLabel: passedValueLabel,
    defaultValue,
    onChange,
    clearable = false,
    multiple = false,
    disabled = false,
    menuAlign = "start",
    className,
    children,
    ...props
  }, forwardedRef) => {
    if (!multiple && (Array.isArray(controlledValue) || Array.isArray(defaultValue))) {
      throw new Error("ExperimentalSelectChip: `multiple` is `false`, but `value` or `defaultValue` is an array");
    }
    if (multiple && (controlledValue !== void 0 && !Array.isArray(controlledValue) || defaultValue !== void 0 && !Array.isArray(defaultValue))) {
      throw new Error("ExperimentalSelectChip: `multiple` is `true`, but `value` or `defaultValue` is not an array");
    }
    if (!valueIdKey) {
      const controlledValueToCheck = multiple ? controlledValue == null ? void 0 : controlledValue[0] : controlledValue;
      const defaultValueToCheck = multiple ? defaultValue == null ? void 0 : defaultValue[0] : defaultValue;
      if (typeof controlledValueToCheck === "object" && controlledValueToCheck !== null || typeof defaultValueToCheck === "object" && defaultValueToCheck !== null) {
        throw new Error(
          "ExperimentalSelectChip: `valueIdKey` is required when `value` or `defaultValue` is an object or an array of objects"
        );
      }
    }
    if (clearable && multiple) {
      throw new Error("ExperimentalSelectChip: `clearable` and `multiple` cannot be used together");
    }
    const getValueId = (value2) => {
      if (value2 === null) return null;
      if (Array.isArray(value2)) {
        return value2.map((v) => v && typeof v === "object" ? v[valueIdKey] : v);
      }
      return typeof value2 === "object" ? value2[valueIdKey] : value2;
    };
    const getValueLabel = (value2) => {
      if (value2 === null || Array.isArray(value2)) return null;
      return String(typeof value2 === "object" ? value2[valueLabelKey ?? valueIdKey] : value2);
    };
    const [value, setValue] = useControlled(
      controlledValue,
      defaultValue ?? (multiple ? [] : null),
      onChange
    );
    const valueId = getValueId(value);
    const valueLabel = passedValueLabel !== void 0 ? passedValueLabel : getValueLabel(value);
    const forceNonSelectedStyle = !clearable && !multiple && defaultValue !== void 0 && areValueIdsIdentical(valueId, getValueId(defaultValue));
    const listboxOptionsAnchorTo = (() => {
      switch (menuAlign) {
        case "start":
          return "bottom start";
        case "center":
          return "bottom";
        case "end":
          return "bottom end";
      }
    })();
    return /* @__PURE__ */ jsx(ExperimentalSelectChipContext.Provider, { value: { clearable, multiple }, children: /* @__PURE__ */ jsxs(
      Listbox,
      {
        value,
        onChange: (newValue) => {
          if (clearable && getValueId(newValue) === valueId) {
            setValue(null);
          } else {
            setValue(newValue);
          }
        },
        by: valueIdKey,
        multiple,
        disabled,
        children: [
          /* @__PURE__ */ jsx(ListboxButton, { as: Fragment, children: ({ open }) => /* @__PURE__ */ jsx(
            ExperimentalChip,
            {
              ref: forwardedRef,
              "aria-label": valueLabel ? label : void 0,
              selected: Array.isArray(value) ? value.length : value !== null,
              "data-open": open || void 0,
              iconAfter: /* @__PURE__ */ jsx(CaretDownInteractive, {}),
              className: classNames(["gds-select-chip", className]),
              ...props,
              ...forceNonSelectedStyle ? { "data-selected": void 0 } : null,
              children: /* @__PURE__ */ jsx(
                ExperimentalTransition,
                {
                  layout: "inline",
                  className: `
                    max-w-full
                    @style-[--gds-transition-state=idle]:nested/transition-content:w-auto
                    @style-[--gds-transition-state=idle]:nested/transition-content:truncate
                  `,
                  children: valueLabel || label
                }
              )
            }
          ) }),
          /* @__PURE__ */ jsx(ListboxOptions, { as: Fragment, anchor: { to: listboxOptionsAnchorTo }, modal: false, transition: true, children: /* @__PURE__ */ jsxs(
            ExperimentalLegacyMenu,
            {
              className: `
                min-w-[var(--button-width)] transition outline-none [--anchor-gap:theme(spacing.1)] [--anchor-padding:theme(spacing.2)]
                data-[closed]:-translate-y-1
                data-[closed]:data-[anchor~=top]:translate-y-1
                data-[closed]:opacity-0
              `,
              children: [
                label ? /* @__PURE__ */ jsx(ExperimentalLegacyMenu.Heading, { children: label }) : null,
                children
              ]
            }
          ) })
        ]
      }
    ) });
  }
);
ExperimentalSelectChipRoot.displayName = "ExperimentalSelectChip";
const ExperimentalSelectChipOption = forwardRef(
  ({ value: passedValue, children, ...props }, forwardedRef) => {
    const { t } = useI18n();
    const { clearable, multiple } = useContext(ExperimentalSelectChipContext);
    const value = passedValue !== void 0 ? passedValue : children;
    return /* @__PURE__ */ jsx(ListboxOption, { ref: forwardedRef, as: Fragment, value, children: ({ focus, selected, selectedOption }) => selectedOption ? /* @__PURE__ */ jsx("span", { children }) : multiple ? /* @__PURE__ */ jsx(ExperimentalLegacyMenu.CheckboxItem, { focus, selected, ...props, children }) : /* @__PURE__ */ jsxs(ExperimentalLegacyMenu.Item, { focus, selected, ...props, children: [
      children,
      clearable && selected ? /* @__PURE__ */ jsxs("span", { className: "sr-only", children: [
        "(",
        t("components.selectChip.clickToUnselect"),
        ")"
      ] }) : null
    ] }) });
  }
);
ExperimentalSelectChipOption.displayName = "ExperimentalSelectChip.Option";
function areValueIdsIdentical(valueId1, valueId2) {
  if (Array.isArray(valueId1) && Array.isArray(valueId2)) {
    return areArraysIdentical(valueId1, valueId2);
  }
  return valueId1 === valueId2;
}
function areArraysIdentical(array1, array2) {
  if (array1.length !== array2.length) return false;
  const set1 = new Set(array1);
  const set2 = new Set(array2);
  if (set1.size !== set2.size) return false;
  for (const item of set1) {
    if (!set2.has(item)) {
      return false;
    }
  }
  return true;
}
export {
  ExperimentalSelectChipOption,
  ExperimentalSelectChipRoot
};
