import { r as registerInstance, c as createEvent, h, H as Host, g as getElement } from './index-a0453e17.js';
import { a as defaultLocale, d as defaultConfig } from './initialize-7bec2c8a.js';
import { L as Logger } from './log-f87572ce.js';
import { L as ListenToConfig } from './config.decorator-6374c946.js';
import { h as inputHandleClick, a as inputHandleHostClick, i as inputHandleFocus, e as inputHandleBlur, f as inputHandleChange, k as getUpcomingValue, s as stopEventBubbling, b as inputListenOnClick, j as inputHandleReset, c as inputSetFocus, d as inputSetBlur, l as getNativeInputValue } from './form-input-1bff7eb7.js';
import { m as debounceEvent } from './helpers-008ae2b8.js';
import { i as inheritAttributes } from './attributes-7267db50.js';
import { g as useBalConfig } from './index-4143a4f7.js';
import { s as getDecimalSeparator$1, u as getThousandSeparator$1, q as formatLocaleNumber$1 } from './index.esm-3cf7e81b.js';
import { B as BEM } from './bem-c44dad2a.js';
import { d as defaultBalAriaForm } from './form-e0003a65.js';
import { l as lodash_isnil } from './index-82aff103.js';
import { N as NUMBER_KEYS, A as ACTION_KEYS } from './keys.constant-1eab1767.js';
import { l as lodash_isempty } from './index-14bbb131.js';
import './browser-216e7b03.js';
import './icons.constant-f579c326.js';
import './_commonjsHelpers-ba3f0406.js';

/**
 * lodash 3.0.2 (Custom Build) <https://lodash.com/>
 * Build: `lodash modularize exports="npm" -o ./`
 * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
 * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 * Available under MIT license <https://lodash.com/license>
 */

/** `Object#toString` result references. */
var numberTag = '[object Number]';

/** Used for built-in method references. */
var objectProto = Object.prototype;

/**
 * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
 * of values.
 */
var objectToString = objectProto.toString;

/**
 * Checks if `value` is object-like. A value is object-like if it's not `null`
 * and has a `typeof` result of "object".
 *
 * @static
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
 * @example
 *
 * _.isObjectLike({});
 * // => true
 *
 * _.isObjectLike([1, 2, 3]);
 * // => true
 *
 * _.isObjectLike(_.noop);
 * // => false
 *
 * _.isObjectLike(null);
 * // => false
 */
function isObjectLike(value) {
  return !!value && typeof value == 'object';
}

/**
 * Checks if `value` is `NaN`.
 *
 * **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4)
 * which returns `true` for `undefined` and other non-numeric values.
 *
 * @static
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
 * @example
 *
 * _.isNaN(NaN);
 * // => true
 *
 * _.isNaN(new Number(NaN));
 * // => true
 *
 * isNaN(undefined);
 * // => true
 *
 * _.isNaN(undefined);
 * // => false
 */
function isNaN(value) {
  // An `NaN` primitive is the only value that is not equal to itself.
  // Perform the `toStringTag` check first to avoid errors with some ActiveX objects in IE.
  return isNumber$1(value) && value != +value;
}

/**
 * Checks if `value` is classified as a `Number` primitive or object.
 *
 * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified
 * as numbers, use the `_.isFinite` method.
 *
 * @static
 * @memberOf _
 * @category Lang
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
 * @example
 *
 * _.isNumber(3);
 * // => true
 *
 * _.isNumber(Number.MIN_VALUE);
 * // => true
 *
 * _.isNumber(Infinity);
 * // => true
 *
 * _.isNumber('3');
 * // => false
 */
function isNumber$1(value) {
  return typeof value == 'number' ||
    (isObjectLike(value) && objectToString.call(value) == numberTag);
}

var lodash_isnan = isNaN;

const getLocale = () => {
  const config = useBalConfig();
  return (config && config.locale) || defaultLocale;
};
const getDecimalSeparator = () => {
  return getDecimalSeparator$1(getLocale());
};
const getThousandSeparator = () => {
  return getThousandSeparator$1(getLocale());
};
const formatLocaleNumber = (number, minimumFractionDigits) => {
  return formatLocaleNumber$1(getLocale(), number, minimumFractionDigits);
};
const getNegativeSymbol = () => {
  return '-';
};

function isNumber(value) {
  const num = parseFloat(value);
  return typeof num === 'number' && !lodash_isnan(num);
}
function isNotNumber(value) {
  return !isNumber(value) && value !== '' && value !== getNegativeSymbol() && value !== getDecimalSeparator();
}
function toNumber(value, decimalPoints = 0) {
  if (value === '' ||
    value === undefined ||
    value === null ||
    lodash_isnan(value) ||
    value === getNegativeSymbol() ||
    value === getDecimalSeparator() ||
    !isNumber(value)) {
    return undefined;
  }
  return decimalPoints === 0 ? parseInt(value, 10) : parseFloat(value);
}
function toFixedNumber(value, decimalPoints = 0) {
  if (lodash_isnil(value)) {
    return '';
  }
  if (value.charAt(0) === getDecimalSeparator()) {
    value = `0${value}`;
  }
  const num = decimalPoints === 0 ? parseInt(value, 10) : parseFloat(value.replace(getDecimalSeparator(), '.'));
  return lodash_isnan(num) ? '' : num.toFixed(decimalPoints);
}
function mapDecimalSeparator(value) {
  return value.replace('.', getDecimalSeparator());
}
function toUserFormattedNumber(value, decimalPoints = 0, suffix = '') {
  if (lodash_isnil(value)) {
    return '';
  }
  if (value.charAt(0) === getDecimalSeparator()) {
    value = `0${value}`;
  }
  const num = decimalPoints === 0 ? parseInt(value, 10) : parseFloat(value);
  const formattedSuffix = suffix !== '' ? ` ${suffix.trim()}` : '';
  return lodash_isnan(num) ? '' : formatLocaleNumber(num, decimalPoints) + formattedSuffix;
}
const countDecimalSeparators = (value) => (value.split(getDecimalSeparator()) || []).length - 1 || 0;
function validateKeyDown({ key, selectionStart, selectionEnd, newValue, decimal, }) {
  if (key === getNegativeSymbol() && selectionStart && selectionStart > 0 && selectionEnd && selectionEnd > 0) {
    return false;
  }
  if (key === getDecimalSeparator()) {
    if (decimal === 0) {
      return false;
    }
    else if (countDecimalSeparators(newValue) > 1) {
      return false;
    }
  }
  if (![...NUMBER_KEYS, ...ACTION_KEYS, getDecimalSeparator(), getNegativeSymbol()].includes(key)) {
    return false;
  }
  if (decimal !== 0 && newValue.includes(getDecimalSeparator()) && [...NUMBER_KEYS].includes(key)) {
    const newValueParts = newValue.split(getDecimalSeparator());
    const decimalPart = newValueParts[newValueParts.length - 1];
    if (decimalPart.length > decimal) {
      return false;
    }
  }
  return true;
}

const balNumberInputCss = ".bal-number-input{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;display:block;position:relative;-ms-flex:1;flex:1;-ms-flex-align:center;align-items:center;width:100%;padding:0;font-family:var(--bal-font-family-text)}";

var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
const NumberInput = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.balInput = createEvent(this, "balInput", 7);
    this.balChange = createEvent(this, "balChange", 7);
    this.balBlur = createEvent(this, "balBlur", 7);
    this.balFocus = createEvent(this, "balFocus", 7);
    this.balKeyPress = createEvent(this, "balKeyPress", 7);
    this.inputId = `bal-number-input-${numberInputIds++}`;
    this.inheritedAttributes = {};
    this.lastValue = '';
    this.inputValue = this.value;
    this.initialValue = undefined;
    this.onClick = (ev) => inputHandleClick(this, ev);
    this.handleClick = (ev) => inputHandleHostClick(this, ev);
    this.onInput = (_ev) => {
      var _a;
      if (this.nativeInput) {
        if (isNotNumber(this.nativeInput.value)) {
          this.nativeInputValue = this.lastValue || '';
          return;
        }
      }
      this.lastValue = ((_a = this.nativeInput) === null || _a === void 0 ? void 0 : _a.value) || '';
      this.balInput.emit(toNumber(this.lastValue, this.decimal));
    };
    this.onFocus = (ev) => {
      inputHandleFocus(this, ev);
      if (this.nativeInput) {
        this.nativeInputValue = mapDecimalSeparator(this.lastValue || '');
      }
    };
    this.onBlur = (ev) => {
      inputHandleBlur(this, ev);
      if (this.nativeInput) {
        this.lastValue = toFixedNumber(this.lastValueGetter, this.decimal);
        this.nativeInputValue = toUserFormattedNumber(this.lastValueGetter, this.decimal, this.suffix);
      }
      this.inputValue = toNumber(this.lastValueGetter, this.decimal);
      inputHandleChange(this);
    };
    this.onKeydown = (ev) => {
      const oldValue = getNativeInputValue(this);
      const newValue = getUpcomingValue(this, ev);
      const input = ev === null || ev === void 0 ? void 0 : ev.target;
      if (input &&
        !validateKeyDown({
          key: ev.key,
          decimal: this.decimal,
          newValue,
          oldValue,
          selectionStart: input.selectionStart,
          selectionEnd: input.selectionEnd,
        })) {
        return stopEventBubbling(ev);
      }
    };
    this.focused = false;
    this.language = defaultConfig.language;
    this.region = defaultConfig.region;
    this.ariaForm = defaultBalAriaForm;
    this.nativeInputValue = '';
    this.inputPattern = this.createPattern();
    this.name = this.inputId;
    this.invalid = false;
    this.decimal = 0;
    this.suffix = undefined;
    this.pattern = undefined;
    this.placeholder = undefined;
    this.required = false;
    this.disabled = false;
    this.readonly = false;
    this.exactNumber = false;
    this.max = undefined;
    this.min = undefined;
    this.debounce = 0;
    this.value = undefined;
  }
  createLogger(log) {
    this.log = log;
  }
  debounceChanged() {
    this.balChange = debounceEvent(this.balChange, this.debounce);
  }
  valueChanged(newValue, oldValue) {
    if (newValue !== oldValue) {
      const isValueNotDefined = newValue === '' || lodash_isnil(newValue) || lodash_isnan(newValue);
      const emptyValue = this.exactNumber ? '0' : '';
      const value = isValueNotDefined ? emptyValue : newValue.toString();
      this.inputValue = toNumber(toFixedNumber(value, this.decimal), this.decimal);
      this.lastValue = toFixedNumber(value, this.decimal);
      if (this.focused) {
        this.nativeInputValue = mapDecimalSeparator(this.lastValue);
      }
      else {
        this.nativeInputValue = toUserFormattedNumber(this.lastValue, this.decimal, this.suffix);
      }
    }
  }
  connectedCallback() {
    this.debounceChanged();
    this.initialValue = this.value || 0;
    if (this.value !== undefined) {
      this.valueChanged(this.value, undefined);
    }
  }
  componentDidLoad() {
    this.inputValue = this.value;
  }
  componentWillLoad() {
    this.inheritedAttributes = inheritAttributes(this.el, ['aria-label', 'tabindex', 'title']);
  }
  listenOnClick(ev) {
    inputListenOnClick(this, ev);
  }
  resetHandler(ev) {
    const formElement = ev.target;
    if (formElement === null || formElement === void 0 ? void 0 : formElement.contains(this.el)) {
      inputHandleReset(this, this.initialValue, this.resetHandlerTimer);
    }
  }
  async configChanged(state) {
    this.language = state.language;
    this.region = state.region;
    this.inputPattern = this.createPattern();
    if (this.nativeInput) {
      if (this.focused) {
        this.nativeInputValue = mapDecimalSeparator(this.lastValue);
      }
      else {
        this.nativeInputValue = toUserFormattedNumber(this.lastValue, this.decimal, this.suffix);
      }
    }
  }
  async setFocus() {
    inputSetFocus(this);
  }
  async setBlur() {
    inputSetBlur(this);
  }
  getInputElement() {
    return Promise.resolve(this.nativeInput);
  }
  async setAriaForm(ariaForm) {
    this.ariaForm = Object.assign({}, ariaForm);
  }
  createPattern() {
    if (this.pattern) {
      return this.pattern;
    }
    let suffix = this.suffix || '';
    if (suffix !== '') {
      suffix = ` ${suffix}`;
    }
    const thousandSeparator = getThousandSeparator();
    let decimalSeparator = getDecimalSeparator();
    if (decimalSeparator === ',') {
      decimalSeparator = '\\,';
    }
    return `-?\\d{1,3}(?:${thousandSeparator}\\d{3})*(?:\\${decimalSeparator}\\d{1,2})?(?:${suffix})?`;
  }
  get lastValueGetter() {
    if (this.exactNumber && (lodash_isnil(this.lastValue) || lodash_isempty(this.lastValue))) {
      return '0';
    }
    return this.lastValue;
  }
  render() {
    const block = BEM.block('number-input');
    return (h(Host, { onClick: this.handleClick, "aria-disabled": this.disabled ? 'true' : null, class: Object.assign({}, block.class()) }, h("input", Object.assign({ class: {
        'input': true,
        'is-disabled': this.disabled || this.readonly,
        'is-danger': this.invalid,
      }, "data-testid": "bal-number-input", ref: input => (this.nativeInput = input), id: this.ariaForm.controlId || this.inputId, "aria-labelledby": this.ariaForm.labelId, "aria-describedby": this.ariaForm.messageId, "aria-invalid": this.invalid === true ? 'true' : 'false', "aria-disabled": this.disabled ? 'true' : null, name: this.name, disabled: this.disabled, placeholder: this.placeholder || '', readonly: this.readonly, required: this.required, pattern: this.inputPattern, min: this.min, max: this.max, value: this.nativeInputValue, onInput: e => this.onInput(e), onFocus: e => this.onFocus(e), onBlur: e => this.onBlur(e), onClick: this.onClick, onKeyDown: e => this.onKeydown(e), onKeyPress: e => this.balKeyPress.emit(e) }, this.inheritedAttributes))));
  }
  get el() { return getElement(this); }
  static get watchers() { return {
    "debounce": ["debounceChanged"],
    "value": ["valueChanged"]
  }; }
};
__decorate([
  Logger('bal-number-input')
], NumberInput.prototype, "createLogger", null);
__decorate([
  ListenToConfig()
], NumberInput.prototype, "configChanged", null);
let numberInputIds = 0;
NumberInput.style = {
  css: balNumberInputCss
};

export { NumberInput as bal_number_input };
