// src/components/user-action/select/Select.tsx
import {
  createContext as createContext2,
  forwardRef as forwardRef3,
  useCallback as useCallback5,
  useContext as useContext2,
  useEffect as useEffect6,
  useId as useId3,
  useImperativeHandle,
  useMemo as useMemo2,
  useRef as useRef2,
  useState as useState7
} from "react";
import clsx4 from "clsx";

// src/localization/LanguageProvider.tsx
import { createContext, useContext, useEffect, useMemo, useState as useState2 } from "react";

// src/hooks/useLocalStorage.ts
import { useCallback, useState } from "react";

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

// src/localization/util.ts
var languages = ["en", "de"];
var languagesLocalNames = {
  en: "English",
  de: "Deutsch"
};
var DEFAULT_LANGUAGE = "en";
var LanguageUtil = {
  languages,
  DEFAULT_LANGUAGE,
  languagesLocalNames
};

// src/localization/LanguageProvider.tsx
import { jsx } from "react/jsx-runtime";
var LanguageContext = createContext({
  language: LanguageUtil.DEFAULT_LANGUAGE,
  setLanguage: (v) => v
});
var useLanguage = () => {
  const context = useContext(LanguageContext);
  if (!context) {
    throw new Error("useLanguage must be used within LanguageContext. Try adding a LanguageProvider around your app.");
  }
  return context;
};

// src/localization/useTranslation.ts
var TranslationPluralCount = {
  zero: 0,
  one: 1,
  two: 2,
  few: 3,
  many: 11,
  other: -1
};
var useTranslation = (translations, overwriteTranslation = {}) => {
  const { language: languageProp, translation: overwrite } = overwriteTranslation;
  const { language: inferredLanguage } = useLanguage();
  const usedLanguage = languageProp ?? inferredLanguage;
  const usedTranslations = [...translations];
  if (overwrite) {
    usedTranslations.push(overwrite);
  }
  return (key, options) => {
    const { count, replacements } = { ...{ count: 0, replacements: {} }, ...options };
    try {
      for (let i = translations.length - 1; i >= 0; i--) {
        const translation = translations[i];
        const localizedTranslation = translation[usedLanguage];
        if (!localizedTranslation) {
          continue;
        }
        const value = localizedTranslation[key];
        if (!value) {
          continue;
        }
        let forProcessing;
        if (typeof value !== "string") {
          if (count === TranslationPluralCount.zero && value?.zero) {
            forProcessing = value.zero;
          } else if (count === TranslationPluralCount.one && value?.one) {
            forProcessing = value.one;
          } else if (count === TranslationPluralCount.two && value?.two) {
            forProcessing = value.two;
          } else if (TranslationPluralCount.few <= count && count < TranslationPluralCount.many && value?.few) {
            forProcessing = value.few;
          } else if (count > TranslationPluralCount.many && value?.many) {
            forProcessing = value.many;
          } else {
            forProcessing = value.other;
          }
        } else {
          forProcessing = value;
        }
        forProcessing = forProcessing.replace(/\{\{(\w+)}}/g, (_, placeholder) => {
          return replacements[placeholder] ?? `{{key:${placeholder}}}`;
        });
        return forProcessing;
      }
    } catch (e) {
      console.error(e);
    }
    return `{{${usedLanguage}:${key}}}`;
  };
};

// src/components/layout/Expandable.tsx
import { forwardRef, useCallback as useCallback2, useId } from "react";
import { ChevronDown } from "lucide-react";
import clsx from "clsx";

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

// src/components/layout/Expandable.tsx
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
var ExpansionIcon = ({ isExpanded, className }) => {
  return /* @__PURE__ */ jsx2(
    ChevronDown,
    {
      "aria-hidden": true,
      className: clsx(
        "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 = forwardRef(function Expandable2({
  children,
  id: providedId,
  label,
  icon,
  isExpanded = false,
  onChange,
  clickOnlyOnHeader = true,
  disabled = false,
  className,
  headerClassName,
  contentClassName,
  contentExpandedClassName
}, ref) {
  const defaultIcon = useCallback2((expanded) => /* @__PURE__ */ jsx2(ExpansionIcon, { isExpanded: expanded }), []);
  icon ??= defaultIcon;
  const generatedId = useId();
  const id = providedId ?? generatedId;
  return /* @__PURE__ */ jsxs(
    "div",
    {
      ref,
      onClick: () => !clickOnlyOnHeader && !disabled && onChange?.(!isExpanded),
      className: clsx(
        "flex-col-0 bg-surface text-on-surface group rounded-lg shadow-sm",
        { "cursor-pointer": !clickOnlyOnHeader && !disabled },
        className
      ),
      children: [
        /* @__PURE__ */ jsxs(
          "button",
          {
            onClick: () => clickOnlyOnHeader && !disabled && onChange?.(!isExpanded),
            className: clsx(
              "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__ */ jsx2(
          "div",
          {
            id: `${id}-content`,
            className: clsx(
              "flex-col-2 px-4 transition-all duration-300 ease-in-out",
              {
                [clsx("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 = forwardRef(function ExpandableUncontrolled2({
  isExpanded,
  onChange,
  ...props
}, ref) {
  const [usedIsExpanded, setUsedIsExpanded] = useOverwritableState(isExpanded, onChange);
  return /* @__PURE__ */ jsx2(
    Expandable,
    {
      ...props,
      ref,
      isExpanded: usedIsExpanded,
      onChange: setUsedIsExpanded
    }
  );
});

// src/hooks/focus/useFocusTrap.ts
import { useCallback as useCallback3, useEffect as useEffect4, useId as useId2, useRef, useState as useState5 } from "react";

// src/hooks/focus/useIsMounted.ts
import { useEffect as useEffect3, useLayoutEffect, useState as useState4 } from "react";
var isClient = typeof window !== "undefined" && typeof document !== "undefined";
var useIsomorphicEffect = isClient ? useLayoutEffect : useEffect3;
var useIsMounted = () => {
  const [isMounted, setIsMounted] = useState4(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 = useRef(null);
  const [paused, setPaused] = useState5(false);
  const isMounted = useIsMounted();
  const id = useId2();
  const focusElement = useCallback3(() => {
    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]);
  useEffect4(() => {
    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]);
  useEffect4(() => {
    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
import { CheckIcon, Plus, XIcon } from "lucide-react";

// src/components/layout/Chip.tsx
import clsx2 from "clsx";
import { jsx as jsx3, jsxs as jsxs2 } from "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__ */ jsxs2(
    "div",
    {
      ...restProps,
      className: clsx2(
        `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__ */ jsx3("span", { className: colorMappingIcon, children: trailingIcon })
      ]
    }
  );
};

// src/components/user-action/Button.tsx
import { forwardRef as forwardRef2 } from "react";
import clsx3 from "clsx";
import { jsx as jsx4, jsxs as jsxs3 } from "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 = forwardRef2(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__ */ jsxs3(
    "button",
    {
      ref,
      onClick,
      className: clsx3(
        "group font-semibold",
        colorClasses,
        "not-disabled:hover:brightness-90",
        "disabled:text-disabled disabled:bg-disabled-background",
        ButtonUtil.paddingMapping[size],
        className
      ),
      ...restProps,
      children: [
        startIcon && /* @__PURE__ */ jsx4(
          "span",
          {
            className: clsx3(
              iconColorClasses,
              "group-disabled:text-disabled-icon"
            ),
            children: startIcon
          }
        ),
        children,
        endIcon && /* @__PURE__ */ jsx4(
          "span",
          {
            className: clsx3(
              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__ */ jsxs3(
    "button",
    {
      onClick,
      className: clsx3(
        "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__ */ jsx4(
          "span",
          {
            className: clsx3(
              iconColorClasses,
              "group-disabled:text-disabled-icon"
            ),
            children: startIcon
          }
        ),
        children,
        endIcon && /* @__PURE__ */ jsx4(
          "span",
          {
            className: clsx3(
              iconColorClasses,
              "group-disabled:text-disabled-icon"
            ),
            children: endIcon
          }
        )
      ]
    }
  );
};
var IconButton = forwardRef2(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__ */ jsx4(
    "button",
    {
      ref,
      className: clsx3(
        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
import { useCallback as useCallback4, useEffect as useEffect5, useState as useState6 } from "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] = useState6();
  const isMounted = useIsMounted();
  const calculate = useCallback4(() => {
    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;
  useEffect5(() => {
    if (active && isMounted) {
      calculate();
    } else {
      setStyle(void 0);
    }
  }, [calculate, active, isMounted, height, width]);
  useEffect5(() => {
    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
import { createPortal } from "react-dom";
import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
var defaultToggleOpenOptions = {
  highlightStartPositionBehavior: "first"
};
var SelectContext = createContext2(null);
function useSelectContext() {
  const ctx = useContext2(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 = useRef2(null);
  const generatedId = useId3();
  const usedId = id ?? generatedId;
  const [internalState, setInternalState] = useState7({
    isOpen,
    options: []
  });
  const selectedValues = useMemo2(
    () => isMultiSelect ? values ?? [] : [value].filter(Boolean),
    [isMultiSelect, value, values]
  );
  const selectedOptions = useMemo2(
    () => 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 = useCallback5((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 = useCallback5((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 = useCallback5((ref) => {
    triggerRef.current = ref.current;
  }, []);
  const unregisterTrigger = useCallback5(() => {
    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
    }));
  };
  useEffect6(() => {
    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__ */ jsx5(SelectContext.Provider, { value: contextValue, children });
};
var SelectOption = forwardRef3(
  function SelectOption2({ children, value, disabled = false, iconAppearance, className, ...restProps }, ref) {
    const { state, config, item, trigger } = useSelectContext();
    const { register, unregister, toggleSelection, highlightItem } = item;
    const itemRef = useRef2(null);
    iconAppearance ??= config.iconAppearance;
    const label = children ?? value;
    useEffect6(() => {
      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__ */ jsxs4(
      "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: clsx4(
          "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__ */ jsx5(
            CheckIcon,
            {
              className: clsx4("w-4 h-4", { "opacity-0": !isSelected || disabled }),
              "aria-hidden": true
            }
          ),
          label,
          iconAppearance === "right" && /* @__PURE__ */ jsx5(
            CheckIcon,
            {
              className: clsx4("w-4 h-4", { "opacity-0": !isSelected || disabled }),
              "aria-hidden": true
            }
          )
        ]
      }
    );
  }
);
var defaultSelectButtonTranslation = {
  en: {
    clickToSelect: "Click to select"
  },
  de: {
    clickToSelect: "Zum ausw\xE4hlen dr\xFCcken"
  }
};
var SelectButton = forwardRef3(function SelectButton2({ placeholder, selectedDisplay, ...props }, ref) {
  const translation = useTranslation([defaultSelectButtonTranslation]);
  const { state, trigger } = useSelectContext();
  const { register, unregister, toggleOpen } = trigger;
  const innerRef = useRef2(null);
  useImperativeHandle(ref, () => innerRef.current);
  useEffect6(() => {
    register(innerRef);
    return () => unregister();
  }, [register, unregister]);
  const disabled = !!props?.disabled || !!state.disabled;
  const invalid = state.invalid;
  const hasValue = state.value.length > 0;
  return /* @__PURE__ */ jsxs4(
    "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: clsx4(
        "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__ */ jsx5("div", { className: clsx4("flex flex-wrap gap-x-1 gap-y-2"), children: state.selectedOptions.map(({ value, label }, index) => /* @__PURE__ */ jsxs4("span", { className: "flex-row-0", children: [
          label,
          index < state.value.length - 1 && /* @__PURE__ */ jsx5("span", { children: "," })
        ] }, value)) }) : placeholder ?? translation("clickToSelect"),
        /* @__PURE__ */ jsx5(
          ExpansionIcon,
          {
            isExpanded: state.isOpen,
            className: clsx4({
              "text-input-text": !disabled && !invalid,
              "text-negative": !disabled && invalid,
              "text-disabled": disabled
            })
          }
        )
      ]
    }
  );
});
var SelectChipDisplay = forwardRef3(function SelectChipDisplay2({ ...props }, ref) {
  const { state, trigger, item } = useSelectContext();
  const { register, unregister, toggleOpen } = trigger;
  const innerRef = useRef2(null);
  useImperativeHandle(ref, () => innerRef.current);
  useEffect6(() => {
    register(innerRef);
    return () => unregister();
  }, [register, unregister]);
  const disabled = !!props?.disabled || !!state.disabled;
  const invalid = state.invalid;
  return /* @__PURE__ */ jsxs4(
    "div",
    {
      ...props,
      ref: innerRef,
      className: clsx4(
        "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__ */ jsxs4(Chip, { className: "gap-x-2", children: [
          label,
          /* @__PURE__ */ jsx5(
            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__ */ jsx5(XIcon, { className: "w-5 h-5" })
            }
          )
        ] }, value)),
        /* @__PURE__ */ jsx5(
          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__ */ jsx5(Plus, {})
          }
        )
      ]
    }
  );
});
var SelectContent = forwardRef3(
  function SelectContent2({
    alignment,
    orientation = "vertical",
    containerClassName,
    ...props
  }, ref) {
    const innerRef = useRef2(null);
    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 createPortal(
      /* @__PURE__ */ jsxs4(
        "div",
        {
          id: `select-container-${state.id}`,
          className: clsx4("fixed inset-0 w-screen h-screen", containerClassName),
          hidden: !state.isOpen,
          children: [
            /* @__PURE__ */ jsx5(
              "div",
              {
                id: `select-background-${state.id}`,
                onClick: () => trigger.toggleOpen(false),
                className: clsx4("fixed inset-0 w-screen h-screen")
              }
            ),
            /* @__PURE__ */ jsx5(
              "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: clsx4("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 = forwardRef3(function Select2({
  children,
  contentPanelProps,
  buttonProps,
  ...props
}, ref) {
  return /* @__PURE__ */ jsxs4(SelectRoot, { ...props, isMultiSelect: false, children: [
    /* @__PURE__ */ jsx5(
      SelectButton,
      {
        ref,
        ...buttonProps,
        selectedDisplay: (values) => {
          const value = values[0];
          if (!buttonProps?.selectedDisplay) return void 0;
          return buttonProps.selectedDisplay(value);
        }
      }
    ),
    /* @__PURE__ */ jsx5(SelectContent, { ...contentPanelProps, children })
  ] });
});
var SelectUncontrolled = forwardRef3(function SelectUncontrolled2({
  value: initialValue,
  onValueChanged,
  ...props
}, ref) {
  const [value, setValue] = useOverwritableState(initialValue, onValueChanged);
  return /* @__PURE__ */ jsx5(
    Select,
    {
      ...props,
      ref,
      value,
      onValueChanged: setValue
    }
  );
});
var MultiSelect = forwardRef3(function MultiSelect2({
  children,
  contentPanelProps,
  buttonProps,
  ...props
}, ref) {
  return /* @__PURE__ */ jsxs4(SelectRoot, { ...props, isMultiSelect: true, children: [
    /* @__PURE__ */ jsx5(SelectButton, { ref, ...buttonProps }),
    /* @__PURE__ */ jsx5(SelectContent, { ...contentPanelProps, children })
  ] });
});
var MultiSelectUncontrolled = forwardRef3(function MultiSelectUncontrolled2({
  values: initialValues,
  onValuesChanged,
  ...props
}, ref) {
  const [values, setValues] = useOverwritableState(initialValues, onValuesChanged);
  return /* @__PURE__ */ jsx5(
    MultiSelect,
    {
      ...props,
      ref,
      values,
      onValuesChanged: setValues
    }
  );
});
var MultiSelectChipDisplay = forwardRef3(function MultiSelectChipDisplay2({
  children,
  contentPanelProps,
  chipDisplayProps,
  ...props
}, ref) {
  return /* @__PURE__ */ jsxs4(SelectRoot, { ...props, isMultiSelect: true, children: [
    /* @__PURE__ */ jsx5(SelectChipDisplay, { ref, ...chipDisplayProps }),
    /* @__PURE__ */ jsx5(SelectContent, { ...contentPanelProps, children })
  ] });
});
var MultiSelectChipDisplayUncontrolled = forwardRef3(function MultiSelectChipDisplayUncontrolled2({
  values: initialValues,
  onValuesChanged,
  ...props
}, ref) {
  const [values, setValues] = useOverwritableState(initialValues, onValuesChanged);
  return /* @__PURE__ */ jsx5(
    MultiSelectChipDisplay,
    {
      ...props,
      ref,
      values,
      onValuesChanged: setValues
    }
  );
});
export {
  MultiSelect,
  MultiSelectChipDisplay,
  MultiSelectChipDisplayUncontrolled,
  MultiSelectUncontrolled,
  Select,
  SelectButton,
  SelectChipDisplay,
  SelectContent,
  SelectOption,
  SelectRoot,
  SelectUncontrolled
};
//# sourceMappingURL=index.mjs.map