'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var React = require('react');
var theme = require('@helpdice/theme');

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 _arrayWithHoles(r) {
  if (Array.isArray(r)) return r;
}
function _arrayWithoutHoles(r) {
  if (Array.isArray(r)) return _arrayLikeToArray(r);
}
function _defineProperty(e, r, t) {
  return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
    value: t,
    enumerable: true,
    configurable: true,
    writable: true
  }) : e[r] = t, e;
}
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 _iterableToArray(r) {
  if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
}
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 = true,
      o = false;
    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 = true, n = r;
    } finally {
      try {
        if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
      } finally {
        if (o) throw n;
      }
    }
    return a;
  }
}
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 _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
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 _objectSpread2(e) {
  for (var r = 1; r < arguments.length; r++) {
    var t = null != arguments[r] ? arguments[r] : {};
    r % 2 ? ownKeys(Object(t), true).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 _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;
}
function _slicedToArray(r, e) {
  return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function _toConsumableArray(r) {
  return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
}
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);
    if ("object" != typeof i) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r ? String : Number)(t);
}
function _toPropertyKey(t) {
  var i = _toPrimitive(t, "string");
  return "symbol" == typeof i ? i : i + "";
}
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;
  }
}

/**
 * Escape regex char
 *
 * See: https://stackoverflow.com/questions/17885855/use-dynamic-variable-string-as-regex-pattern-in-javascript
 */
var escapeRegExp = function escapeRegExp(stringToGoIntoTheRegex) {
  return stringToGoIntoTheRegex.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
};

var abbrMap = {
  k: 1000,
  m: 1000000,
  b: 1000000000
};

/**
 * Parse a value with abbreviation e.g 1k = 1000
 */
var parseAbbrValue = function parseAbbrValue(value) {
  var decimalSeparator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.';
  var reg = new RegExp("(\\d+(".concat(escapeRegExp(decimalSeparator), "\\d*)?)([kmb])$"), 'i');
  var match = value.match(reg);
  if (match) {
    var _match = _slicedToArray(match, 4),
      digits = _match[1],
      abbr = _match[3];
    var multiplier = abbrMap[abbr.toLowerCase()];
    return Number(digits.replace(decimalSeparator, '.')) * multiplier;
  }
  return undefined;
};

/**
 * Remove group separator from value eg. 1,000 > 1000
 */
var removeSeparators = function removeSeparators(value) {
  var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';
  var reg = new RegExp(escapeRegExp(separator), 'g');
  return value.replace(reg, '');
};

/**
 * Remove invalid characters
 */
var removeInvalidChars = function removeInvalidChars(value, validChars) {
  var chars = escapeRegExp(validChars.join(''));
  var reg = new RegExp("[^\\d".concat(chars, "]"), 'gi');
  return value.replace(reg, '');
};

/**
 * Remove prefix, separators and extra decimals from value
 */
var cleanValue = function cleanValue(_ref) {
  var value = _ref.value,
    _ref$groupSeparator = _ref.groupSeparator,
    groupSeparator = _ref$groupSeparator === void 0 ? ',' : _ref$groupSeparator,
    _ref$decimalSeparator = _ref.decimalSeparator,
    decimalSeparator = _ref$decimalSeparator === void 0 ? '.' : _ref$decimalSeparator,
    _ref$allowDecimals = _ref.allowDecimals,
    allowDecimals = _ref$allowDecimals === void 0 ? true : _ref$allowDecimals,
    _ref$decimalsLimit = _ref.decimalsLimit,
    decimalsLimit = _ref$decimalsLimit === void 0 ? 2 : _ref$decimalsLimit,
    _ref$allowNegativeVal = _ref.allowNegativeValue,
    allowNegativeValue = _ref$allowNegativeVal === void 0 ? true : _ref$allowNegativeVal,
    _ref$disableAbbreviat = _ref.disableAbbreviations,
    disableAbbreviations = _ref$disableAbbreviat === void 0 ? false : _ref$disableAbbreviat,
    _ref$prefix = _ref.prefix,
    prefix = _ref$prefix === void 0 ? '' : _ref$prefix,
    _ref$transformRawValu = _ref.transformRawValue,
    transformRawValue = _ref$transformRawValu === void 0 ? function (rawValue) {
      return rawValue;
    } : _ref$transformRawValu;
  var transformedValue = transformRawValue(value);
  if (transformedValue === '-') {
    return transformedValue;
  }
  var abbreviations = disableAbbreviations ? [] : ['k', 'm', 'b'];
  var reg = new RegExp("((^|\\D)-\\d)|(-".concat(escapeRegExp(prefix), ")"));
  var isNegative = reg.test(transformedValue);

  // Is there a digit before the prefix? eg. 1$
  var _ref2 = RegExp("(\\d+)-?".concat(escapeRegExp(prefix))).exec(value) || [],
    _ref3 = _slicedToArray(_ref2, 2),
    prefixWithValue = _ref3[0],
    preValue = _ref3[1];
  var withoutPrefix = prefix ? prefixWithValue ? transformedValue.replace(prefixWithValue, '').concat(preValue) : transformedValue.replace(prefix, '') : transformedValue;
  var withoutSeparators = removeSeparators(withoutPrefix, groupSeparator);
  var withoutInvalidChars = removeInvalidChars(withoutSeparators, [groupSeparator, decimalSeparator].concat(abbreviations));
  var valueOnly = withoutInvalidChars;
  if (!disableAbbreviations) {
    // disallow letter without number
    if (abbreviations.some(function (letter) {
      return letter === withoutInvalidChars.toLowerCase().replace(decimalSeparator, '');
    })) {
      return '';
    }
    var parsed = parseAbbrValue(withoutInvalidChars, decimalSeparator);
    if (parsed) {
      valueOnly = String(parsed);
    }
  }
  var includeNegative = isNegative && allowNegativeValue ? '-' : '';
  if (decimalSeparator && valueOnly.includes(decimalSeparator)) {
    var _withoutInvalidChars$ = withoutInvalidChars.split(decimalSeparator),
      _withoutInvalidChars$2 = _slicedToArray(_withoutInvalidChars$, 2),
      _int = _withoutInvalidChars$2[0],
      decimals = _withoutInvalidChars$2[1];
    var trimmedDecimals = decimalsLimit && decimals ? decimals.slice(0, decimalsLimit) : decimals;
    var includeDecimals = allowDecimals ? "".concat(decimalSeparator).concat(trimmedDecimals) : '';
    return "".concat(includeNegative).concat(_int).concat(includeDecimals);
  }
  return "".concat(includeNegative).concat(valueOnly);
};

var fixedDecimalValue = function fixedDecimalValue(value, decimalSeparator, fixedDecimalLength) {
  if (fixedDecimalLength !== undefined && value.length > 1) {
    if (fixedDecimalLength === 0) {
      return value.replace(decimalSeparator, '');
    }
    if (value.includes(decimalSeparator)) {
      var _value$split = value.split(decimalSeparator),
        _value$split2 = _slicedToArray(_value$split, 2),
        _int = _value$split2[0],
        decimals = _value$split2[1];
      if (decimals.length === fixedDecimalLength) {
        return value;
      }
      if (decimals.length > fixedDecimalLength) {
        return "".concat(_int).concat(decimalSeparator).concat(decimals.slice(0, fixedDecimalLength));
      }
    }
    var reg = value.length > fixedDecimalLength ? new RegExp("(\\d+)(\\d{".concat(fixedDecimalLength, "})")) : new RegExp("(\\d)(\\d+)");
    var match = value.match(reg);
    if (match) {
      var _match = _slicedToArray(match, 3),
        _int2 = _match[1],
        _decimals = _match[2];
      return "".concat(_int2).concat(decimalSeparator).concat(_decimals);
    }
  }
  return value;
};

var getSuffix = function getSuffix(value, _ref) {
  var _ref$groupSeparator = _ref.groupSeparator,
    groupSeparator = _ref$groupSeparator === void 0 ? ',' : _ref$groupSeparator,
    _ref$decimalSeparator = _ref.decimalSeparator,
    decimalSeparator = _ref$decimalSeparator === void 0 ? '.' : _ref$decimalSeparator;
  var suffixReg = new RegExp("\\d([^".concat(escapeRegExp(groupSeparator)).concat(escapeRegExp(decimalSeparator), "0-9]+)"));
  var suffixMatch = value.match(suffixReg);
  return suffixMatch ? suffixMatch[1] : undefined;
};

/**
 * Format value with decimal separator, group separator and prefix
 */
var formatValue = function formatValue(options) {
  var _value = options.value,
    decimalSeparator = options.decimalSeparator,
    intlConfig = options.intlConfig,
    decimalScale = options.decimalScale,
    _options$prefix = options.prefix,
    prefix = _options$prefix === void 0 ? '' : _options$prefix,
    _options$suffix = options.suffix,
    suffix = _options$suffix === void 0 ? '' : _options$suffix;
  if (_value === '' || _value === undefined) {
    return '';
  }
  if (_value === '-') {
    return '-';
  }
  var isNegative = new RegExp("^\\d?-".concat(prefix ? "".concat(escapeRegExp(prefix), "?") : '', "\\d")).test(_value);
  var value = decimalSeparator !== '.' ? replaceDecimalSeparator(_value, decimalSeparator, isNegative) : _value;
  if (decimalSeparator && decimalSeparator !== '-' && value.startsWith(decimalSeparator)) {
    value = '0' + value;
  }
  var defaultNumberFormatOptions = {
    minimumFractionDigits: decimalScale || 0,
    maximumFractionDigits: 20
  };
  var numberFormatter = intlConfig ? new Intl.NumberFormat(intlConfig.locale, intlConfig.currency ? _objectSpread2(_objectSpread2({}, defaultNumberFormatOptions), {}, {
    style: 'currency',
    currency: intlConfig.currency
  }) : defaultNumberFormatOptions) : new Intl.NumberFormat(undefined, defaultNumberFormatOptions);
  var parts = numberFormatter.formatToParts(Number(value));
  var formatted = replaceParts(parts, options);

  // Does intl formatting add a suffix?
  var intlSuffix = getSuffix(formatted, _objectSpread2({}, options));

  // Include decimal separator if user input ends with decimal separator
  var includeDecimalSeparator = _value.slice(-1) === decimalSeparator ? decimalSeparator : '';
  var _ref = value.match(RegExp('\\d+\\.(\\d+)')) || [],
    _ref2 = _slicedToArray(_ref, 2),
    decimals = _ref2[1];

  // Keep original decimal padding if no decimalScale
  if (decimalScale === undefined && decimals && decimalSeparator) {
    if (formatted.includes(decimalSeparator)) {
      formatted = formatted.replace(RegExp("(\\d+)(".concat(escapeRegExp(decimalSeparator), ")(\\d+)"), 'g'), "$1$2".concat(decimals));
    } else {
      if (intlSuffix && !suffix) {
        formatted = formatted.replace(intlSuffix, "".concat(decimalSeparator).concat(decimals).concat(intlSuffix));
      } else {
        formatted = "".concat(formatted).concat(decimalSeparator).concat(decimals);
      }
    }
  }
  if (suffix && includeDecimalSeparator) {
    return "".concat(formatted).concat(includeDecimalSeparator).concat(suffix);
  }
  if (intlSuffix && includeDecimalSeparator) {
    return formatted.replace(intlSuffix, "".concat(includeDecimalSeparator).concat(intlSuffix));
  }
  if (intlSuffix && suffix) {
    return formatted.replace(intlSuffix, "".concat(includeDecimalSeparator).concat(suffix));
  }
  return [formatted, includeDecimalSeparator, suffix].join('');
};

/**
 * Before converting to Number, decimal separator has to be .
 */
var replaceDecimalSeparator = function replaceDecimalSeparator(value, decimalSeparator, isNegative) {
  var newValue = value;
  if (decimalSeparator && decimalSeparator !== '.') {
    newValue = newValue.replace(RegExp(escapeRegExp(decimalSeparator), 'g'), '.');
    if (isNegative && decimalSeparator === '-') {
      newValue = "-".concat(newValue.slice(1));
    }
  }
  return newValue;
};
var replaceParts = function replaceParts(parts, _ref3) {
  var prefix = _ref3.prefix,
    groupSeparator = _ref3.groupSeparator,
    decimalSeparator = _ref3.decimalSeparator,
    decimalScale = _ref3.decimalScale,
    _ref3$disableGroupSep = _ref3.disableGroupSeparators,
    disableGroupSeparators = _ref3$disableGroupSep === void 0 ? false : _ref3$disableGroupSep;
  return parts.reduce(function (prev, _ref4, i) {
    var type = _ref4.type,
      value = _ref4.value;
    if (i === 0 && prefix) {
      if (type === 'minusSign') {
        return [value, prefix];
      }
      if (type === 'currency') {
        return [].concat(_toConsumableArray(prev), [prefix]);
      }
      return [prefix, value];
    }
    if (type === 'currency') {
      return prefix ? prev : [].concat(_toConsumableArray(prev), [value]);
    }
    if (type === 'group') {
      return !disableGroupSeparators ? [].concat(_toConsumableArray(prev), [groupSeparator !== undefined ? groupSeparator : value]) : prev;
    }
    if (type === 'decimal') {
      if (decimalScale !== undefined && decimalScale === 0) {
        return prev;
      }
      return [].concat(_toConsumableArray(prev), [decimalSeparator !== undefined ? decimalSeparator : value]);
    }
    if (type === 'fraction') {
      return [].concat(_toConsumableArray(prev), [decimalScale !== undefined ? value.slice(0, decimalScale) : value]);
    }
    return [].concat(_toConsumableArray(prev), [value]);
  }, ['']).join('');
};

var defaultConfig = {
  currencySymbol: '',
  groupSeparator: '',
  decimalSeparator: '',
  prefix: '',
  suffix: ''
};

/**
 * Get locale config from input or default
 */
var getLocaleConfig = function getLocaleConfig(intlConfig) {
  var _ref = intlConfig || {},
    locale = _ref.locale,
    currency = _ref.currency;
  var numberFormatter = locale ? new Intl.NumberFormat(locale, currency ? {
    currency: currency,
    style: 'currency'
  } : undefined) : new Intl.NumberFormat();
  return numberFormatter.formatToParts(1000.1).reduce(function (prev, curr, i) {
    if (curr.type === 'currency') {
      if (i === 0) {
        return _objectSpread2(_objectSpread2({}, prev), {}, {
          currencySymbol: curr.value,
          prefix: curr.value
        });
      } else {
        return _objectSpread2(_objectSpread2({}, prev), {}, {
          currencySymbol: curr.value,
          suffix: curr.value
        });
      }
    }
    if (curr.type === 'group') {
      return _objectSpread2(_objectSpread2({}, prev), {}, {
        groupSeparator: curr.value
      });
    }
    if (curr.type === 'decimal') {
      return _objectSpread2(_objectSpread2({}, prev), {}, {
        decimalSeparator: curr.value
      });
    }
    return prev;
  }, defaultConfig);
};

var isNumber = function isNumber(input) {
  return RegExp(/\d/, 'gi').test(input);
};

var padTrimValue = function padTrimValue(value) {
  var decimalSeparator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.';
  var decimalScale = arguments.length > 2 ? arguments[2] : undefined;
  if (decimalScale === undefined || value === '' || value === undefined) {
    return value;
  }
  if (!value.match(/\d/g)) {
    return '';
  }
  var _value$split = value.split(decimalSeparator),
    _value$split2 = _slicedToArray(_value$split, 2),
    _int = _value$split2[0],
    decimals = _value$split2[1];
  if (decimalScale === 0) {
    return _int;
  }
  var newValue = decimals || '';
  if (newValue.length < decimalScale) {
    while (newValue.length < decimalScale) {
      newValue += '0';
    }
  } else {
    newValue = newValue.slice(0, decimalScale);
  }
  return "".concat(_int).concat(decimalSeparator).concat(newValue);
};

/**
 * Based on the last key stroke and the cursor position, update the value
 * and reposition the cursor to the right place
 */
var repositionCursor = function repositionCursor(_ref) {
  var selectionStart = _ref.selectionStart,
    value = _ref.value,
    lastKeyStroke = _ref.lastKeyStroke,
    stateValue = _ref.stateValue,
    groupSeparator = _ref.groupSeparator;
  var cursorPosition = selectionStart;
  var modifiedValue = value;
  if (stateValue && cursorPosition) {
    var splitValue = value.split('');
    // if cursor is to right of groupSeparator and backspace pressed, delete the character to the left of the separator and reposition the cursor
    if (lastKeyStroke === 'Backspace' && stateValue[cursorPosition] === groupSeparator) {
      splitValue.splice(cursorPosition - 1, 1);
      cursorPosition -= 1;
    }
    // if cursor is to left of groupSeparator and delete pressed, delete the character to the right of the separator and reposition the cursor
    if (lastKeyStroke === 'Delete' && stateValue[cursorPosition] === groupSeparator) {
      splitValue.splice(cursorPosition, 1);
      cursorPosition += 1;
    }
    modifiedValue = splitValue.join('');
    return {
      modifiedValue: modifiedValue,
      cursorPosition: cursorPosition
    };
  }
  return {
    modifiedValue: modifiedValue,
    cursorPosition: selectionStart
  };
};

var _excluded = ["allowDecimals", "allowNegativeValue", "id", "name", "className", "customInput", "decimalsLimit", "defaultValue", "disabled", "maxLength", "value", "onValueChange", "fixedDecimalLength", "placeholder", "decimalScale", "prefix", "suffix", "intlConfig", "step", "min", "max", "disableGroupSeparators", "disableAbbreviations", "decimalSeparator", "groupSeparator", "onChange", "onFocus", "onBlur", "onKeyDown", "onKeyUp", "transformRawValue", "formatValueOnBlur", "children"];
var InputCurrency = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
  var _ref$allowDecimals = _ref.allowDecimals,
    allowDecimals = _ref$allowDecimals === void 0 ? true : _ref$allowDecimals,
    _ref$allowNegativeVal = _ref.allowNegativeValue,
    allowNegativeValue = _ref$allowNegativeVal === void 0 ? true : _ref$allowNegativeVal,
    id = _ref.id,
    name = _ref.name,
    className = _ref.className,
    customInput = _ref.customInput,
    decimalsLimit = _ref.decimalsLimit,
    defaultValue = _ref.defaultValue,
    _ref$disabled = _ref.disabled,
    disabled = _ref$disabled === void 0 ? false : _ref$disabled,
    userMaxLength = _ref.maxLength,
    userValue = _ref.value,
    onValueChange = _ref.onValueChange,
    fixedDecimalLength = _ref.fixedDecimalLength,
    placeholder = _ref.placeholder,
    decimalScale = _ref.decimalScale,
    prefix = _ref.prefix,
    suffix = _ref.suffix,
    intlConfig = _ref.intlConfig,
    step = _ref.step,
    min = _ref.min,
    max = _ref.max,
    _ref$disableGroupSepa = _ref.disableGroupSeparators,
    disableGroupSeparators = _ref$disableGroupSepa === void 0 ? false : _ref$disableGroupSepa,
    _ref$disableAbbreviat = _ref.disableAbbreviations,
    disableAbbreviations = _ref$disableAbbreviat === void 0 ? false : _ref$disableAbbreviat,
    _decimalSeparator = _ref.decimalSeparator,
    _groupSeparator = _ref.groupSeparator,
    onChange = _ref.onChange,
    onFocus = _ref.onFocus,
    onBlur = _ref.onBlur,
    onKeyDown = _ref.onKeyDown,
    onKeyUp = _ref.onKeyUp,
    transformRawValue = _ref.transformRawValue,
    _ref$formatValueOnBlu = _ref.formatValueOnBlur,
    formatValueOnBlur = _ref$formatValueOnBlu === void 0 ? true : _ref$formatValueOnBlu,
    children = _ref.children,
    props = _objectWithoutProperties(_ref, _excluded);
  var theme$1 = theme.useTheme();
  if (_decimalSeparator && isNumber(_decimalSeparator)) {
    throw new Error('decimalSeparator cannot be a number');
  }
  if (_groupSeparator && isNumber(_groupSeparator)) {
    throw new Error('groupSeparator cannot be a number');
  }
  var localeConfig = React.useMemo(function () {
    return getLocaleConfig(intlConfig);
  }, [intlConfig]);
  var decimalSeparator = _decimalSeparator || localeConfig.decimalSeparator || '';
  var groupSeparator = _groupSeparator || localeConfig.groupSeparator || '';
  if (decimalSeparator && groupSeparator && decimalSeparator === groupSeparator && disableGroupSeparators === false) {
    throw new Error('decimalSeparator cannot be the same as groupSeparator');
  }
  var formatValueOptions = {
    decimalSeparator: decimalSeparator,
    groupSeparator: groupSeparator,
    disableGroupSeparators: disableGroupSeparators,
    intlConfig: intlConfig,
    prefix: prefix || localeConfig.prefix,
    suffix: suffix
  };
  var cleanValueOptions = {
    decimalSeparator: decimalSeparator,
    groupSeparator: groupSeparator,
    allowDecimals: allowDecimals,
    decimalsLimit: decimalsLimit || fixedDecimalLength || 2,
    allowNegativeValue: allowNegativeValue,
    disableAbbreviations: disableAbbreviations,
    prefix: prefix || localeConfig.prefix,
    transformRawValue: transformRawValue
  };
  var _useState = React.useState(function () {
      return defaultValue != null ? formatValue(_objectSpread2(_objectSpread2({}, formatValueOptions), {}, {
        decimalScale: decimalScale,
        value: String(defaultValue)
      })) : userValue != null ? formatValue(_objectSpread2(_objectSpread2({}, formatValueOptions), {}, {
        decimalScale: decimalScale,
        value: String(userValue)
      })) : '';
    }),
    _useState2 = _slicedToArray(_useState, 2),
    stateValue = _useState2[0],
    setStateValue = _useState2[1];
  var _useState3 = React.useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    dirty = _useState4[0],
    setDirty = _useState4[1];
  var _useState5 = React.useState(0),
    _useState6 = _slicedToArray(_useState5, 2),
    cursor = _useState6[0],
    setCursor = _useState6[1];
  var _useState7 = React.useState(0),
    _useState8 = _slicedToArray(_useState7, 2),
    changeCount = _useState8[0],
    setChangeCount = _useState8[1];
  var _useState9 = React.useState(null),
    _useState0 = _slicedToArray(_useState9, 2),
    lastKeyStroke = _useState0[0],
    setLastKeyStroke = _useState0[1];
  var inputRef = React.useRef(null);
  React.useImperativeHandle(ref, function () {
    return inputRef.current;
  });

  /**
   * Process change in value
   */
  var processChange = function processChange(value, selectionStart) {
    setDirty(true);
    var _repositionCursor = repositionCursor({
        selectionStart: selectionStart,
        value: value,
        lastKeyStroke: lastKeyStroke,
        stateValue: stateValue,
        groupSeparator: groupSeparator
      }),
      modifiedValue = _repositionCursor.modifiedValue,
      cursorPosition = _repositionCursor.cursorPosition;
    var stringValue = cleanValue(_objectSpread2({
      value: modifiedValue
    }, cleanValueOptions));
    if (userMaxLength && stringValue.replace(/-/g, '').length > userMaxLength) {
      return;
    }
    if (stringValue === '' || stringValue === '-' || stringValue === decimalSeparator) {
      onValueChange && onValueChange(undefined, name, {
        "float": null,
        formatted: '',
        value: ''
      });
      setStateValue(stringValue);
      // Always sets cursor after '-' or decimalSeparator input
      setCursor(1);
      return;
    }
    var stringValueWithoutSeparator = decimalSeparator ? stringValue.replace(decimalSeparator, '.') : stringValue;
    var numberValue = parseFloat(stringValueWithoutSeparator);
    var formattedValue = formatValue(_objectSpread2({
      value: stringValue
    }, formatValueOptions));
    if (cursorPosition != null) {
      // Prevent cursor jumping
      var newCursor = cursorPosition + (formattedValue.length - value.length);
      newCursor = newCursor <= 0 ? prefix ? prefix.length : 0 : newCursor;
      setCursor(newCursor);
      setChangeCount(changeCount + 1);
    }
    setStateValue(formattedValue);
    if (onValueChange) {
      var values = {
        "float": numberValue,
        formatted: formattedValue,
        value: stringValue
      };
      onValueChange(stringValue, name, values);
    }
  };

  /**
   * Handle change event
   */
  var handleOnChange = function handleOnChange(event) {
    var _event$target = event.target,
      value = _event$target.value,
      selectionStart = _event$target.selectionStart;
    processChange(value, selectionStart);
    onChange && onChange(event);
  };

  /**
   * Handle focus event
   */
  var handleOnFocus = function handleOnFocus(event) {
    onFocus && onFocus(event);
    return stateValue ? stateValue.length : 0;
  };

  /**
   * Handle blur event
   *
   * Format value by padding/trimming decimals if required by
   */
  var handleOnBlur = function handleOnBlur(event) {
    var value = event.target.value;
    var valueOnly = cleanValue(_objectSpread2({
      value: value
    }, cleanValueOptions));
    if (valueOnly === '-' || valueOnly === decimalSeparator || !valueOnly) {
      setStateValue('');
      onBlur && onBlur(event);
      return;
    }
    var fixedDecimals = fixedDecimalValue(valueOnly, decimalSeparator, fixedDecimalLength);
    var newValue = padTrimValue(fixedDecimals, decimalSeparator, decimalScale !== undefined ? decimalScale : fixedDecimalLength);
    var numberValue = parseFloat(newValue.replace(decimalSeparator, '.'));
    var formattedValue = formatValue(_objectSpread2(_objectSpread2({}, formatValueOptions), {}, {
      value: newValue
    }));
    if (onValueChange && formatValueOnBlur) {
      onValueChange(newValue, name, {
        "float": numberValue,
        formatted: formattedValue,
        value: newValue
      });
    }
    setStateValue(formattedValue);
    onBlur && onBlur(event);
  };

  /**
   * Handle key down event
   *
   * Increase or decrease value by step
   */
  var handleOnKeyDown = function handleOnKeyDown(event) {
    var key = event.key;
    setLastKeyStroke(key);
    if (step && (key === 'ArrowUp' || key === 'ArrowDown')) {
      event.preventDefault();
      setCursor(stateValue.length);
      var currentValue = parseFloat(userValue != null ? String(userValue).replace(decimalSeparator, '.') : cleanValue(_objectSpread2({
        value: stateValue
      }, cleanValueOptions))) || 0;
      var newValue = key === 'ArrowUp' ? currentValue + step : currentValue - step;
      if (min !== undefined && newValue < Number(min)) {
        return;
      }
      if (max !== undefined && newValue > Number(max)) {
        return;
      }
      var fixedLength = String(step).includes('.') ? Number(String(step).split('.')[1].length) : undefined;
      processChange(String(fixedLength ? newValue.toFixed(fixedLength) : newValue).replace('.', decimalSeparator));
    }
    onKeyDown && onKeyDown(event);
  };

  /**
   * Handle key up event
   *
   * Move cursor if there is a suffix to prevent user typing past suffix
   */
  var handleOnKeyUp = function handleOnKeyUp(event) {
    var key = event.key,
      selectionStart = event.currentTarget.selectionStart;
    if (key !== 'ArrowUp' && key !== 'ArrowDown' && stateValue !== '-') {
      var _suffix = getSuffix(stateValue, {
        groupSeparator: groupSeparator,
        decimalSeparator: decimalSeparator
      });
      if (_suffix && selectionStart && selectionStart > stateValue.length - _suffix.length) {
        /* istanbul ignore else */
        if (inputRef.current) {
          var newCursor = stateValue.length - _suffix.length;
          inputRef.current.setSelectionRange(newCursor, newCursor);
        }
      }
    }
    onKeyUp && onKeyUp(event);
  };

  // Update state if userValue changes to undefined
  React.useEffect(function () {
    if (userValue == null && defaultValue == null) {
      setStateValue('');
    }
  }, [defaultValue, userValue]);
  React.useEffect(function () {
    // prevent cursor jumping if editing value
    if (dirty && stateValue !== '-' && inputRef.current && document.activeElement === inputRef.current) {
      inputRef.current.setSelectionRange(cursor, cursor);
    }
  }, [stateValue, cursor, inputRef, dirty, changeCount]);

  /**
   * If user has only entered "-" or decimal separator,
   * keep the char to allow them to enter next value
   */
  var getRenderValue = function getRenderValue() {
    if (userValue != null && stateValue !== '-' && (!decimalSeparator || stateValue !== decimalSeparator)) {
      return formatValue(_objectSpread2(_objectSpread2({}, formatValueOptions), {}, {
        decimalScale: dirty ? undefined : decimalScale,
        value: String(userValue)
      }));
    }
    return stateValue;
  };
  var inputProps = _objectSpread2({
    type: 'text',
    inputMode: 'decimal',
    id: id,
    name: name,
    className: className,
    onChange: handleOnChange,
    onBlur: handleOnBlur,
    onFocus: handleOnFocus,
    onKeyDown: handleOnKeyDown,
    onKeyUp: handleOnKeyUp,
    placeholder: placeholder,
    disabled: disabled,
    value: getRenderValue(),
    ref: inputRef
  }, props);
  if (customInput) {
    var CustomInput = customInput;
    return /*#__PURE__*/React.createElement(CustomInput, inputProps);
  }
  return /*#__PURE__*/React.createElement("div", null, children && /*#__PURE__*/React.createElement("label", {
    style: {
      display: 'block',
      marginBottom: '0.7rem',
      fontSize: '14px',
      fontWeight: 'light'
    }
  }, children), /*#__PURE__*/React.createElement("input", _extends({}, inputProps, {
    style: {
      textAlign: 'right',
      border: "1px solid ".concat(theme$1.palette.border),
      fontSize: '14px',
      borderRadius: '5px',
      height: '35px',
      padding: '5px 10px',
      fontWeight: 'light',
      width: 'auto',
      background: 'transparent',
      minWidth: '200px'
    }
  })));
});

exports.cleanValue = cleanValue;
exports.default = InputCurrency;
exports.formatValue = formatValue;
