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/user-action/select/index.ts
var select_exports = {};
__export(select_exports, {
  MultiSelect: () => MultiSelect,
  MultiSelectChipDisplay: () => MultiSelectChipDisplay,
  MultiSelectChipDisplayUncontrolled: () => MultiSelectChipDisplayUncontrolled,
  MultiSelectUncontrolled: () => MultiSelectUncontrolled,
  Select: () => Select,
  SelectButton: () => SelectButton,
  SelectChipDisplay: () => SelectChipDisplay,
  SelectContent: () => SelectContent,
  SelectOption: () => SelectOption,
  SelectRoot: () => SelectRoot,
  SelectUncontrolled: () => SelectUncontrolled
});
module.exports = __toCommonJS(select_exports);

// src/components/user-action/select/Select.tsx
var import_react9 = require("react");
var import_clsx4 = __toESM(require("clsx"), 1);

// src/i18n/LocaleProvider.tsx
var import_react2 = require("react");

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

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

// src/i18n/translations.ts
var import_internationalization = require("@helpwave/internationalization");
var hightideTranslationLocales = ["de-DE", "en-US"];
var hightideTranslation = {
  "de-DE": {
    "add": `Hinzuf\xFCgen`,
    "age": `Alter`,
    "all": `Alle`,
    "apply": `Anwenden`,
    "back": `Zur\xFCck`,
    "cancel": `Abbrechen`,
    "carousel": `Karussell`,
    "change": `\xC4ndern`,
    "chooseLanguage": `W\xE4hle deine bevorzugte Sprache`,
    "chooseSlide": `W\xE4hle die angezeigte Slide aus`,
    "chooseTheme": `W\xE4hle dein bevorzugtes Farbschema.`,
    "clear": `L\xF6schen`,
    "click": `Klicken`,
    "clickToCopy": `Zum kopieren klicken`,
    "clickToSelect": `Zum Ausw\xE4hlen dr\xFCcken`,
    "close": `Schlie\xDFen`,
    "confirm": `Best\xE4tigen`,
    "copied": `Kopiert`,
    "copy": `Kopieren`,
    "create": `Erstellen`,
    "decline": `Ablehnen`,
    "delete": `L\xF6schen`,
    "discard": `Verwerfen`,
    "discardChanges": `\xC4nderungen Verwerfen`,
    "done": `Fertig`,
    "edit": `Bearbeiten`,
    "endDate": `Ende`,
    "enterText": `Text hier eingeben`,
    "entryDate": `Eintragsdatum`,
    "error": `Fehler`,
    "errorOccurred": `Ein Fehler ist aufgetreten`,
    "exit": `Beenden`,
    "fieldRequiredError": `Dieses Feld ist erforderlich.`,
    "filter": `Filter`,
    "gender": ({ gender }) => {
      return import_internationalization.TranslationGen.resolveSelect(gender, {
        "male": `M\xE4nnlich`,
        "female": `Weiblich`,
        "other": `Divers`
      });
    },
    "goodToSeeYou": `Sch\xF6n dich zu sehen`,
    "identifier": `Identifikator`,
    "invalidEmail": `Die E-Mail ist ung\xFCltig.`,
    "invalidEmailError": `Bitte geben Sie eine g\xFCltige E-Mail-Adresse ein.`,
    "language": `Sprache`,
    "less": `Weniger`,
    "loading": `L\xE4dt`,
    "locale": `Locale`,
    "max": `Max`,
    "maxLengthError": `Maximale L\xE4nge \xFCberschritten.`,
    "min": `Min`,
    "minLengthError": `Mindestl\xE4nge nicht erreicht.`,
    "more": `Mehr`,
    "name": `Name`,
    "next": `Weiter`,
    "no": `Nein`,
    "none": `Nichts`,
    "notEmpty": `Das Feld darf nicht leer sein.`,
    "nothingFound": `Nichts gefunden`,
    "of": `von`,
    "optional": `Optional`,
    "outOfRangeNumber": ({ min, max }) => {
      return `Der Wert muss zwischen ${min} und ${max} liegen.`;
    },
    "outOfRangeSelectionItems": ({ min, max }) => {
      return `Es m\xFCssen zwischen ${min} und ${max} Elemente ausgew\xE4hlt werden.`;
    },
    "outOfRangeString": ({ min, max }) => {
      return `Der Wert muss zwischen ${min} und ${max} Zeichen lang sein.`;
    },
    "pleaseWait": `Bitte warten...`,
    "previous": `Vorherige`,
    "remove": `Entfernen`,
    "required": `Erforderlich`,
    "reset": `Zur\xFCcksetzen`,
    "save": `Speichern`,
    "saved": `Gespeichert`,
    "search": `Suche`,
    "select": `Select`,
    "selectOption": `Option ausw\xE4hlen`,
    "show": `Anzeigen`,
    "showLess": `Weniger anzeigen`,
    "showMore": `Mehr anzeigen`,
    "showSlide": ({ index }) => {
      return `Zeige Slide ${index}`;
    },
    "slide": `Slide`,
    "slideNavigation": `Slide Navigation`,
    "slideOf": ({ index, length }) => {
      return `Slide ${index} von ${length} slides`;
    },
    "startDate": `Start`,
    "street": `Stra\xDFe`,
    "submit": `Abschicken`,
    "success": `Erfolg`,
    "text": `Text`,
    "themeMode": ({ theme }) => {
      return import_internationalization.TranslationGen.resolveSelect(theme, {
        "dark": `Dunkel`,
        "light": `Hell`,
        "system": `System`
      });
    },
    "themes": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Farbschema`,
        "other": `Farbschemas`
      });
    },
    "time.ago": `vor`,
    "time.agoDays": ({ days }) => {
      return `var ${days} Tagen`;
    },
    "time.april": `April`,
    "time.august": `August`,
    "time.century": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Jahrhundert`,
        "other": `Jahrhunderte`
      });
    },
    "time.day": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Tag`,
        "other": `Tage`
      });
    },
    "time.decade": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Jahrzehnt`,
        "other": `Jahrzehnte`
      });
    },
    "time.december": `December`,
    "time.february": `Febuar`,
    "time.hour": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Stunde`,
        "other": `Stunden`
      });
    },
    "time.in": `in`,
    "time.inDays": ({ days }) => {
      return `in ${days} Tagen`;
    },
    "time.january": `Januar`,
    "time.july": `Juli`,
    "time.june": `Juni`,
    "time.march": `M\xE4rz`,
    "time.may": `Mai`,
    "time.microsecond": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Mikrosekunde`,
        "other": `Mikrosekunden`
      });
    },
    "time.millisecond": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Millisekunde`,
        "other": `Millisekunden`
      });
    },
    "time.minute": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Minute`,
        "other": `Minuten`
      });
    },
    "time.month": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Monat`,
        "other": `Monate`
      });
    },
    "time.monthName": ({ month }) => {
      return import_internationalization.TranslationGen.resolveSelect(month, {
        "january": `Januar`,
        "february": `Februar`,
        "march": `M\xE4rz`,
        "april": `April`,
        "may": `Mai`,
        "june": `Juni`,
        "july": `Juli`,
        "august": `August`,
        "september": `September`,
        "october": `Oktober`,
        "november": `November`,
        "december": `Dezember`,
        "other": `Unbekannter Monat`
      });
    },
    "time.nanosecond": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Nanosekunde`,
        "other": `Nanosekunden`
      });
    },
    "time.november": `November`,
    "time.october": `October`,
    "time.second": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Sekunde`,
        "other": `Sekunden`
      });
    },
    "time.september": `September`,
    "time.today": `Heute`,
    "time.tomorrow": `Morgen`,
    "time.year": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Jahr`,
        "other": `Jahre`
      });
    },
    "time.yesterday": `Gestern`,
    "tooFewSelectionItems": ({ min }) => {
      return `Es m\xFCssen mindestens ${min} Elemente ausgew\xE4hlt werden.`;
    },
    "tooLong": ({ max }) => {
      return `Der Wert darf h\xF6chstens ${max} Zeichen enthalten.`;
    },
    "tooManySelectionItems": ({ max }) => {
      return `Es m\xFCssen maximal ${max} Elemente ausgew\xE4hlt werden.`;
    },
    "tooShort": ({ min }) => {
      return `Der Wert muss mindestens ${min} Zeichen enthalten.`;
    },
    "unsavedChanges": `Ungespeicherte \xC4nderungen`,
    "unsavedChangesSaveQuestion": `M\xF6chtest du die \xC4nderungen speichern?`,
    "update": `Update`,
    "value": `Wert`,
    "welcome": `Willkommen`,
    "yes": `Ja`
  },
  "en-US": {
    "add": `Add`,
    "age": `Age`,
    "all": `All`,
    "apply": `Apply`,
    "back": `Back`,
    "cancel": `Cancel`,
    "carousel": `Carousel`,
    "change": `Change`,
    "chooseLanguage": `Choose your language`,
    "chooseSlide": `Choose slide to display`,
    "chooseTheme": `Choose your preferred color theme.`,
    "clear": `Clear`,
    "click": `Click`,
    "clickToCopy": `Click to Copy`,
    "clickToSelect": `Click to select`,
    "close": `Close`,
    "confirm": `Confirm`,
    "copied": `Copied`,
    "copy": `Copy`,
    "create": `Create`,
    "decline": `Decline`,
    "delete": `Delete`,
    "discard": `Discard`,
    "discardChanges": `Discard Changes`,
    "done": `Done`,
    "edit": `Edit`,
    "endDate": `End`,
    "enterText": `Enter text here`,
    "entryDate": `Entry Date`,
    "error": `Error`,
    "errorOccurred": `An error occurred`,
    "exit": `Exit`,
    "fieldRequiredError": `This field is required.`,
    "filter": `Filter`,
    "gender": ({ gender }) => {
      return import_internationalization.TranslationGen.resolveSelect(gender, {
        "male": `Male`,
        "female": `Female`,
        "other": `Other`
      });
    },
    "goodToSeeYou": `Good to see you`,
    "identifier": `Identifier`,
    "invalidEmail": `The email is not valid.`,
    "invalidEmailError": `Please enter a valid email address.`,
    "language": `Language`,
    "less": `Less`,
    "loading": `Loading`,
    "locale": `Locale`,
    "max": `Max`,
    "maxLengthError": `Maximum length exceeded.`,
    "min": `Min`,
    "minLengthError": `Minimum length not met.`,
    "more": `More`,
    "name": `Name`,
    "next": `Next`,
    "no": `No`,
    "none": `None`,
    "notEmpty": `The field cannot be empty.`,
    "nothingFound": `Nothing found`,
    "of": `of`,
    "optional": `Optional`,
    "outOfRangeNumber": ({ min, max }) => {
      return `The value must be between ${min} and ${max}.`;
    },
    "outOfRangeSelectionItems": ({ min, max }) => {
      return `Between ${min} and ${max} items must be selected.`;
    },
    "outOfRangeString": ({ min, max }) => {
      return `The value needs to have between ${min} and ${max} characters.`;
    },
    "pleaseWait": `Please wait...`,
    "previous": `Previous`,
    "remove": `Remove`,
    "required": `Required`,
    "reset": `Reset`,
    "save": `Save`,
    "saved": `Saved`,
    "search": `Search`,
    "select": `Select`,
    "selectOption": `Select an option`,
    "show": `Show`,
    "showLess": `Show less`,
    "showMore": `Show more`,
    "showSlide": ({ index }) => {
      return `Show Slide ${index}`;
    },
    "slide": `Slide`,
    "slideNavigation": `Slide navigation`,
    "slideOf": ({ index, length }) => {
      return `Slide ${index} of ${length} slides`;
    },
    "startDate": `Start`,
    "street": `Street`,
    "submit": `Submit`,
    "success": `Success`,
    "text": `Text`,
    "themeMode": ({ theme }) => {
      return import_internationalization.TranslationGen.resolveSelect(theme, {
        "dark": `Dark`,
        "light": `Light`,
        "system": `System`
      });
    },
    "themes": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Theme`,
        "other": `Themes`
      });
    },
    "time.ago": `ago`,
    "time.agoDays": ({ days }) => {
      return `days ${days} ago`;
    },
    "time.april": `April`,
    "time.august": `August`,
    "time.century": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Century`,
        "other": `Centuries`
      });
    },
    "time.day": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Day`,
        "other": `Days`
      });
    },
    "time.decade": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Decade`,
        "other": `Decades`
      });
    },
    "time.december": `December`,
    "time.february": `Febuary`,
    "time.hour": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Hour`,
        "other": `Hours`
      });
    },
    "time.in": `in`,
    "time.inDays": ({ days }) => {
      return `in ${days} days`;
    },
    "time.january": `January`,
    "time.july": `July`,
    "time.june": `June`,
    "time.march": `March`,
    "time.may": `May`,
    "time.microsecond": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Microsecond`,
        "other": `Microseconds`
      });
    },
    "time.millisecond": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Millisecond`,
        "other": `Milliseconds`
      });
    },
    "time.minute": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Minute`,
        "other": `Minutes`
      });
    },
    "time.month": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Month`,
        "other": `Months`
      });
    },
    "time.monthName": ({ month }) => {
      return import_internationalization.TranslationGen.resolveSelect(month, {
        "january": `January`,
        "february": `February`,
        "march": `March`,
        "april": `April`,
        "may": `May`,
        "june": `June`,
        "july": `July`,
        "august": `August`,
        "september": `September`,
        "october": `October`,
        "november": `November`,
        "december": `December`,
        "other": `Unknown Month`
      });
    },
    "time.nanosecond": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Nanosecond`,
        "other": `Nanoseconds`
      });
    },
    "time.november": `November`,
    "time.october": `October`,
    "time.second": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Second`,
        "other": `Seconds`
      });
    },
    "time.september": `September`,
    "time.today": `Today`,
    "time.tomorrow": `Tomorrow`,
    "time.year": ({ count }) => {
      return import_internationalization.TranslationGen.resolveSelect(count, {
        "=1": `Year`,
        "other": `Years`
      });
    },
    "time.yesterday": `Yesterday`,
    "tooFewSelectionItems": ({ min }) => {
      return `Select at least ${min} items.`;
    },
    "tooLong": ({ max }) => {
      return `The value requires less than ${max} characters.`;
    },
    "tooManySelectionItems": ({ max }) => {
      return `Select at most ${max} items.`;
    },
    "tooShort": ({ min }) => {
      return `The value requires at least ${min} characters.`;
    },
    "unsavedChanges": `Unsaved Changes`,
    "unsavedChangesSaveQuestion": `Do you want to save your changes?`,
    "update": `Update`,
    "value": `Value`,
    "welcome": `Welcome`,
    "yes": `Yes`
  }
};

// src/i18n/util.ts
var localsNames = {
  "en-US": "English (US)",
  "de-DE": "Deutsch"
};
var DEFAULT_LOCALE = "en-US";
function localeToLanguage(locale) {
  return locale.split("-")[0];
}
var LocalizationUtil = {
  locals: hightideTranslationLocales,
  localToLanguage: localeToLanguage,
  DEFAULT_LOCALE,
  languagesLocalNames: localsNames
};

// src/i18n/LocaleProvider.tsx
var import_jsx_runtime = require("react/jsx-runtime");
var LocaleContext = (0, import_react2.createContext)({
  locale: LocalizationUtil.DEFAULT_LOCALE,
  setLocale: (v) => v
});
var useLocale = () => {
  const context = (0, import_react2.useContext)(LocaleContext);
  if (!context) {
    throw new Error("useLocale must be used within LocaleContext. Try adding a LocaleProvider around your app.");
  }
  return context;
};

// src/i18n/useHightideTranslation.ts
var import_internationalization2 = require("@helpwave/internationalization");

// src/utils/array.ts
var moveItems = (list, move = 0) => {
  const result = [];
  let start = move;
  if (start < 0) {
    start = list.length - move;
  }
  start = start % list.length;
  for (let i = 0; i < list.length; i++) {
    result[i] = list[(i + start) % list.length];
  }
  return result;
};
function resolveSingleOrArray(value) {
  if (Array.isArray(value)) {
    return value;
  } else if (value) {
    return [value];
  }
  return [];
}
var ArrayUtil = {
  unique: (list) => {
    const seen = /* @__PURE__ */ new Set();
    return list.filter((item) => {
      if (seen.has(item)) {
        return false;
      }
      seen.add(item);
      return true;
    });
  },
  difference: (list, removeList) => {
    const remove = new Set(removeList);
    return list.filter((item) => !remove.has(item));
  },
  moveItems,
  resolveSingleOrArray
};

// src/i18n/useHightideTranslation.ts
function useHightideTranslation(extensions, overwrites) {
  const { locale: inferredLocale } = useLocale();
  const locale = overwrites?.locale ?? inferredLocale;
  const translationExtensions = ArrayUtil.resolveSingleOrArray(extensions);
  return (0, import_internationalization2.combineTranslation)([
    ...translationExtensions,
    hightideTranslation
  ], locale);
}

// src/components/layout/Expandable.tsx
var import_react4 = require("react");
var import_lucide_react = require("lucide-react");
var import_clsx = __toESM(require("clsx"), 1);

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

// src/components/layout/Expandable.tsx
var import_jsx_runtime2 = require("react/jsx-runtime");
var ExpansionIcon = ({ isExpanded, className }) => {
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
    import_lucide_react.ChevronDown,
    {
      "aria-hidden": true,
      className: (0, import_clsx.default)(
        "min-w-6 w-6 min-h-6 h-6 transition-transform motion-safe:duration-200 motion-reduce:duration-0 ease-in-out",
        { "rotate-180": isExpanded },
        className
      )
    }
  );
};
var Expandable = (0, import_react4.forwardRef)(function Expandable2({
  children,
  id: providedId,
  label,
  icon,
  isExpanded = false,
  onChange,
  clickOnlyOnHeader = true,
  disabled = false,
  className,
  headerClassName,
  contentClassName,
  contentExpandedClassName
}, ref) {
  const defaultIcon = (0, import_react4.useCallback)((expanded) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ExpansionIcon, { isExpanded: expanded }), []);
  icon ??= defaultIcon;
  const generatedId = (0, import_react4.useId)();
  const id = providedId ?? generatedId;
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
    "div",
    {
      ref,
      onClick: () => !clickOnlyOnHeader && !disabled && onChange?.(!isExpanded),
      className: (0, import_clsx.default)(
        "flex-col-0 bg-surface text-on-surface group rounded-lg shadow-sm",
        { "cursor-pointer": !clickOnlyOnHeader && !disabled },
        className
      ),
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
          "button",
          {
            onClick: () => clickOnlyOnHeader && !disabled && onChange?.(!isExpanded),
            className: (0, import_clsx.default)(
              "flex-row-2 py-2 px-4 rounded-lg justify-between items-center bg-surface text-on-surface select-none",
              {
                "group-hover:brightness-97": !isExpanded,
                "hover:brightness-97": isExpanded && !disabled,
                "cursor-pointer": clickOnlyOnHeader && !disabled
              },
              headerClassName
            ),
            "aria-expanded": isExpanded,
            "aria-controls": `${id}-content`,
            "aria-disabled": disabled ?? void 0,
            children: [
              label,
              icon(isExpanded)
            ]
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
          "div",
          {
            id: `${id}-content`,
            className: (0, import_clsx.default)(
              "flex-col-2 px-4 transition-all duration-300 ease-in-out",
              {
                [(0, import_clsx.default)("max-h-96 opacity-100 pb-2 overflow-y-auto", contentExpandedClassName)]: isExpanded,
                "max-h-0 opacity-0 overflow-hidden": !isExpanded
              },
              contentClassName
            ),
            role: "region",
            children
          }
        )
      ]
    }
  );
});
var ExpandableUncontrolled = (0, import_react4.forwardRef)(function ExpandableUncontrolled2({
  isExpanded,
  onChange,
  ...props
}, ref) {
  const [usedIsExpanded, setUsedIsExpanded] = useOverwritableState(isExpanded, onChange);
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
    Expandable,
    {
      ...props,
      ref,
      isExpanded: usedIsExpanded,
      onChange: setUsedIsExpanded
    }
  );
});

// src/hooks/focus/useFocusTrap.ts
var import_react6 = require("react");

// src/hooks/focus/useIsMounted.ts
var import_react5 = require("react");
var isClient = typeof window !== "undefined" && typeof document !== "undefined";
var useIsomorphicEffect = isClient ? import_react5.useLayoutEffect : import_react5.useEffect;
var useIsMounted = () => {
  const [isMounted, setIsMounted] = (0, import_react5.useState)(false);
  useIsomorphicEffect(() => {
    setIsMounted(true);
    return () => {
      setIsMounted(false);
    };
  }, []);
  return isMounted;
};

// src/hooks/focus/useFocusTrap.ts
var createFocusGuard = () => {
  const div = document.createElement("div");
  Object.assign(div.style, {
    opacity: "0",
    outline: "none",
    boxShadow: "none",
    position: "fixed",
    pointerEvents: "none",
    touchAction: "none"
  });
  div.tabIndex = 0;
  div.setAttribute("data-hw-focus-guard", "");
  document.body.appendChild(div);
  return div;
};
function getContainedFocusableElements(element) {
  return element?.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
}
var FocusTrapService = class {
  constructor() {
    // The last entry is always the active one
    this.listeners = [];
    this.onFocusIn = (event) => {
      const active = this.getActive();
      if (!active || !active.container.current) return;
      const { container } = active;
      if (!container.current.contains(event.target)) {
        this.focusElement();
      }
    };
  }
  getActive() {
    if (this.listeners.length === 0) return void 0;
    return this.listeners[this.listeners.length - 1];
  }
  focusElement() {
    const active = this.getActive();
    if (!active) return;
    const { container, initialFocusElement } = active;
    const containerElement = container.current;
    if (initialFocusElement?.current) {
      initialFocusElement.current.focus();
    } else {
      const elements = getContainedFocusableElements(containerElement);
      if (elements && elements.length > 0) {
        const first = elements.item(0);
        first.focus();
      } else {
        containerElement.focus();
      }
    }
  }
  removeGuards() {
    document.querySelectorAll("[data-hw-focus-guard]").forEach((node) => node.remove());
  }
  addGuards() {
    document.body.insertAdjacentElement("afterbegin", createFocusGuard());
    document.body.insertAdjacentElement("beforeend", createFocusGuard());
  }
  activate() {
    document.addEventListener("focusin", this.onFocusIn);
    this.addGuards();
  }
  deactivate() {
    document.removeEventListener("focusin", this.onFocusIn);
    this.removeGuards();
  }
  register(listener) {
    this.listeners.push(listener);
    if (this.listeners.length === 1) {
      this.activate();
    }
    const active = listener;
    this.listeners.forEach((listener2) => {
      const { focus, pause } = listener2;
      if (listener2 === active) {
        focus();
      } else {
        pause();
      }
    });
  }
  unregister(id) {
    const index = this.listeners.findIndex((trap) => trap.id === id);
    if (index !== -1) {
      const isActive = index === this.listeners.length - 1;
      const listener = this.listeners[index];
      this.listeners = this.listeners.filter((listener2) => listener2.id !== id);
      if (isActive) {
        this.deactivate();
        listener.focusLast();
        const active = this.getActive();
        this.listeners.forEach((listener2) => {
          const { pause, unpause } = listener2;
          if (listener2 === active) {
            unpause();
          } else {
            pause();
          }
        });
        if (this.listeners.length > 0) {
          this.activate();
        }
      }
    } else {
      console.warn(`Unable to unregister id ${id}: not found`);
    }
  }
};
var service = new FocusTrapService();
var useFocusTrap = ({
  container,
  active = true,
  initialFocus,
  focusFirst = true
}) => {
  const lastFocusRef = (0, import_react6.useRef)(null);
  const [paused, setPaused] = (0, import_react6.useState)(false);
  const isMounted = useIsMounted();
  const id = (0, import_react6.useId)();
  const focusElement = (0, import_react6.useCallback)(() => {
    const containerElement = container.current;
    if (initialFocus?.current) {
      initialFocus.current.focus();
    } else {
      const elements = getContainedFocusableElements(containerElement);
      if (elements && elements.length > 0) {
        const first = elements.item(0);
        first.focus();
      } else {
        containerElement.focus();
      }
    }
  }, [container, initialFocus]);
  (0, import_react6.useEffect)(() => {
    if (active && isMounted) {
      let pause = function() {
        setPaused(true);
      }, unpause = function() {
        setPaused(false);
        if (!container.current.contains(document.activeElement)) {
          focusElement();
        }
      }, focus = function() {
        focusElement();
        setPaused(false);
      }, focusLast = function() {
        lastFocusRef.current?.focus();
      };
      if (!lastFocusRef.current) {
        lastFocusRef.current = document.activeElement;
      }
      service.register({ id, pause, focus, focusLast, unpause, container, initialFocusElement: initialFocus });
      return () => {
        service.unregister(id);
        lastFocusRef.current = void 0;
      };
    }
  }, [active, container, focusElement, id, initialFocus, isMounted]);
  (0, import_react6.useEffect)(() => {
    if (active && !paused && isMounted) {
      let onKeyDown = function(event) {
        const key = event.key;
        const elements = getContainedFocusableElements(containerElement);
        const active2 = document.activeElement;
        const index = [...elements].findIndex((value) => value === active2);
        if (index === -1 || event.altKey || event.ctrlKey || event.metaKey) {
          return;
        }
        if (key === "Tab") {
          const next = event.shiftKey ? -1 : 1;
          const nextIndex = (index + next + elements.length) % elements.length;
          const nextElement = elements[nextIndex];
          nextElement.focus();
          event.preventDefault();
        }
      };
      const containerElement = container.current;
      containerElement.addEventListener("keydown", onKeyDown);
      return () => {
        containerElement.removeEventListener("keydown", onKeyDown);
      };
    }
  }, [active, paused, isMounted, container, initialFocus, focusFirst, focusElement]);
};

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

// src/components/user-action/select/Select.tsx
var import_lucide_react2 = require("lucide-react");

// src/components/layout/Chip.tsx
var import_clsx2 = __toESM(require("clsx"), 1);
var import_jsx_runtime3 = require("react/jsx-runtime");
var Chip = ({
  children,
  trailingIcon,
  color = "default",
  size = "md",
  icon = false,
  variant = "normal",
  className = "",
  ...restProps
}) => {
  const colorMapping = {
    default: "text-tag-default-text bg-tag-default-background",
    dark: "text-tag-dark-text bg-tag-dark-background",
    red: "text-tag-red-text bg-tag-red-background",
    yellow: "text-tag-yellow-text bg-tag-yellow-background",
    green: "text-tag-green-text bg-tag-green-background",
    blue: "text-tag-blue-text bg-tag-blue-background",
    pink: "text-tag-pink-text bg-tag-pink-background",
    orange: "text-tag-orange-text bg-tag-orange-background"
  }[color];
  const colorMappingIcon = {
    default: "text-tag-default-icon",
    dark: "text-tag-dark-icon",
    red: "text-tag-red-icon",
    yellow: "text-tag-yellow-icon",
    green: "text-tag-green-icon",
    blue: "text-tag-blue-icon",
    pink: "text-tag-pink-icon",
    orange: "text-tag-orange-icon"
  }[color];
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
    "div",
    {
      ...restProps,
      className: (0, import_clsx2.default)(
        `flex-row-0 w-fit font-semibold`,
        colorMapping,
        !icon ? {
          "px-1 py-0.5": size === "sm",
          "px-2 py-1": size === "md",
          "px-4 py-2": size === "lg"
        } : {
          "p-0.5": size === "sm",
          "p-1": size === "md",
          "p-2": size === "lg"
        },
        {
          "rounded-md": variant === "normal",
          "rounded-full": variant === "fullyRounded"
        },
        className
      ),
      children: [
        children,
        trailingIcon && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: colorMappingIcon, children: trailingIcon })
      ]
    }
  );
};

// src/components/user-action/Button.tsx
var import_react7 = require("react");
var import_clsx3 = __toESM(require("clsx"), 1);
var import_jsx_runtime4 = require("react/jsx-runtime");
var ButtonColorUtil = {
  solid: ["primary", "secondary", "tertiary", "positive", "warning", "negative", "neutral"],
  text: ["primary", "negative", "neutral"],
  outline: ["primary"]
};
var IconButtonUtil = {
  icon: [...ButtonColorUtil.solid, "transparent"]
};
var paddingMapping = {
  none: "",
  small: "btn-sm",
  medium: "btn-md",
  large: "btn-lg"
};
var iconPaddingMapping = {
  none: "",
  tiny: "icon-btn-xs",
  small: "icon-btn-sm",
  medium: "icon-btn-md",
  large: "icon-btn-lg"
};
var ButtonUtil = {
  paddingMapping,
  iconPaddingMapping
};
var SolidButton = (0, import_react7.forwardRef)(function SolidButton2({
  children,
  color = "primary",
  size = "medium",
  startIcon,
  endIcon,
  onClick,
  className,
  ...restProps
}, ref) {
  const colorClasses = {
    primary: "not-disabled:bg-button-solid-primary-background not-disabled:text-button-solid-primary-text",
    secondary: "not-disabled:bg-button-solid-secondary-background not-disabled:text-button-solid-secondary-text",
    tertiary: "not-disabled:bg-button-solid-tertiary-background not-disabled:text-button-solid-tertiary-text",
    positive: "not-disabled:bg-button-solid-positive-background not-disabled:text-button-solid-positive-text",
    warning: "not-disabled:bg-button-solid-warning-background not-disabled:text-button-solid-warning-text",
    negative: "not-disabled:bg-button-solid-negative-background not-disabled:text-button-solid-negative-text",
    neutral: "not-disabled:bg-button-solid-neutral-background not-disabled:text-button-solid-neutral-text"
  }[color];
  const iconColorClasses = {
    primary: "not-group-disabled:text-button-solid-primary-icon",
    secondary: "not-group-disabled:text-button-solid-secondary-icon",
    tertiary: "not-group-disabled:text-button-solid-tertiary-icon",
    positive: "not-group-disabled:text-button-solid-positive-icon",
    warning: "not-group-disabled:text-button-solid-warning-icon",
    negative: "not-group-disabled:text-button-solid-negative-icon",
    neutral: "not-group-disabled:text-button-solid-neutral-icon"
  }[color];
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
    "button",
    {
      ref,
      onClick,
      className: (0, import_clsx3.default)(
        "group font-semibold",
        colorClasses,
        "not-disabled:hover:brightness-90",
        "disabled:text-disabled disabled:bg-disabled-background",
        ButtonUtil.paddingMapping[size],
        className
      ),
      ...restProps,
      children: [
        startIcon && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "span",
          {
            className: (0, import_clsx3.default)(
              iconColorClasses,
              "group-disabled:text-disabled-icon"
            ),
            children: startIcon
          }
        ),
        children,
        endIcon && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "span",
          {
            className: (0, import_clsx3.default)(
              iconColorClasses,
              "group-disabled:text-disabled-icon"
            ),
            children: endIcon
          }
        )
      ]
    }
  );
});
var TextButton = ({
  children,
  color = "neutral",
  size = "medium",
  startIcon,
  endIcon,
  onClick,
  coloredHoverBackground = true,
  className,
  ...restProps
}) => {
  const colorClasses = {
    primary: "not-disabled:bg-transparent not-disabled:text-button-text-primary-text not-disabled:focus-visible:outline-button-text-primary-text",
    negative: "not-disabled:bg-transparent not-disabled:text-button-text-negative-text not-disabled:focus-visible:outline-button-text-negative-text",
    neutral: "not-disabled:bg-transparent not-disabled:text-button-text-neutral-text not-disabled:focus-visible:outline-button-text-neutral-text"
  }[color];
  const backgroundColor = {
    primary: "not-disabled:hover:bg-button-text-primary-text/20 not-disabled:focus-visible:bg-button-text-primary-text/20",
    negative: "not-disabled:hover:bg-button-text-negative-text/20 not-disabled:focus-visible:bg-button-text-negative-text/20",
    neutral: "not-disabled:hover:bg-button-text-neutral-text/20 not-disabled:focus-visible:bg-button-text-neutral-text/20"
  }[color];
  const iconColorClasses = {
    primary: "not-group-disabled:text-button-text-primary-icon",
    negative: "not-group-disabled:text-button-text-negative-icon",
    neutral: "not-group-disabled:text-button-text-neutral-icon"
  }[color];
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
    "button",
    {
      onClick,
      className: (0, import_clsx3.default)(
        "group font-semibold",
        "disabled:text-disabled",
        colorClasses,
        {
          [backgroundColor]: coloredHoverBackground,
          "not-disabled:hover:bg-button-text-hover-background": !coloredHoverBackground
        },
        ButtonUtil.paddingMapping[size],
        className
      ),
      ...restProps,
      children: [
        startIcon && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "span",
          {
            className: (0, import_clsx3.default)(
              iconColorClasses,
              "group-disabled:text-disabled-icon"
            ),
            children: startIcon
          }
        ),
        children,
        endIcon && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "span",
          {
            className: (0, import_clsx3.default)(
              iconColorClasses,
              "group-disabled:text-disabled-icon"
            ),
            children: endIcon
          }
        )
      ]
    }
  );
};
var IconButton = (0, import_react7.forwardRef)(function IconButton2({
  children,
  color = "primary",
  size = "medium",
  className,
  ...restProps
}, ref) {
  const colorClasses = {
    primary: "not-disabled:bg-button-solid-primary-background not-disabled:text-button-solid-primary-text",
    secondary: "not-disabled:bg-button-solid-secondary-background not-disabled:text-button-solid-secondary-text",
    tertiary: "not-disabled:bg-button-solid-tertiary-background not-disabled:text-button-solid-tertiary-text",
    positive: "not-disabled:bg-button-solid-positive-background not-disabled:text-button-solid-positive-text",
    warning: "not-disabled:bg-button-solid-warning-background not-disabled:text-button-solid-warning-text",
    negative: "not-disabled:bg-button-solid-negative-background not-disabled:text-button-solid-negative-text",
    neutral: "not-disabled:bg-button-solid-neutral-background not-disabled:text-button-solid-neutral-text",
    transparent: "not-disabled:bg-transparent"
  }[color];
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
    "button",
    {
      ref,
      className: (0, import_clsx3.default)(
        colorClasses,
        "not-disabled:hover:brightness-90",
        "disabled:text-disabled",
        {
          "disabled:bg-disabled-background": color !== "transparent",
          "disabled:opacity-70": color === "transparent",
          "not-disabled:hover:bg-button-text-hover-background": color === "transparent"
        },
        ButtonUtil.iconPaddingMapping[size],
        className
      ),
      ...restProps,
      children
    }
  );
});

// src/hooks/useFloatingElement.ts
var import_react8 = require("react");

// src/utils/math.ts
var clamp = (value, range = [0, 1]) => {
  const [min, max] = range;
  return Math.min(Math.max(value, min), max);
};

// src/hooks/useFloatingElement.ts
function calculatePosition({
  windowRect,
  containerRect,
  anchorRect,
  options
}) {
  const { verticalAlignment, horizontalAlignment, gap, screenPadding } = options;
  const windowWidth = windowRect.width;
  const windowHeight = windowRect.height;
  const maxWidth = windowWidth - 2 * screenPadding;
  const maxHeight = windowHeight - 2 * screenPadding;
  const width = Math.min(containerRect.width, maxWidth);
  const height = Math.min(containerRect.height, maxHeight);
  const leftSuggestion = {
    beforeStart: anchorRect.left - width - gap,
    afterStart: anchorRect.left,
    center: anchorRect.left + anchorRect.width / 2 - width / 2,
    beforeEnd: anchorRect.right - width,
    afterEnd: anchorRect.right + gap
  }[horizontalAlignment];
  const topSuggestion = {
    beforeStart: anchorRect.top - height - gap,
    afterStart: anchorRect.top,
    center: anchorRect.top + anchorRect.height / 2 - height / 2,
    beforeEnd: anchorRect.bottom - height,
    afterEnd: anchorRect.bottom + gap
  }[verticalAlignment];
  const left = clamp(leftSuggestion, [
    screenPadding,
    windowWidth - screenPadding - width
  ]);
  const top = clamp(topSuggestion, [
    screenPadding,
    windowHeight - screenPadding - height
  ]);
  return {
    left,
    top,
    maxWidth,
    maxHeight
  };
}
function useFloatingElement({
  active = true,
  windowRef,
  anchorRef,
  containerRef,
  isPolling = false,
  pollingInterval = 100,
  verticalAlignment = "afterEnd",
  horizontalAlignment = "afterStart",
  screenPadding = 16,
  gap = 4
}) {
  const [style, setStyle] = (0, import_react8.useState)();
  const isMounted = useIsMounted();
  const calculate = (0, import_react8.useCallback)(() => {
    const containerRect = containerRef.current.getBoundingClientRect();
    const windowRect = windowRef?.current.getBoundingClientRect() ?? {
      top: 0,
      bottom: window.innerHeight,
      left: 0,
      right: window.innerWidth,
      width: window.innerWidth,
      height: window.innerHeight
    };
    const anchorElement = anchorRef?.current;
    if (anchorRef && !anchorElement) {
      console.warn("FloatingContainer anchor provided, but its value is undefined");
    }
    const anchorRect = anchorElement?.getBoundingClientRect() ?? windowRect;
    const calculateProps = {
      windowRect,
      anchorRect,
      containerRect,
      options: {
        horizontalAlignment,
        verticalAlignment,
        screenPadding,
        gap
      }
    };
    setStyle(calculatePosition(calculateProps));
  }, [anchorRef, containerRef, gap, horizontalAlignment, screenPadding, verticalAlignment, windowRef]);
  const height = containerRef.current?.getBoundingClientRect().height;
  const width = containerRef.current?.getBoundingClientRect().width;
  (0, import_react8.useEffect)(() => {
    if (active && isMounted) {
      calculate();
    } else {
      setStyle(void 0);
    }
  }, [calculate, active, isMounted, height, width]);
  (0, import_react8.useEffect)(() => {
    window.addEventListener("resize", calculate);
    let timeout;
    if (isPolling) {
      timeout = setInterval(calculate, pollingInterval);
    }
    return () => {
      window.removeEventListener("resize", calculate);
      if (timeout) {
        clearInterval(timeout);
      }
    };
  }, [calculate, isPolling, pollingInterval]);
  return style;
}

// src/components/user-action/select/Select.tsx
var import_react_dom = require("react-dom");
var import_jsx_runtime5 = require("react/jsx-runtime");
var defaultToggleOpenOptions = {
  highlightStartPositionBehavior: "first"
};
var SelectContext = (0, import_react9.createContext)(null);
function useSelectContext() {
  const ctx = (0, import_react9.useContext)(SelectContext);
  if (!ctx) {
    throw new Error("SelectContext must be used within a ListBoxPrimitive");
  }
  return ctx;
}
var SelectRoot = ({
  children,
  id,
  value,
  onValueChanged,
  values,
  onValuesChanged,
  isOpen = false,
  disabled = false,
  invalid = false,
  isMultiSelect = false,
  iconAppearance = "left"
}) => {
  const triggerRef = (0, import_react9.useRef)(null);
  const generatedId = (0, import_react9.useId)();
  const usedId = id ?? generatedId;
  const [internalState, setInternalState] = (0, import_react9.useState)({
    isOpen,
    options: []
  });
  const selectedValues = (0, import_react9.useMemo)(
    () => isMultiSelect ? values ?? [] : [value].filter(Boolean),
    [isMultiSelect, value, values]
  );
  const selectedOptions = (0, import_react9.useMemo)(
    () => selectedValues.map((value2) => internalState.options.find((option) => value2 === option.value)).filter(Boolean),
    [selectedValues, internalState.options]
  );
  const state = {
    ...internalState,
    id: usedId,
    disabled,
    invalid,
    value: selectedValues,
    selectedOptions
  };
  const config = {
    isMultiSelect,
    iconAppearance
  };
  const registerItem = (0, import_react9.useCallback)((item) => {
    setInternalState((prev) => {
      const updatedOptions = [...prev.options, item];
      updatedOptions.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;
      });
      return {
        ...prev,
        options: updatedOptions
      };
    });
  }, []);
  const unregisterItem = (0, import_react9.useCallback)((value2) => {
    setInternalState((prev) => {
      const updatedOptions = prev.options.filter((i) => i.value !== value2);
      return {
        ...prev,
        options: updatedOptions
      };
    });
  }, []);
  const toggleSelection = (value2, isSelected) => {
    if (disabled) {
      return;
    }
    const option = state.options.find((i) => i.value === value2);
    if (!option) {
      console.error(`SelectOption with value: ${value2} not found`);
      return;
    }
    let newValue;
    if (isMultiSelect) {
      const isSelectedBefore = state.value.includes(value2);
      const isSelectedAfter = isSelected ?? !isSelectedBefore;
      if (!isSelectedAfter) {
        newValue = state.value.filter((v) => v !== value2);
      } else {
        newValue = [...state.value, value2];
      }
    } else {
      newValue = [value2];
    }
    if (!isMultiSelect) {
      onValueChanged?.(newValue[0]);
    } else {
      onValuesChanged?.(newValue);
    }
    setInternalState((prevState) => ({
      ...prevState,
      highlightedValue: value2
    }));
  };
  const highlightItem = (value2) => {
    if (disabled) {
      return;
    }
    setInternalState((prevState) => ({
      ...prevState,
      highlightedValue: value2
    }));
  };
  const registerTrigger = (0, import_react9.useCallback)((ref) => {
    triggerRef.current = ref.current;
  }, []);
  const unregisterTrigger = (0, import_react9.useCallback)(() => {
    triggerRef.current = null;
  }, []);
  const toggleOpen = (isOpen2, toggleOpenOptions) => {
    const { highlightStartPositionBehavior } = { ...defaultToggleOpenOptions, ...toggleOpenOptions };
    let firstSelectedValue;
    let firstEnabledValue;
    for (let i = 0; i < state.options.length; i++) {
      const currentOption = state.options[highlightStartPositionBehavior === "first" ? i : state.options.length - i - 1];
      if (!currentOption.disabled) {
        if (!firstEnabledValue) {
          firstEnabledValue = currentOption.value;
        }
        if (selectedValues.includes(currentOption.value)) {
          firstSelectedValue = currentOption.value;
          break;
        }
      }
    }
    setInternalState((prevState) => ({
      ...prevState,
      isOpen: isOpen2 ?? !prevState.isOpen,
      highlightedValue: firstSelectedValue ?? firstEnabledValue
    }));
  };
  const moveHighlightedIndex = (delta) => {
    let highlightedIndex = state.options.findIndex((value2) => value2.value === internalState.highlightedValue);
    if (highlightedIndex === -1) {
      highlightedIndex = 0;
    }
    const optionLength = state.options.length;
    const startIndex = (highlightedIndex + delta % optionLength + optionLength) % optionLength;
    const isForward = delta >= 0;
    let highlightedValue = state.options[startIndex].value;
    for (let i = 0; i < state.options.length; i++) {
      const index = (startIndex + (isForward ? i : -i) + optionLength) % optionLength;
      if (!state.options[index].disabled) {
        highlightedValue = state.options[index].value;
        break;
      }
    }
    setInternalState((prevState) => ({
      ...prevState,
      highlightedValue
    }));
  };
  (0, import_react9.useEffect)(() => {
    if (!internalState.highlightedValue) return;
    const highlighted = internalState.options.find((value2) => value2.value === internalState.highlightedValue);
    if (highlighted) {
      highlighted.ref.current?.scrollIntoView({ behavior: "instant", block: "nearest" });
    } else {
      console.error(`SelectRoot: Could not find highlighted value (${internalState.highlightedValue})`);
    }
  }, [internalState.highlightedValue]);
  const contextValue = {
    state,
    config,
    item: {
      register: registerItem,
      unregister: unregisterItem,
      toggleSelection,
      highlightItem,
      moveHighlightedIndex
    },
    trigger: {
      ref: triggerRef,
      register: registerTrigger,
      unregister: unregisterTrigger,
      toggleOpen
    }
  };
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(SelectContext.Provider, { value: contextValue, children });
};
var SelectOption = (0, import_react9.forwardRef)(
  function SelectOption2({ children, value, disabled = false, iconAppearance, className, ...restProps }, ref) {
    const { state, config, item, trigger } = useSelectContext();
    const { register, unregister, toggleSelection, highlightItem } = item;
    const itemRef = (0, import_react9.useRef)(null);
    iconAppearance ??= config.iconAppearance;
    const label = children ?? value;
    (0, import_react9.useEffect)(() => {
      register({
        value,
        label,
        disabled,
        ref: itemRef
      });
      return () => unregister(value);
    }, [value, disabled, register, unregister, children, label]);
    const isHighlighted = state.highlightedValue === value;
    const isSelected = state.value.includes(value);
    return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
      "li",
      {
        ...restProps,
        ref: (node) => {
          itemRef.current = node;
          if (typeof ref === "function") ref(node);
          else if (ref) ref.current = node;
        },
        id: value,
        role: "option",
        "aria-disabled": disabled,
        "aria-selected": isSelected,
        "data-highlighted": isHighlighted ? "" : void 0,
        "data-selected": isSelected ? "" : void 0,
        "data-disabled": disabled ? "" : void 0,
        className: (0, import_clsx4.default)(
          "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: (event) => {
          if (!disabled) {
            toggleSelection(value);
            if (!config.isMultiSelect) {
              trigger.toggleOpen(false);
            }
            restProps.onClick?.(event);
          }
        },
        onMouseEnter: (event) => {
          if (!disabled) {
            highlightItem(value);
            restProps.onMouseEnter?.(event);
          }
        },
        children: [
          iconAppearance === "left" && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
            import_lucide_react2.CheckIcon,
            {
              className: (0, import_clsx4.default)("w-4 h-4", { "opacity-0": !isSelected || disabled }),
              "aria-hidden": true
            }
          ),
          label,
          iconAppearance === "right" && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
            import_lucide_react2.CheckIcon,
            {
              className: (0, import_clsx4.default)("w-4 h-4", { "opacity-0": !isSelected || disabled }),
              "aria-hidden": true
            }
          )
        ]
      }
    );
  }
);
var SelectButton = (0, import_react9.forwardRef)(function SelectButton2({ placeholder, selectedDisplay, ...props }, ref) {
  const translation = useHightideTranslation();
  const { state, trigger } = useSelectContext();
  const { register, unregister, toggleOpen } = trigger;
  const innerRef = (0, import_react9.useRef)(null);
  (0, import_react9.useImperativeHandle)(ref, () => innerRef.current);
  (0, import_react9.useEffect)(() => {
    register(innerRef);
    return () => unregister();
  }, [register, unregister]);
  const disabled = !!props?.disabled || !!state.disabled;
  const invalid = state.invalid;
  const hasValue = state.value.length > 0;
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
    "button",
    {
      ...props,
      ref: innerRef,
      id: state.id,
      disabled,
      onClick: (event) => {
        props.onClick?.(event);
        toggleOpen(!state.isOpen);
      },
      onKeyDown: (event) => {
        props.onKeyDown?.(event);
        switch (event.key) {
          case "ArrowDown":
            toggleOpen(true, { highlightStartPositionBehavior: "first" });
            event.preventDefault();
            event.stopPropagation();
            break;
          case "ArrowUp":
            toggleOpen(true, { highlightStartPositionBehavior: "last" });
            event.preventDefault();
            event.stopPropagation();
            break;
        }
      },
      className: (0, import_clsx4.default)(
        "flex-row-2 items-center justify-between rounded-md px-3 py-2",
        {
          "bg-input-background text-placeholder": !hasValue && !disabled && !invalid,
          "bg-input-background text-input-text": hasValue && !disabled && !invalid,
          "bg-negative/20": !disabled && invalid,
          "text-placeholder": !hasValue && !disabled,
          "text-negative": hasValue && !disabled && invalid,
          "bg-disabled-background text-disabled": disabled
        },
        props.className
      ),
      "data-placeholder": !hasValue ? "" : void 0,
      "data-disabled": disabled ? "" : void 0,
      "data-invalid": invalid ? "" : void 0,
      "aria-invalid": invalid,
      "aria-disabled": disabled,
      "aria-haspopup": "listbox",
      "aria-expanded": state.isOpen,
      "aria-controls": state.isOpen ? `${state.id}-listbox` : void 0,
      children: [
        hasValue ? selectedDisplay?.(state.value) ?? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("div", { className: (0, import_clsx4.default)("flex flex-wrap gap-x-1 gap-y-2"), children: state.selectedOptions.map(({ value, label }, index) => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { className: "flex-row-0", children: [
          label,
          index < state.value.length - 1 && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { children: "," })
        ] }, value)) }) : placeholder ?? translation("clickToSelect"),
        /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
          ExpansionIcon,
          {
            isExpanded: state.isOpen,
            className: (0, import_clsx4.default)({
              "text-input-text": !disabled && !invalid,
              "text-negative": !disabled && invalid,
              "text-disabled": disabled
            })
          }
        )
      ]
    }
  );
});
var SelectChipDisplay = (0, import_react9.forwardRef)(function SelectChipDisplay2({ ...props }, ref) {
  const { state, trigger, item } = useSelectContext();
  const { register, unregister, toggleOpen } = trigger;
  const innerRef = (0, import_react9.useRef)(null);
  (0, import_react9.useImperativeHandle)(ref, () => innerRef.current);
  (0, import_react9.useEffect)(() => {
    register(innerRef);
    return () => unregister();
  }, [register, unregister]);
  const disabled = !!props?.disabled || !!state.disabled;
  const invalid = state.invalid;
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
    "div",
    {
      ...props,
      ref: innerRef,
      className: (0, import_clsx4.default)(
        "flex flex-wrap flex-row gap-2 items-center bg-input-background text-input-text rounded-md px-2.5 py-2.5",
        props.className
      ),
      "data-disabled": disabled ? "" : void 0,
      "data-invalid": invalid ? "" : void 0,
      "aria-invalid": invalid,
      "aria-disabled": disabled,
      children: [
        state.selectedOptions.map(({ value, label }) => /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(Chip, { className: "gap-x-2", children: [
          label,
          /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
            TextButton,
            {
              onClick: () => {
                item.toggleSelection(value, false);
              },
              size: "none",
              color: "negative",
              className: "flex-row-0 items-center px-0.5 py-0.5 w-6 h-6 rounded",
              children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.XIcon, { className: "w-5 h-5" })
            }
          )
        ] }, value)),
        /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
          IconButton,
          {
            id: state.id,
            onClick: () => toggleOpen(),
            onKeyDown: (event) => {
              switch (event.key) {
                case "ArrowDown":
                  toggleOpen(true, { highlightStartPositionBehavior: "first" });
                  break;
                case "ArrowUp":
                  toggleOpen(true, { highlightStartPositionBehavior: "last" });
              }
            },
            size: "small",
            color: "neutral",
            "aria-invalid": invalid,
            "aria-disabled": disabled,
            "aria-haspopup": "listbox",
            "aria-expanded": state.isOpen,
            "aria-controls": state.isOpen ? `${state.id}-listbox` : void 0,
            children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_lucide_react2.Plus, {})
          }
        )
      ]
    }
  );
});
var SelectContent = (0, import_react9.forwardRef)(
  function SelectContent2({
    alignment,
    orientation = "vertical",
    containerClassName,
    ...props
  }, ref) {
    const innerRef = (0, import_react9.useRef)(null);
    (0, import_react9.useImperativeHandle)(ref, () => innerRef.current);
    const { trigger, state, config, item } = useSelectContext();
    const position = useFloatingElement({
      active: state.isOpen,
      anchorRef: trigger.ref,
      containerRef: innerRef,
      ...alignment
    });
    useFocusTrap({
      container: innerRef,
      active: state.isOpen && !!position
    });
    return (0, import_react_dom.createPortal)(
      /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
        "div",
        {
          id: `select-container-${state.id}`,
          className: (0, import_clsx4.default)("fixed inset-0 w-screen h-screen", containerClassName),
          hidden: !state.isOpen,
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
              "div",
              {
                id: `select-background-${state.id}`,
                onClick: () => trigger.toggleOpen(false),
                className: (0, import_clsx4.default)("fixed inset-0 w-screen h-screen")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
              "ul",
              {
                ...props,
                id: `${state.id}-listbox`,
                ref: innerRef,
                onKeyDown: (event) => {
                  switch (event.key) {
                    case "Escape":
                      trigger.toggleOpen(false);
                      event.preventDefault();
                      event.stopPropagation();
                      break;
                    case match(orientation, {
                      vertical: "ArrowDown",
                      horizontal: "ArrowUp"
                    }):
                      item.moveHighlightedIndex(1);
                      event.preventDefault();
                      break;
                    case match(orientation, {
                      vertical: "ArrowUp",
                      horizontal: "ArrowDown"
                    }):
                      item.moveHighlightedIndex(-1);
                      event.preventDefault();
                      break;
                    case "Home":
                      event.preventDefault();
                      break;
                    case "End":
                      event.preventDefault();
                      break;
                    case "Enter":
                    // Fall through
                    case " ":
                      if (state.highlightedValue) {
                        item.toggleSelection(state.highlightedValue);
                        if (!config.isMultiSelect) {
                          trigger.toggleOpen(false);
                        }
                        event.preventDefault();
                      }
                      break;
                  }
                },
                className: (0, import_clsx4.default)("flex-col-0 p-2 bg-menu-background text-menu-text rounded-md shadow-hw-bottom focus-style-within overflow-auto", props.className),
                style: {
                  opacity: position ? void 0 : 0,
                  position: "fixed",
                  ...position
                },
                role: "listbox",
                "aria-multiselectable": config.isMultiSelect,
                "aria-orientation": orientation,
                tabIndex: position ? 0 : void 0,
                children: props.children
              }
            )
          ]
        }
      ),
      document.body
    );
  }
);
var Select = (0, import_react9.forwardRef)(function Select2({
  children,
  contentPanelProps,
  buttonProps,
  ...props
}, ref) {
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(SelectRoot, { ...props, isMultiSelect: false, children: [
    /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
      SelectButton,
      {
        ref,
        ...buttonProps,
        selectedDisplay: (values) => {
          const value = values[0];
          if (!buttonProps?.selectedDisplay) return void 0;
          return buttonProps.selectedDisplay(value);
        }
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(SelectContent, { ...contentPanelProps, children })
  ] });
});
var SelectUncontrolled = (0, import_react9.forwardRef)(function SelectUncontrolled2({
  value: initialValue,
  onValueChanged,
  ...props
}, ref) {
  const [value, setValue] = useOverwritableState(initialValue, onValueChanged);
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
    Select,
    {
      ...props,
      ref,
      value,
      onValueChanged: setValue
    }
  );
});
var MultiSelect = (0, import_react9.forwardRef)(function MultiSelect2({
  children,
  contentPanelProps,
  buttonProps,
  ...props
}, ref) {
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(SelectRoot, { ...props, isMultiSelect: true, children: [
    /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(SelectButton, { ref, ...buttonProps }),
    /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(SelectContent, { ...contentPanelProps, children })
  ] });
});
var MultiSelectUncontrolled = (0, import_react9.forwardRef)(function MultiSelectUncontrolled2({
  values: initialValues,
  onValuesChanged,
  ...props
}, ref) {
  const [values, setValues] = useOverwritableState(initialValues, onValuesChanged);
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
    MultiSelect,
    {
      ...props,
      ref,
      values,
      onValuesChanged: setValues
    }
  );
});
var MultiSelectChipDisplay = (0, import_react9.forwardRef)(function MultiSelectChipDisplay2({
  children,
  contentPanelProps,
  chipDisplayProps,
  ...props
}, ref) {
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(SelectRoot, { ...props, isMultiSelect: true, children: [
    /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(SelectChipDisplay, { ref, ...chipDisplayProps }),
    /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(SelectContent, { ...contentPanelProps, children })
  ] });
});
var MultiSelectChipDisplayUncontrolled = (0, import_react9.forwardRef)(function MultiSelectChipDisplayUncontrolled2({
  values: initialValues,
  onValuesChanged,
  ...props
}, ref) {
  const [values, setValues] = useOverwritableState(initialValues, onValuesChanged);
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
    MultiSelectChipDisplay,
    {
      ...props,
      ref,
      values,
      onValuesChanged: setValues
    }
  );
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  MultiSelect,
  MultiSelectChipDisplay,
  MultiSelectChipDisplayUncontrolled,
  MultiSelectUncontrolled,
  Select,
  SelectButton,
  SelectChipDisplay,
  SelectContent,
  SelectOption,
  SelectRoot,
  SelectUncontrolled
});
//# sourceMappingURL=index.cjs.map