function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
var _excluded = ["aria-label", "aria-labelledby", "decimalScale", "defaultValue", "disabled", "error", "fillDecimalScale", "onChange", "onKeyDown", "onBlur", "prefix", "readOnly", "step", "style", "suffix", "value", "qa"],
  _excluded2 = ["currencyDisplay", "currencyIsoCode", "decimalScale", "fillDecimalScale", "prefix", "suffix"];
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
import { formatCurrencyToParts } from '@procore/globalization-toolkit';
import { findIndex } from 'ramda';
import React from 'react';
import { useI18nContext } from '../_hooks/I18n';
import { spacing } from '../_styles/spacing';
import { mergeRefs } from '../_utils/mergeRefs';
import { defaultCurrencyFillDecimalScale, defaultCurrencyInputPrefix } from './NumberInput.constants';
import { useNumberFormat, useNumberInputLabel, usePrevious } from './NumberInput.hooks';
import { addonRootFontFamily, addonRootFontSize, addonRootPadding, inputDefaultXPadding, StyledIncrementerButton, StyledIncrementerWrapper, StyledInput, StyledPrefix, StyledSuffix, StyledWrapper } from './NumberInput.styles';
import { backspaceKey, commaKey, controlKey, copyKey, defaultLocale, deleteKey, emptyString, format, getNewCursorPosition, getSeparators, highlightAllKey, identicalLocales, identifyPressedKey, maxDigitLength, metaKeyIdentifier, minus, numericKeypadKey, periodKey, prepareValueToFormatting, toFixed, unformat } from './NumberInput.utils';
function noop() {}
var PlusIcon = function PlusIcon() {
  return /*#__PURE__*/React.createElement("svg", {
    width: "8",
    height: "8",
    viewBox: "0 0 8 8",
    xmlns: "http://www.w3.org/2000/svg"
  }, /*#__PURE__*/React.createElement("path", {
    d: "M4.5 0H3.5V3.5H0V4.5H3.5V8H4.5V4.5H8V3.5H4.5V0Z"
  }));
};
var MinusIcon = function MinusIcon() {
  return /*#__PURE__*/React.createElement("svg", {
    width: "8",
    height: "2",
    viewBox: "0 0 8 2",
    xmlns: "http://www.w3.org/2000/svg"
  }, /*#__PURE__*/React.createElement("path", {
    d: "M4.5 0.5H3.5H0V1.5H3.5H4.5H8V0.5H4.5Z"
  }));
};

/**

 The number input allows users to add numbers to a given form or table.
 The currency input will be used for data with a monetary value.
 Both components allow characters 0-9, periods, and commas. In order to avoid
 the loss of precision, the number length is limited by 15 digits.

 @since 10.19.0

 @see [Storybook](https://stories.core.procore.com/?path=/story/core-react_demos-numberinput--demo-number-input)

 @see [Design Guidelines](https://design.procore.com/number-and-currency-input)

 */
export var NumberInput = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
  var ariaLabel = _ref['aria-label'],
    ariaLabelledBy = _ref['aria-labelledby'],
    _ref$decimalScale = _ref.decimalScale,
    decimalScale = _ref$decimalScale === void 0 ? true : _ref$decimalScale,
    defaultValue = _ref.defaultValue,
    _ref$disabled = _ref.disabled,
    disabled = _ref$disabled === void 0 ? false : _ref$disabled,
    _ref$error = _ref.error,
    error = _ref$error === void 0 ? false : _ref$error,
    _ref$fillDecimalScale = _ref.fillDecimalScale,
    fillDecimalScale = _ref$fillDecimalScale === void 0 ? 'none' : _ref$fillDecimalScale,
    _onChange = _ref.onChange,
    _ref$onKeyDown = _ref.onKeyDown,
    _onKeyDown = _ref$onKeyDown === void 0 ? noop : _ref$onKeyDown,
    _ref$onBlur = _ref.onBlur,
    _onBlur = _ref$onBlur === void 0 ? noop : _ref$onBlur,
    _ref$prefix = _ref.prefix,
    prefix = _ref$prefix === void 0 ? emptyString : _ref$prefix,
    readOnly = _ref.readOnly,
    _ref$step = _ref.step,
    step = _ref$step === void 0 ? 0 : _ref$step,
    style = _ref.style,
    _ref$suffix = _ref.suffix,
    suffix = _ref$suffix === void 0 ? emptyString : _ref$suffix,
    value = _ref.value,
    qa = _ref.qa,
    props = _objectWithoutProperties(_ref, _excluded);
  var I18n = useI18nContext();
  var contextLocale = I18n.locale || defaultLocale;
  var inputRef = React.useRef(null);
  var _useNumberFormat = useNumberFormat({
      decimalScale: decimalScale,
      fillDecimalScale: fillDecimalScale,
      locale: contextLocale
    }),
    verifiedDecimalScale = _useNumberFormat.decimalScale,
    fillDecimalScaleOnBlur = _useNumberFormat.fillDecimalScaleOnBlur,
    fixedDecimalScale = _useNumberFormat.fixedDecimalScale,
    formatValue = _useNumberFormat.formatValue,
    getValueLengthInfo = _useNumberFormat.getValueLengthInfo,
    locale = _useNumberFormat.locale;
  var _useNumberInputLabel = useNumberInputLabel({
      ariaLabel: ariaLabel,
      ariaLabelledBy: ariaLabelledBy,
      id: props.id,
      name: props.name,
      prefix: prefix,
      suffix: suffix
    }),
    inputProps = _useNumberInputLabel.inputProps,
    prefixProps = _useNumberInputLabel.prefixProps,
    suffixProps = _useNumberInputLabel.suffixProps;
  var isControlled = value !== undefined;
  var isControlledWithoutOnChangeHandlerAndReadOnlyAttribute = isControlled && !_onChange && !readOnly;
  var hasIncrementer = step > 0 && !readOnly;
  var _React$useMemo = React.useMemo(function () {
      return getSeparators(locale);
    }, [locale]),
    group = _React$useMemo.group,
    decimal = _React$useMemo.decimal;
  var decimalSeparatorKey = React.useMemo(function () {
    return decimal === periodKey ? periodKey : commaKey;
  }, [decimal]);
  var inputPadding = React.useMemo(function () {
    var fontContext = "".concat(addonRootFontSize, " \"").concat(addonRootFontFamily, "\"");
    if (prefix || suffix) {
      var element = document.createElement('canvas');
      var context = element === null || element === void 0 ? void 0 : element.getContext('2d');
      if (context) {
        context.font = fontContext;
        var extraBasePadding = inputDefaultXPadding + addonRootPadding;
        var suffixPadding = extraBasePadding + Math.ceil(context.measureText(suffix).width);
        var getRightPadding = function getRightPadding() {
          if (hasIncrementer && suffix) {
            return suffixPadding + spacing.xl;
          }
          if (suffix) {
            return suffixPadding;
          }
          return null;
        };
        return {
          left: prefix ? extraBasePadding + Math.ceil(context.measureText(prefix).width) : inputDefaultXPadding,
          right: getRightPadding()
        };
      }
    }
    return {
      left: inputDefaultXPadding,
      right: null
    };
  }, [prefix, suffix, hasIncrementer]);
  var getValueChange = React.useCallback(function (value) {
    var _unformat = unformat(locale, value),
      parsedNumber = _unformat.parsedNumber;
    return {
      value: value,
      parsedNumber: isNaN(parsedNumber) ? null : parsedNumber
    };
  }, [locale]);
  var externalOnChange = React.useCallback(function (value) {
    return _onChange && _onChange(getValueChange(value));
  }, [_onChange, getValueChange]);
  var _React$useState = React.useState(formatValue(defaultValue)),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    inputValue = _React$useState2[0],
    setInputValue = _React$useState2[1];
  var _React$useState3 = React.useState(isControlled ? formatValue(value) : inputValue),
    _React$useState4 = _slicedToArray(_React$useState3, 2),
    prevValue = _React$useState4[0],
    setPrevValue = _React$useState4[1];
  var _React$useState5 = React.useState({
      selectionStart: 0,
      selectionEnd: 0,
      selection: emptyString
    }),
    _React$useState6 = _slicedToArray(_React$useState5, 2),
    prevCursorPosition = _React$useState6[0],
    setPrevCursorPosition = _React$useState6[1];
  var _React$useState7 = React.useState(),
    _React$useState8 = _slicedToArray(_React$useState7, 2),
    pressedKey = _React$useState8[0],
    setPressedKey = _React$useState8[1];
  var prevLocale = usePrevious(locale);

  // eslint-disable-next-line react-hooks/exhaustive-deps
  React.useLayoutEffect(function () {
    var formattedValue = formatValue(value);
    if (isControlled && inputValue !== formattedValue) {
      setInputValue(formattedValue);
    }
    if (isControlledWithoutOnChangeHandlerAndReadOnlyAttribute) {
      console.error("Warning: Failed prop type: You provided a `value` prop to a form field without an `onChange` handler.\n        This will render a read-only field. If the field should be mutable use `defaultValue`.\n        Otherwise, set either `onChange` or `readOnly`.");
    }
  }, [value]);
  React.useEffect(function () {
    if (prevLocale && !identicalLocales(prevLocale, locale)) {
      setInputValue(function (prev) {
        var newValue = formatValue(unformat(prevLocale, prev).parsedNumber);
        externalOnChange(newValue);
        return newValue;
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [prevLocale, formatValue]);
  React.useLayoutEffect(function () {
    var _inputRef$current;
    var displayValue = ((_inputRef$current = inputRef.current) === null || _inputRef$current === void 0 ? void 0 : _inputRef$current.value) || '';
    if (!_onChange || !displayValue) {
      return;
    }
    var formattedValue = formatValue(value);
    if (displayValue !== formattedValue) {
      var lastChar = displayValue[displayValue.length - 1];
      var lastCharIsPending = [periodKey, commaKey].includes(lastChar);
      var decimals = displayValue.split(decimal)[1] || '';
      var lastDecimalIsZero = decimals && decimals[decimals.length - 1] === '0';
      var onlyMinusDisplayed = displayValue === minus;

      // a client state and display mismatch is only valid when
      if (lastCharIsPending || lastDecimalIsZero || onlyMinusDisplayed) {
        return;
      }

      // otherwise sync display with client state
      setInputValue(formattedValue);
    }
  });
  var getNewValueAndCursorPosition = function getNewValueAndCursorPosition(value, pressedKey) {
    var preparedValue = prepareValueToFormatting(decimal, decimalSeparatorKey, group, pressedKey, prevCursorPosition, prevValue, verifiedDecimalScale, value);
    var newValue = formatValue(preparedValue);
    return {
      newValue: newValue,
      newCursorPosition: getNewCursorPosition(decimal, decimalSeparatorKey, group, newValue, pressedKey, prevCursorPosition, prevValue, value, verifiedDecimalScale, locale, fillDecimalScale)
    };
  };
  var adjustCursor = function adjustCursor(newPosition) {
    var _inputRef$current2;
    (_inputRef$current2 = inputRef.current) === null || _inputRef$current2 === void 0 ? void 0 : _inputRef$current2.setSelectionRange(newPosition, newPosition);
    // Mobile Chrome adjustment
    setTimeout(function () {
      var _inputRef$current3;
      return (_inputRef$current3 = inputRef.current) === null || _inputRef$current3 === void 0 ? void 0 : _inputRef$current3.setSelectionRange(newPosition, newPosition);
    }, 0);
  };
  var makeStep = function makeStep() {
    var down = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    var getSignificantPrecision = function getSignificantPrecision(fraction) {
      var reversedFraction = fraction.split(emptyString).reverse();
      var indexOfLastSignificantFractionDigit = findIndex(function (i) {
        return i !== '0';
      }, reversedFraction);
      return indexOfLastSignificantFractionDigit > -1 ? reversedFraction.slice(indexOfLastSignificantFractionDigit).length : 0;
    };
    var _unformat2 = unformat(locale, inputValue),
      parsedNumber = _unformat2.parsedNumber,
      fraction = _unformat2.fraction;
    var _unformat3 = unformat(locale, step),
      stepFraction = _unformat3.fraction;
    var prevValuePrecision = fraction.length || 0;
    var prevValueSignificantPrecision = getSignificantPrecision(fraction);
    var rawStepPrecision = stepFraction.length || 0;
    var rawStepPrecisionExceedsDecimalScale = rawStepPrecision > verifiedDecimalScale;
    var stepPrecision = rawStepPrecisionExceedsDecimalScale ? verifiedDecimalScale : rawStepPrecision;
    if (rawStepPrecisionExceedsDecimalScale) {
      console.warn("WARNING: Step's value was rounded since its scale (".concat(rawStepPrecision, ") exceeds the decimal scale (").concat(verifiedDecimalScale, ")."));
    }
    var diff = toFixed(step, stepPrecision) * (down ? -1 : 1);
    var precision = Math.max(stepPrecision, fixedDecimalScale ? verifiedDecimalScale : prevValuePrecision);
    var significantPrecision = Math.max(prevValueSignificantPrecision, stepPrecision);
    var calculated = inputValue ? ((parsedNumber || 0) + diff).toFixed(significantPrecision) : diff;
    var _getValueLengthInfo = getValueLengthInfo(calculated, true),
      isSafeLength = _getValueLengthInfo.isSafeLength,
      isSafeIntegerLength = _getValueLengthInfo.isSafeIntegerLength;
    var rejectStepByLengthLimit = !isSafeLength || !isSafeIntegerLength;
    if (rejectStepByLengthLimit) {
      console.warn("WARNING: Incrementer's step was not fulfilled since result oversteps input ".concat(maxDigitLength, "-digit limit and can't be presented without a loss of precision."));
      return;
    }
    var formatted = format(locale, precision, 'always', calculated, true);
    setInputValue(formatted);
    externalOnChange(formatted);
  };
  var internalOnKeyDown = function internalOnKeyDown(e) {
    var ctrlKey = e.ctrlKey,
      metaKey = e.metaKey,
      key = e.key,
      _e$target = e.target,
      value = _e$target.value,
      selectionStart = _e$target.selectionStart,
      selectionEnd = _e$target.selectionEnd;
    var selection = value.slice(selectionStart, selectionEnd);
    setPressedKey(key);
    setPrevCursorPosition({
      selectionStart: selectionStart,
      selectionEnd: selectionEnd,
      selection: selection
    });
    setPrevValue(value);
    var preserveDecimalSeparator = function preserveDecimalSeparator() {
      var decimalBackspaced = !selection && [backspaceKey].includes(key) && value[selectionEnd - 1] === decimal;
      var decimalDeleted = !selection && [deleteKey, numericKeypadKey].includes(key) && value[selectionEnd] === decimal;
      var nonReplacingKeys = [metaKeyIdentifier, controlKey, highlightAllKey, copyKey].includes(key) && (ctrlKey || metaKey);
      var decimalReplacedAsSelection = selection && selection.includes(decimal) && selection.length < value.length && !nonReplacingKeys;
      var preserveDecimal = decimalBackspaced || decimalDeleted || decimalReplacedAsSelection;
      if (preserveDecimal) {
        var base = decimalReplacedAsSelection ? selectionStart : selectionEnd;
        var shift = decimalBackspaced && -1 || decimalDeleted && 1 || 0;
        var cursorPosition = base + shift;
        e.preventDefault();
        adjustCursor(cursorPosition);
      }
    };
    var isDecimalSeparatorPreserved = function isDecimalSeparatorPreserved() {
      var _getValueLengthInfo2 = getValueLengthInfo(value),
        safeIntegerLength = _getValueLengthInfo2.safeIntegerLength,
        integerLength = _getValueLengthInfo2.integerLength,
        fractionLength = _getValueLengthInfo2.fractionLength;
      var decimalSeparatorCanNotBeRemoved = safeIntegerLength - integerLength < fractionLength;
      return fillDecimalScaleOnBlur && decimalSeparatorCanNotBeRemoved || fixedDecimalScale;
    };
    if (isDecimalSeparatorPreserved()) {
      preserveDecimalSeparator();
    }
    var handleIncrementer = function handleIncrementer() {
      switch (key) {
        case 'ArrowUp':
        case 'Up':
          e.preventDefault();
          makeStep();
          break;
        case 'ArrowDown':
        case 'Down':
          e.preventDefault();
          makeStep(true);
          break;
      }
    };
    if (hasIncrementer) {
      handleIncrementer();
    }
    _onKeyDown(e);
  };
  var internalOnChange = function internalOnChange(e) {
    if (isControlledWithoutOnChangeHandlerAndReadOnlyAttribute) return;
    var value = e.target.value,
      inputType = e.nativeEvent.inputType;
    var _getNewValueAndCursor = getNewValueAndCursorPosition(value, identifyPressedKey(decimalSeparatorKey, inputType, pressedKey, prevValue, value)),
      newValue = _getNewValueAndCursor.newValue,
      newCursorPosition = _getNewValueAndCursor.newCursorPosition;
    // Prevent cursor flickering
    e.target.value = newValue;
    setInputValue(newValue);
    adjustCursor(newCursorPosition);
    if (newValue !== prevValue) {
      externalOnChange(newValue);
    }
  };
  var internalOnBlur = function internalOnBlur(e) {
    var _unformat4 = unformat(locale, inputValue),
      integer = _unformat4.integer,
      fraction = _unformat4.fraction;
    var shouldValueBeCleared = inputValue === minus || inputValue === decimal || inputValue === "".concat(minus).concat(decimal);
    var shouldIntegerPartBeFilled = fraction.length > 0 && (integer === emptyString || integer === minus);
    var isDecimalSeparatorRedundant = verifiedDecimalScale > 0 && inputValue[inputValue.length - 1] === decimal && !fillDecimalScaleOnBlur;
    var isDecimalScaleNotFilled = verifiedDecimalScale - fraction.length > 0;
    var shouldDecimalScaleBeFilled = fillDecimalScaleOnBlur && isDecimalScaleNotFilled;
    if (shouldValueBeCleared || shouldIntegerPartBeFilled || isDecimalSeparatorRedundant || shouldDecimalScaleBeFilled) {
      var getNewValue = function getNewValue() {
        if (shouldValueBeCleared) {
          return emptyString;
        }
        if (shouldIntegerPartBeFilled) {
          var numberOfZerosToPad = verifiedDecimalScale - fraction.length;
          return "".concat(integer, "0").concat(decimal).concat(shouldDecimalScaleBeFilled ? fraction.concat(Array.from({
            length: numberOfZerosToPad
          }, function (_) {
            return '0';
          }).join(emptyString)) : fraction);
        }
        if (isDecimalSeparatorRedundant) {
          return inputValue.replace(new RegExp("[".concat(decimal, "]"), 'g'), emptyString);
        }
        if (shouldDecimalScaleBeFilled) {
          return format(locale, verifiedDecimalScale, 'always', inputValue);
        }
        return inputValue;
      };
      var newValue = getNewValue();
      setInputValue(newValue);
      externalOnChange(newValue);
    }
    _onBlur(e);
  };
  return /*#__PURE__*/React.createElement(StyledWrapper, {
    $hasIncrementer: hasIncrementer,
    "data-qa": qa === null || qa === void 0 ? void 0 : qa.wrapper
  }, /*#__PURE__*/React.createElement(StyledInput, _extends({
    value: inputValue,
    disabled: disabled,
    error: error,
    onKeyDown: internalOnKeyDown,
    onChange: internalOnChange,
    onBlur: internalOnBlur,
    inputMode: "numeric"
    // Chrome- InvalidStateError: Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input element's type ('number') does not support selection.
    // Firefox- Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable
    // type={hasIncrementer ? 'number' : undefined}
    ,
    lang: contextLocale,
    readOnly: readOnly,
    style: _objectSpread(_objectSpread({}, style), {
      paddingLeft: "".concat(inputPadding.left, "px"),
      paddingRight: "".concat(inputPadding.right, "px")
    })
  }, inputProps, props, {
    ref: mergeRefs(ref, inputRef)
  })), prefix && /*#__PURE__*/React.createElement(StyledPrefix, _extends({
    disabled: disabled
  }, prefixProps), prefix), suffix && /*#__PURE__*/React.createElement(StyledSuffix, _extends({
    $withIncrementer: hasIncrementer,
    disabled: disabled
  }, suffixProps), suffix), hasIncrementer && /*#__PURE__*/React.createElement(StyledIncrementerWrapper, null, /*#__PURE__*/React.createElement(StyledIncrementerButton, {
    "aria-hidden": "true",
    type: "button",
    disabled: disabled,
    tabIndex: -1,
    "data-qa": qa === null || qa === void 0 ? void 0 : qa.increment,
    onClick: function onClick() {
      return makeStep();
    }
  }, /*#__PURE__*/React.createElement(PlusIcon, null)), /*#__PURE__*/React.createElement(StyledIncrementerButton, {
    "aria-hidden": "true",
    type: "button",
    disabled: disabled,
    tabIndex: -1,
    "data-qa": qa === null || qa === void 0 ? void 0 : qa.decrement,
    onClick: function onClick() {
      return makeStep(true);
    }
  }, /*#__PURE__*/React.createElement(MinusIcon, null))));
});
NumberInput.displayName = 'NumberInput';
export var getCurrencyProps = function getCurrencyProps(locale, _decimalScale, symbol, currencyIsoCode, currencyDisplay) {
  var _parts$find, _parts$find2;
  var currencyOptions = {
    locale: locale,
    currencyIsoCode: currencyIsoCode || 'USD',
    currencyDisplay: currencyDisplay || 'narrowSymbol'
  };
  var parts = formatCurrencyToParts(1, currencyOptions);
  var formatterDecimalScale = ((_parts$find = parts.find(function (part) {
    return part.type === 'fraction';
  })) === null || _parts$find === void 0 ? void 0 : _parts$find.value.length) || 0;
  var decimalScale = _decimalScale || formatterDecimalScale;
  var placement = parts.findIndex(function (object) {
    return object.type === 'currency';
  }) < parts.findIndex(function (part) {
    return part.type === 'integer';
  }) ? 'prefix' : 'suffix';
  var currencyIsoSymbol = currencyIsoCode ? (_parts$find2 = parts.find(function (part) {
    return part.type === 'currency';
  })) === null || _parts$find2 === void 0 ? void 0 : _parts$find2.value.toString() : undefined;
  var currencyProps = placement === 'prefix' ? {
    decimalScale: decimalScale,
    prefix: currencyIsoSymbol || symbol || ''
  } : {
    decimalScale: decimalScale,
    suffix: currencyIsoSymbol || symbol || ''
  };
  return currencyProps;
};
export var CurrencyInput = /*#__PURE__*/React.forwardRef(function (_ref2, ref) {
  var currencyDisplay = _ref2.currencyDisplay,
    currencyIsoCode = _ref2.currencyIsoCode,
    _decimalScale = _ref2.decimalScale,
    _ref2$fillDecimalScal = _ref2.fillDecimalScale,
    fillDecimalScale = _ref2$fillDecimalScal === void 0 ? defaultCurrencyFillDecimalScale : _ref2$fillDecimalScal,
    _ref2$prefix = _ref2.prefix,
    prefix = _ref2$prefix === void 0 ? defaultCurrencyInputPrefix : _ref2$prefix,
    suffix = _ref2.suffix,
    props = _objectWithoutProperties(_ref2, _excluded2);
  var I18n = useI18nContext();
  var contextLocale = props.locale || I18n.locale || defaultLocale;
  var currencyProps = getCurrencyProps(contextLocale, _decimalScale, prefix || suffix, currencyIsoCode, currencyDisplay);
  return /*#__PURE__*/React.createElement(NumberInput, _extends({
    fillDecimalScale: fillDecimalScale
  }, props, currencyProps, {
    ref: ref
  }));
});
CurrencyInput.displayName = 'CurrencyInput';
//# sourceMappingURL=NumberInput.js.map