"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxRuntime = require("react/jsx-runtime");
const React = require("react");
const fa = require("react-icons/fa");
const im = require("react-icons/im");
const ReactSelect = require("react-select");
const Creatable = require("react-select/creatable");
const useBindingState = require("../../form/hooks/useBindingState.cjs");
const classNames = require("../../utils/classNames.cjs");
require("../../utils/globals.cjs");
const useContentMemo = require("../../hooks/useContentMemo.cjs");
require("zod");
const useDidUpdateEffect = require("../../hooks/useDidUpdateEffect.cjs");
const options = require("../../types/options.cjs");
const radixDialog = require("../../workarounds/radixDialog.cjs");
const config_context = require("../config/config.context.cjs");
const label_component = require("../label/label.component.cjs");
const spinner_component = require("../spinner/spinner.component.cjs");
const statusWrapper_component = require("../statusWrapper/statusWrapper.component.cjs");
const validationErrors_component = require("../validationErrors/validationErrors.component.cjs");
const select_utils = require("./select.utils.cjs");
require("./select.theme.css.cjs");
const { DropdownIndicator, Option, ValueContainer } = ReactSelect.components;
const ReactSelectComponent = React.forwardRef(({ className, bind, options: options$1, placeholder, validationMode, validationErrorMessages: errorMessages, errorIcon, ariaLabel, currentValue, onSelectOption, getOptionValue, clearable, disabled, searchable, dropdownIcon, loadingIcon, selectedIcon, position, formatOptionLabel, closeMenuOnSelect, displaySize, label, required, requiredIndicator, scrollValidationErrorsIntoView, statusPosition, pending, multi, allowCreate, createText, onOptionCreated, labelId, labelClassName, validationErrorsClassName, statusClassName, disableOnPending, hideIconOnStatus, leftOverlay, autoValidate, onInputChange, inputValue, caseSensitive, filterOption, isInModal, inModalZIndex, inModalPortalTarget, noOptionsMessage, ...nativeProps }, ref) => {
  const internalRef = React.useRef(null);
  React.useImperativeHandle(ref, () => internalRef.current, [internalRef]);
  const [value, setValue, bindConfig] = useBindingState.useBindingState(bind, {
    validationErrorMessages: errorMessages,
    validationMode,
    value: currentValue,
    onChange: onSelectOption,
    autoValidate,
    validationErrorIcon: errorIcon
  });
  const globals = config_context.useArmstrongConfig({
    validationMode: bindConfig.validationMode,
    requiredIndicator,
    scrollValidationErrorsIntoView,
    validationErrorIcon: bindConfig.validationErrorIcon,
    inputStatusPosition: statusPosition,
    inputDisplaySize: displaySize,
    hideInputErrorIconOnStatus: hideIconOnStatus,
    disableControlOnPending: disableOnPending,
    autoValidate: bindConfig.autoValidate
  });
  const handleChange = React.useCallback((newValue) => {
    if (!multi) {
      const singleValue = newValue;
      if (select_utils.isCreatingOption(singleValue)) {
        setValue == null ? void 0 : setValue((onOptionCreated == null ? void 0 : onOptionCreated(singleValue.value)) ?? singleValue.value);
        return;
      }
      setValue == null ? void 0 : setValue(singleValue == null ? void 0 : singleValue.id);
    } else {
      const multiValue = newValue;
      setValue == null ? void 0 : setValue(multiValue == null ? void 0 : multiValue.map((v) => {
        if (select_utils.isCreatingOption(v)) {
          return (onOptionCreated == null ? void 0 : onOptionCreated(v.value)) ?? v.value;
        }
        return v.id;
      }));
      setTimeout(() => {
        var _a;
        return (_a = internalRef.current) == null ? void 0 : _a.focus();
      }, 1);
    }
  }, [multi, setValue, onOptionCreated]);
  const selectedValue = React.useMemo(() => {
    const valueFinder = (incomingOptions) => {
      if (!multi) {
        return (incomingOptions == null ? void 0 : incomingOptions.find((o) => o.id === value)) ?? null;
      }
      return (value == null ? void 0 : value.map((v) => (incomingOptions == null ? void 0 : incomingOptions.find((o) => o.id === v)) ?? {
        id: v,
        content: v,
        wasCreated: true
      })) ?? null;
    };
    if (select_utils.isGroupedOptions(options$1)) {
      return valueFinder(options$1.map((o) => o.options).flat(1));
    }
    return valueFinder(options$1);
  }, [multi, options$1, value]);
  const valueGetter = React.useCallback((option) => {
    var _a, _b;
    if (select_utils.isCreatingOption(option)) {
      return option.value;
    }
    return ((_a = getOptionValue == null ? void 0 : getOptionValue(option)) == null ? void 0 : _a.toString()) ?? ((_b = option.id) == null ? void 0 : _b.toString()) ?? "";
  }, [getOptionValue]);
  const labelGetter = React.useCallback((option) => {
    if (select_utils.isCreatingOption(option)) {
      return `${createText} ${option.value}`;
    }
    return (formatOptionLabel == null ? void 0 : formatOptionLabel(option)) ?? options.getContentFromOption(option);
  }, [createText, formatOptionLabel]);
  const filterOptionInner = React.useCallback((option, incomingInputValue) => {
    var _a, _b;
    if (filterOption) {
      return filterOption(option.data, incomingInputValue);
    }
    if (caseSensitive) {
      return !!((_a = labelGetter(option.data)) == null ? void 0 : _a.toString().includes(incomingInputValue));
    }
    return !!((_b = labelGetter(option.data)) == null ? void 0 : _b.toString().toLowerCase().includes(incomingInputValue.toLowerCase()));
  }, [caseSensitive, filterOption, labelGetter]);
  const valueContent = useContentMemo.useContentMemo(value);
  useDidUpdateEffect.useDidUpdateEffect(() => {
    if (globals.autoValidate) {
      bindConfig.validate();
    }
    bindConfig.setTouched(true);
  }, [valueContent]);
  const showLeftOverlay = leftOverlay && (globals.inputStatusPosition !== "left" || !globals.hideInputErrorIconOnStatus || !pending && !bindConfig.shouldShowValidationErrorIcon);
  const valueContainer = React.useCallback((props) => {
    return jsxRuntime.jsx("div", { className: "arm-select-inner", "data-error-icon": globals.inputStatusPosition, children: jsxRuntime.jsxs(statusWrapper_component.StatusWrapper, { error: !bindConfig.isValid, errorIcon: globals.validationErrorIcon, className: classNames.concat("arm-select-status", statusClassName), statusPosition: globals.inputStatusPosition, validationMode: globals.validationMode, children: [showLeftOverlay && jsxRuntime.jsx("div", { className: "arm-select-overlay arm-select-overlay-left", children: leftOverlay }), jsxRuntime.jsx(ValueContainer, { ...props })] }) });
  }, [
    bindConfig.isValid,
    globals.inputStatusPosition,
    globals.validationErrorIcon,
    globals.validationMode,
    leftOverlay,
    showLeftOverlay,
    statusClassName
  ]);
  const reactSelectProps = {
    isMulti: multi,
    className: "arm-select-input",
    classNamePrefix: "arm-select",
    onChange: handleChange,
    filterOption: filterOptionInner,
    options: options$1,
    placeholder,
    value: selectedValue,
    getOptionValue: valueGetter,
    formatOptionLabel: labelGetter,
    "aria-invalid": !bindConfig.isValid,
    "aria-label": ariaLabel,
    isClearable: clearable,
    isDisabled: disabled || pending && globals.disableControlOnPending ? true : void 0,
    isOptionDisabled: (o) => !!o.disabled,
    isLoading: pending,
    noOptionsMessage: (noOp) => (noOptionsMessage == null ? void 0 : noOptionsMessage(noOp.inputValue)) ?? "No options",
    isSearchable: searchable,
    menuPlacement: position,
    menuPortalTarget: isInModal ? inModalPortalTarget ?? document.body : void 0,
    styles: {
      ...select_utils.emptyStyles(),
      ...isInModal ? {
        menuPortal: (base) => ({
          ...base,
          zIndex: inModalZIndex ?? 9999,
          pointerEvents: "all"
        })
      } : {}
    },
    onBlur: radixDialog.onBlurWorkaround,
    onInputChange,
    inputValue,
    components: {
      Option: (props) => {
        return jsxRuntime.jsx(Option, { ...props, children: jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [labelGetter(props.data), props.isSelected && selectedIcon] }) });
      },
      DropdownIndicator: (props) => jsxRuntime.jsx(DropdownIndicator, { ...props, children: dropdownIcon }),
      LoadingIndicator: () => jsxRuntime.jsx(spinner_component.Spinner, { className: "arm-select-spinner", fillContainer: false, icon: loadingIcon }),
      ValueContainer: valueContainer
    },
    closeMenuOnSelect
  };
  return jsxRuntime.jsxs("div", { className: classNames.concat("arm-select-wrapper", className), "data-size": globals.inputDisplaySize, "data-multi": !!multi, "data-error": !bindConfig.isValid, ...nativeProps, children: [label && jsxRuntime.jsx(label_component.Label, { id: labelId, className: classNames.concat("arm-select-label", labelClassName), required, requiredIndicator: globals.requiredIndicator, displaySize: globals.inputDisplaySize, children: label }), allowCreate ? jsxRuntime.jsx(Creatable, { ref: internalRef, ...reactSelectProps }) : jsxRuntime.jsx(ReactSelect, { ref: internalRef, ...reactSelectProps }), !bindConfig.isValid && jsxRuntime.jsx(validationErrors_component.ValidationErrors, { "aria-label": "Error messages", className: classNames.concat("arm-select-validation-error-display", validationErrorsClassName), validationMode: globals.validationMode, scrollIntoView: globals.scrollValidationErrorsIntoView, validationErrors: bindConfig.validationErrorMessages || [] })] });
});
ReactSelectComponent.displayName = "ReactSelect";
ReactSelectComponent.defaultProps = {
  clearable: true,
  searchable: true,
  selectedIcon: jsxRuntime.jsx(im.ImCheckmark, {}),
  dropdownIcon: jsxRuntime.jsx(fa.FaChevronDown, { size: 16 }),
  createText: "Create:"
};
const NativeSelect = React.forwardRef(({ validationMode, requiredIndicator, scrollValidationErrorsIntoView, errorIcon, validationErrorMessages, currentValue, onSelectOption, bind, className, displaySize, label, required, options: options$1, onChange, placeholderOption, placeholderOptionEnabled, disabled, statusPosition, dropdownIcon, labelId, labelClassName, validationErrorsClassName, statusClassName, hideIconOnStatus, leftOverlay, autoValidate, ...nativeProps }, ref) => {
  const internalRef = React.useRef(null);
  React.useImperativeHandle(ref, () => internalRef.current, [internalRef]);
  const [value, setValue, bindConfig] = useBindingState.useBindingState(bind, {
    validationErrorMessages,
    validationMode,
    value: currentValue,
    onChange: onSelectOption,
    validationErrorIcon: errorIcon,
    autoValidate
  });
  const globals = config_context.useArmstrongConfig({
    validationMode: bindConfig.validationMode,
    requiredIndicator,
    scrollValidationErrorsIntoView,
    validationErrorIcon: bindConfig.validationErrorIcon,
    inputStatusPosition: statusPosition,
    inputDisplaySize: displaySize,
    hideInputErrorIconOnStatus: hideIconOnStatus,
    autoValidate: bindConfig.autoValidate
  });
  const clearSelect = React.useCallback(() => {
    var _a;
    onSelectOption == null ? void 0 : onSelectOption(void 0);
    (_a = bind == null ? void 0 : bind.setValue) == null ? void 0 : _a.call(bind, void 0);
  }, [onSelectOption, bind]);
  const onChangeEvent = React.useCallback((event) => {
    if (onChange) {
      onChange(event);
    }
    const { value: newValue } = event.currentTarget;
    const selectedOption = options$1 == null ? void 0 : options$1.find((option) => {
      var _a;
      return ((_a = option.id) == null ? void 0 : _a.toString()) === newValue;
    });
    if (selectedOption) {
      setValue == null ? void 0 : setValue(selectedOption.id);
      onSelectOption == null ? void 0 : onSelectOption(selectedOption.id);
    } else if (!newValue && placeholderOption && placeholderOptionEnabled) {
      clearSelect();
    }
  }, [onChange, options$1, placeholderOption, placeholderOptionEnabled, setValue, onSelectOption, clearSelect]);
  useDidUpdateEffect.useDidUpdateEffect(() => {
    if (globals.autoValidate) {
      bindConfig.validate();
    }
    bindConfig.setTouched(true);
  }, [value]);
  const showLeftOverlay = leftOverlay && (globals.inputStatusPosition !== "left" || !globals.hideInputErrorIconOnStatus || !bindConfig.shouldShowValidationErrorIcon);
  return jsxRuntime.jsxs("div", { className: classNames.concat("arm-select-wrapper", "arm-select-native-wrapper", className), "data-size": displaySize, "data-error": !bindConfig.isValid, "data-disabled": !!disabled, "data-empty": !!value, children: [label && jsxRuntime.jsx(label_component.Label, { className: classNames.concat("arm-select-label"), required, requiredIndicator: globals.requiredIndicator, displaySize: globals.inputDisplaySize, children: label }), jsxRuntime.jsxs("div", { className: "arm-select-inner", "data-error-icon": statusPosition, "data-disabled": disabled, children: [jsxRuntime.jsxs(statusWrapper_component.StatusWrapper, { error: !bindConfig.isValid, errorIcon: globals.validationErrorIcon, className: classNames.concat("arm-select-status", statusClassName), statusPosition: globals.inputStatusPosition, validationMode: globals.validationMode, children: [showLeftOverlay && jsxRuntime.jsx("div", { className: "arm-select-overlay arm-select-overlay-left", children: leftOverlay }), jsxRuntime.jsxs("select", { "data-left-overlay": !!showLeftOverlay, "data-right-overlay": !bindConfig.isValid, className: "arm-native-select", ...nativeProps, ref: internalRef, onChange: onChangeEvent, value: value ?? void 0, disabled, defaultValue: placeholderOption && !nativeProps.defaultValue && !value ? "" : nativeProps.defaultValue, children: [placeholderOption && jsxRuntime.jsx("option", { value: "", disabled: !placeholderOptionEnabled, children: placeholderOption }), options$1 == null ? void 0 : options$1.map((option) => jsxRuntime.jsx("option", { value: option.id ?? void 0, disabled: option.disabled, ...option.htmlProps, children: options.getContentFromOption(option) }, option.id))] })] }), jsxRuntime.jsx("div", { className: "arm-native-indicators", children: jsxRuntime.jsx("div", { className: "arm-native-select-arrow", children: dropdownIcon }) })] }), !bindConfig.isValid && jsxRuntime.jsx(validationErrors_component.ValidationErrors, { "aria-label": "Error messages", className: "arm-select-validation-error-display", validationMode: globals.validationMode, scrollIntoView: globals.scrollValidationErrorsIntoView, validationErrors: bindConfig.validationErrorMessages || [] })] });
});
NativeSelect.displayName = "NativeSelect";
NativeSelect.defaultProps = {
  dropdownIcon: jsxRuntime.jsx(fa.FaChevronDown, { size: 16 })
};
const Select = React.forwardRef((props, ref) => {
  return jsxRuntime.jsx(ReactSelectComponent, { ...props, multi: false, ref });
});
Select.displayName = "Select";
const MultiSelect = React.forwardRef((props, ref) => {
  return jsxRuntime.jsx(ReactSelectComponent, { ...props, multi: true, ref });
});
MultiSelect.displayName = "MultiSelect";
exports.MultiSelect = MultiSelect;
exports.NativeSelect = NativeSelect;
exports.Select = Select;
//# sourceMappingURL=select.component.cjs.map
