import * as i0 from '@angular/core';
import { inject, ElementRef, Renderer2, LOCALE_ID, PLATFORM_ID, booleanAttribute, numberAttribute, HostListener, Input, HostBinding, Component, forwardRef, Directive, NgModule } from '@angular/core';
import { injectOptional, LocaleService } from '@eui/core';
import { coerceNumberProperty, coerceBooleanProperty } from '@angular/cdk/coercion';
import Cleave from 'cleave.js';
import { InputDirective } from '@eui/components/shared';
import { DOCUMENT, isPlatformBrowser, isPlatformServer } from '@angular/common';
import * as i1 from '@eui/components/directives';
import { EuiClearableDirective, EuiLoadingDirective } from '@eui/components/directives';
import { NgControl, NG_VALUE_ACCESSOR } from '@angular/forms';

/**
 * Get the decimal separator based on the locale
 *
 * @param locale value of the locale based on ISO 639-1
 */
function getDecimal(locale) {
    return new Intl.NumberFormat(locale).format(1.1).charAt(1);
}
/**
 * Get the group separator based on the locale
 *
 * @param locale value of the locale based on ISO 639-1
 */
function getGroup(locale) {
    return new Intl.NumberFormat(locale, { useGrouping: true }).format(1000).charAt(1);
}
/**
 * Input number component that allows the user to enter a number. It supports number
 * formatting and validation. It uses Cleave.js to format the number. It depends on
 * the {@link LocaleService} to get the current locale and format the number accordingly.
 *
 * It supports the following attributes:
 * - {@link min}: The minimum number can be entered. Blocks user's input if not in range.
 * - {@link max}: The maximum number can be entered. Blocks user's input if not in range.
 * - {@link leadingZero}: Adds leading zero to a number. Formatting will not work.
 * - {@link isInvalid}: Sets the invalid state of the input element.
 * - {@link fractionDigits}: Determines how many digits to show after the decimal point.
 * - {@link digits}: Determines how many digits to show before the decimal point.
 * - {@link fillFraction}: Fills the decimal part with zeros in case it's less than the fractionDigits.
 * - {@link roundUp}: Rounds a number with more than two decimals UP.
 * - {@link noFormat}: Disables the number formatting. It will be treated as a plain number.
 * - {@link value}: The value of the input element.
 * - {@link placeholder}: The placeholder value of the input element.
 * - {@link euiClearable}: Adds a clear button to the input element.
 * - {@link euiLoading}: Adds a loading spinner to the input element.
 * - {@link readonly}: Disables the input element.
 * - {@link disabled}: Disables the input element.
 * - {@link euiDanger}: Sets the invalid state of the input element.
 * - {@link euiSuccess}: Sets the success state of the input element.
 * - {@link euiWarning}: Sets the warning state of the input element.
 * - {@link euiInfo}: Sets the info state of the input element.
 * - {@link euiPrimary}: Sets the primary state of the input element.
 * - {@link euiSecondary}: Sets the secondary state of the input element.
 *
 */
class EuiInputNumberComponent extends InputDirective {
    get isInvalid() {
        return this._isInvalid || null;
    }
    set isInvalid(state) {
        this.setInvalid(state);
    }
    /**
     * CSS classes to be added to the host element.
     */
    get cssClasses() {
        return [super.getCssClasses('eui-input-number'), this._isInvalid ? 'eui-input-number--invalid' : ''].join(' ').trim();
    }
    /**
     *  determines how many digits to show after the decimal point
     */
    // TODO: transform to signal attribute
    get fractionDigits() {
        return this._fractionDigits;
    }
    set fractionDigits(value) {
        this._fractionDigits = coerceNumberProperty(value);
    }
    constructor() {
        super();
        /**
         * Adds leading zero to a number. Formatting will not work.
         *      e.g. with leadingZero=3 input number 5 => 005
         */
        // TODO: transform to signal attribute
        this.leadingZero = 0;
        this.type = 'eui-number';
        this._elementRef = inject(ElementRef);
        this._renderer = inject(Renderer2);
        this._fractionDigits = 0;
        this.localeService = injectOptional(LocaleService);
        this.locale_id = inject(LOCALE_ID);
        this.document = inject(DOCUMENT);
        this.platformId = inject(PLATFORM_ID);
        this.onChange = (_) => {
            if (this.control && (_ !== null || _ !== undefined)) {
                // parse number
                // const value = Number(_);
                // run on next MicroTask to avoid NG0100 error TODO: deeper investigation
                // Promise.resolve().then(() => this.control.viewToModelUpdate(value));
                // in case control is FormControl
                // this.control?.control.setValue(isNaN(value) ? null : value, { emitEvent: false, emitModelToViewChange: false });
            }
        };
        this.onTouched = () => {
            this.control?.control.markAsTouched();
        };
        const locale_id = this.locale_id;
        // set default options
        this.options = {
            numeral: true,
            delimiter: getGroup(locale_id || 'en'),
            numeralDecimalMark: getDecimal(locale_id || 'en'),
            numeralDecimalScale: this.fractionDigits,
            numeralIntegerScale: this.digits,
        };
    }
    ngOnInit() {
        super.ngOnInit();
        this.control = this.injector.get(NgControl, undefined, { optional: true });
        // instantiate cleave
        if (!this.control) {
            this.initCleave();
        }
        // subscribe to localization service and listen for locale change. De-construction of locale should happen here!
        this.localeService?.getState().subscribe((state) => {
            this.options = this.getCleaveOptsBasedOnLocale(state?.id);
            // update the options on the cleave instance
            this.updateOptions(true);
        });
        this._renderer.setProperty(this._elementRef.nativeElement, 'rootClassName', 'eui-input-number');
    }
    ngDoCheck() {
        if (!this.control) {
            this.control = this.injector.get(NgControl, undefined, { optional: true });
        }
        this.isInvalid = this.control ? this.control.invalid && this.control.touched : this._isInvalid;
    }
    ngOnChanges(changes) {
        if (Object.hasOwn(changes, 'value')) {
            this._elementRef.nativeElement.value = this.value;
            if (this.cleaveInstance) {
                this.cleaveInstance.setRawValue(this.value);
            }
        }
        if (Object.hasOwn(changes, 'fractionDigits')) {
            this.options = { ...this.options, numeralDecimalScale: this.fractionDigits };
            this.updateOptions();
        }
        if (Object.hasOwn(changes, 'noFormat')) {
            this.options = { ...this.options, numeralThousandsGroupStyle: this.noFormat ? 'none' : 'thousand' };
            this.updateOptions();
        }
        if (Object.hasOwn(changes, 'fillFraction') && this.cleaveInstance) {
            this.applyFractionFill(this.cleaveInstance.getRawValue());
        }
        if (Object.hasOwn(changes, 'digits')) {
            this.options = { ...this.options, numeralIntegerScale: this.digits };
            this.updateOptions();
        }
        if (Object.hasOwn(changes, 'min')) {
            this.min = changes['min'].currentValue;
            if (changes['min'].currentValue >= 0) {
                if (this.cleaveInstance) {
                    // take care of the sign symbol
                    this.cleaveInstance.setRawValue(Math.abs(Number(this.cleaveInstance.getRawValue())).toString());
                }
            }
        }
        if (Object.hasOwn(changes, 'max')) {
            this.max = changes['max'].currentValue;
            // check if current value is in range
            if (this.cleaveInstance) {
                const number = Number(this.cleaveInstance.getRawValue());
                if (number > this.max) {
                    this.cleaveInstance.setRawValue(this.max.toString());
                }
            }
        }
        if (Object.hasOwn(changes, 'roundUp')) {
            if (changes['roundUp'].currentValue > 0) {
                if (this.cleaveInstance) {
                    let number = this.parseNumber(this.cleaveInstance.getRawValue(), false, false);
                    number = this.decimalAdjust(number, this.roundUp);
                    this.cleaveInstance.setRawValue(number.toString());
                }
            }
        }
        if (Object.hasOwn(changes, 'placeholder')) {
            // parse number
            const number = this.parseNumber(changes['placeholder'].currentValue?.toString() || undefined);
            // set placeholder in case none is provided
            this.setPlaceholderAttribute(!this.isItaNumber(number.toString()) ? changes['placeholder'].currentValue : number);
        }
    }
    ngOnDestroy() {
        super.ngOnDestroy();
        // destroy cleave instance
        if (this.cleaveInstance) {
            this.cleaveInstance.destroy();
        }
    }
    onPaste(event) {
        // get the value from clipboard
        const value = (event.clipboardData || window['clipboardData']).getData('text');
        // in case round UP is enabled
        if (this.roundUp > 0) {
            const div = this.document.createElement('input');
            // create a clone of cleaveInstance
            const cloneInstance = new Cleave(div, { ...this.options, numeralDecimalScale: 8 });
            cloneInstance.setRawValue(value.toString());
            let number = this.parseNumber(cloneInstance.getRawValue(), false, false);
            number = this.decimalAdjust(number, this.roundUp);
            if (this.isItaNumber(number.toString())) {
                // TODO: investigate in the future how can this be avoided
                setTimeout(() => {
                    this.cleaveInstance.setRawValue(number.toString());
                    // this.writeValue(number.toString());
                }, 0);
            }
        }
    }
    onKeyDown(e) {
        // check if it's a single symbol and not Special like (Ctrl, backspace etc.)
        if (e?.key?.length <= 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {
            // stop event propagation if key pressed is not a number or locale character or minus sign
            if (Number.isNaN(Number.parseInt(e.key, 10)) &&
                this.isMinusAllowed(e.key) &&
                e.key !== getDecimal(this.localeService?.currentLocale || this.locale_id)) {
                e.stopPropagation();
                e.preventDefault();
                // stop event propagation if key pressed exceeds the min/max value range
            }
            else if (!Number.isNaN(Number.parseInt(e.key, 10)) && this.isOutSideRange(e)) {
                e.stopPropagation();
                e.preventDefault();
            }
            else if (this.isOutSideRange(e)) {
                e.stopPropagation();
                e.preventDefault();
            }
        }
        // protect decimal symbol deletion in case fillFraction is on
        if (e.key === 'Delete' || e.key === 'Backspace') {
            const element = this._elementRef.nativeElement;
            // position of caret
            const pos = element.selectionStart;
            // get character about to be deleted
            const char = element.value.charAt(pos - 1);
            // in case the char is the decimal symbol prevent deletion and move caret in front
            if (this.fillFraction &&
                char === getDecimal(this.localeService?.currentLocale || this.locale_id)) {
                e.stopPropagation();
                e.preventDefault();
                element.setSelectionRange(pos - 1, pos - 1);
            }
            else if (this.isOutSideRange(e)) {
                // don't allow insertion that will put number out of range
                e.stopPropagation();
                e.preventDefault();
            }
        }
    }
    onFocusout() {
        // in case fillFraction feature is on and there's no integer part add leading 0
        if (this.fillFraction && this.cleaveInstance.getRawValue().match(/^\.[0-9]+/g)) {
            this.cleaveInstance.setRawValue('0' + this.cleaveInstance.getRawValue());
        }
        // in case round UP is enabled
        if (this.roundUp > 0) {
            const number = this.parseNumber(this.cleaveInstance.getRawValue(), false, false);
            this.cleaveInstance.setRawValue(this.decimalAdjust(number, this.roundUp).toString());
        }
        // in case min is set and value is less than min reset to the min value
        if (this.min !== null && this.min !== undefined && Number.parseFloat(this.cleaveInstance.getRawValue()) < this.min) {
            this.cleaveInstance.setRawValue(this.min.toString());
        }
        // in case max is set and value is greater than max reset to the max value
        if (this.max !== null && this.max !== undefined && Number.parseFloat(this.cleaveInstance.getRawValue()) > this.max) {
            this.cleaveInstance.setRawValue(this.max.toString());
        }
    }
    /**
     * @Override setInvalid setInvalidAttribute of InputDirective
     * Sets the invalid state of the input element.
     *
     * @param state
     */
    setInvalid(state) {
        // in case it's controlled by NgControl override
        this._isInvalid = this.control ? this.control.invalid && this.control.touched : coerceBooleanProperty(state);
        // set BaseDirective Attribute
        this.euiDanger = this._isInvalid;
    }
    /**
     * @Override setPlaceholder setPlaceholderAttribute of InputDirective
     * Updates the placeholder value based on current number format and given value.
     * If value passed contains characters it doesn't format placeholder.
     * */
    setPlaceholderAttribute(value) {
        // if value is a number, format the value based on current number format
        if (typeof value === 'number' && !isNaN(value) && isPlatformBrowser(this.platformId)) {
            const div = this.document.createElement('input');
            // create a clone of cleaveInstance
            const cloneInstance = new Cleave(div, this.options);
            // BEWARE: by the time your setRawValue cleave options have changed thus number formatting
            cloneInstance.setRawValue(value.toString());
            // set the value with current format as placeholder
            super.setPlaceholderAttribute(cloneInstance.getFormattedValue());
        }
        else if (typeof value === 'string') {
            super.setPlaceholderAttribute(value.toString());
        }
        else if (isNaN(value)) {
            value = this._elementRef.nativeElement.placeholder;
            super.setPlaceholderAttribute(value.toString());
        }
    }
    /**
     * instantiate Cleave.js
     */
    initCleave(onChangeCallback) {
        if (isPlatformServer(this.platformId)) {
            // in case it's not a browser environment
            return;
        }
        // change the cleave prototype function to intercept onCut callback
        // and allow based on the event bubbling and disabled state
        // TIP: change behavior of onCut to stop in case bubble is canceled
        // TODO: See relevant issue https://github.com/nosir/cleave.js/issues/675
        const _onCut = Cleave.prototype['onCut'];
        Cleave.prototype['onCut'] = function (e) {
            /* eslint-enable no-invalid-this */
            // Check if the event is composed and stopPropagation hasn't been called
            if (!e.composed && !e.defaultPrevented && !this.element.disabled) {
                _onCut.call(this, e);
            }
            /* eslint-disable no-invalid-this */
        };
        // in case options is undefined
        const opts = { ...this.options };
        // set the onValue change listener to keep the value at readOnly element in sync
        opts.onValueChanged = onChangeCallback || this.onValueChanged.bind(this);
        // in case round UP is enabled
        if (this.roundUp > 0) {
            const number = this.parseNumber(this._elementRef.nativeElement.value);
            this._elementRef.nativeElement.value = this.decimalAdjust(number, this.roundUp);
        }
        // create the Cleave instance with the new or updated options
        this.cleaveInstance = new Cleave(this._elementRef.nativeElement, opts);
    }
    /**
     * Updates the cleave options by destroying the current instance and creating another one while keeping the previous
     * value.
     */
    updateOptions(localeUpdated = false) {
        if (this.cleaveInstance) {
            // the value before destroying cleave instance
            const previousValue = this.cleaveInstance.getRawValue();
            // update the Cleave instance with the new or updated options
            this.cleaveInstance.properties = {
                ...this.cleaveInstance.properties,
                ...this.options,
                initValue: previousValue,
            };
            // init number formatter with updated options
            this.cleaveInstance.initNumeralFormatter();
            // In case previous settings where numeralDecimalMark='.' with value 1000.99, and they changed to
            // numeralDecimalMark=','; set initValue to 1000.99 or even 1000,99 will not be reflected and cleave will
            // remove the decimal part. Set of the value after initialization causes reformat of number and works.
            this.cleaveInstance.setRawValue(previousValue);
            // parse number
            const number = this.parseNumber(this._elementRef.nativeElement.placeholder || undefined, localeUpdated);
            // set placeholder in case none is provided
            this.setPlaceholderAttribute(number);
        }
    }
    /**
     * Callback function of the Cleave instance that is invoked when value is changed.
     *
     * @param event type of CleaveEventOnChange
     */
    onValueChanged(event) {
        const { target } = event;
        if (this.fillFraction) {
            this.applyFractionFill(target.rawValue);
        }
        this.onChange(this.parseNumber(target.rawValue, false, false));
        // fill leading zero
        if (this.leadingZero) {
            const size = this.leadingZero > this.digits && this.digits > 0 ? this.digits : this.leadingZero;
            this._elementRef.nativeElement.value = this.padZero(event.target.rawValue, size);
        }
    }
    /**
     * responsible to extract all locale information needed to build CleaveOptions related to number format.
     *
     * @param id The id of the locale
     */
    getCleaveOptsBasedOnLocale(id) {
        if (!id || id === '') {
            throw new Error('Locale id cannot be empty or undefined');
        }
        const opts = {
            numeral: true,
            delimiter: getGroup(id),
            numeralDecimalMark: getDecimal(id),
            numeralDecimalScale: this.fractionDigits,
            numeralIntegerScale: this.digits,
            numeralThousandsGroupStyle: this.noFormat ? 'none' : 'thousand', // TODO: implement based on locale
        };
        return { ...this.options, ...opts };
    }
    /**
     * Applies the fill of decimal part with zeros in case decimal part of given number has
     * size less than the max fraction digits.
     *
     * @param number
     * @param cleaveInstance
     * @private
     */
    applyFractionFill(number, cleaveInstance = this.cleaveInstance) {
        // if fill fraction is enabled and there's cleave instance
        if (this.fillFraction) {
            if (this.cleaveInstance) {
                number = number?.toString();
                if (number === '' || !number) {
                    return;
                }
                const hasDecimal = number.split('.').length > 1;
                // in case there's already decimal point in number
                if (hasDecimal) {
                    const decimalSize = number.split('.')[1].length;
                    // if size of decimal part of number is less than the max fraction digits
                    if (decimalSize < this._fractionDigits) {
                        number = number + new Array(this._fractionDigits - decimalSize).fill(0).join('');
                        const pos = this._elementRef.nativeElement.selectionStart;
                        cleaveInstance.setRawValue(number);
                        this._elementRef.nativeElement.setSelectionRange(pos, pos);
                    }
                    // in case there's not, force it by filling it as much zero as the fraction digits
                }
                else if (this.fractionDigits > 0) {
                    number = `${number}.${new Array(this._fractionDigits).fill(0).join('')}`;
                    const pos = this._elementRef.nativeElement.selectionStart;
                    cleaveInstance.setRawValue(number);
                    this._elementRef.nativeElement.setSelectionRange(pos, pos);
                }
            }
        }
    }
    /**
     * Parses a given formatted number and returns it as a number.
     *
     * @param value The formatted number you want to parse e.g. 111,888.22
     * @param userPrevLocaleState Use previous locale state to parse the value. By default, is false
     * @param replaceSymbol Replace the decimal symbol with a dot. By default, is false
     * @private
     */
    parseNumber(value, userPrevLocaleState = false, replaceSymbol = true) {
        // locale state
        const locale = userPrevLocaleState ? this.localeService?.previousLocale : this.localeService?.currentLocale || this.locale_id || 'en';
        // get decimal and group symbols
        const decimalSymbol = getDecimal(locale);
        const groupSymbol = getGroup(locale);
        // replace symbols to parse number
        const parsedNumber = value?.split(groupSymbol).join('').split(decimalSymbol).join('.');
        return this.parseBigNumber(replaceSymbol ? parsedNumber : value);
    }
    /**
     * Pad leading zero to the number
     *
     * @param num The number to add leading zero to
     * @param size Number of number's leading zero
     * @private
     */
    padZero(num, size) {
        num = num.toString();
        // get integer and decimal part
        // eslint-disable-next-line prefer-const
        let [integer, decimal] = num.split('.');
        while (integer.length < size) {
            integer = '0' + integer;
        }
        return decimal ? `${integer}.${decimal}` : integer;
    }
    /**
     * checks whether the min symbol is allowed. It is allowed when minus symbol
     * provided and min input is undefined or min provided and is negative.
     *
     * @param key The key string coming from an event
     */
    isMinusAllowed(key) {
        return !this.min || this.min < 0 ? key !== '-' : true;
    }
    /**
     * check whether the key entered is inside the min and
     * max range. Returns true if it's out of range.
     *
     * @param e A keyboard event
     */
    isOutSideRange(e) {
        if (!this.cleaveInstance) {
            return false;
        }
        // get caret position
        const pos = e.target['selectionStart'];
        // get caret position (in case there's text selected)
        const endPos = e.target['selectionEnd'];
        // get current value (formatted)
        let value = e.target['value'];
        // remove key from value
        if (e.key === 'Delete' || e.key === 'Backspace') {
            // check if there's selection of text to be removed
            if (pos !== endPos) {
                value = e.target['value'].substring(0, pos) + e.target['value'].substring(endPos, e.target['value'].length);
            }
            else {
                value = e.target['value'].substring(0, pos - 1) + e.target['value'].substring(endPos, e.target['value'].length);
            }
        }
        else {
            // add key to the value
            value = [value.slice(0, pos), e.key, value.slice(endPos)].join('');
        }
        // create a Cleave instance to extract the number from formatted value
        const cleave = new Cleave(this.document.createElement('input'), { ...this.options });
        cleave.setRawValue(value);
        const number = Number(cleave.getRawValue());
        // destroy cleave instance
        cleave.destroy();
        return !isNaN(number) &&
            this.min >= 0 ? (this.isDefined(this.max) && this.max < number) : (this.min > number || this.max < number) &&
            this.max <= 0 ? (this.isDefined(this.min) && this.min > number) : (this.min > number || this.max < number);
    }
    /**
     * Decimal adjustment of a number.
     *
     * @param value The number or string representation of a number.
     * @param exp   The exponent (the 10 logarithm of the adjustment base).
     * @returns The adjusted value.
     */
    decimalAdjust(value, exp) {
        // Ensure exp is a number
        exp = +Number(exp);
        // Convert input to string if it's a number
        const valueStr = typeof value === 'number' ? value.toString() : String(value);
        // Handle empty or invalid inputs
        if (!valueStr || isNaN(Number(valueStr))) {
            return '';
        }
        try {
            // Check if the value is negative
            const isNegative = valueStr.startsWith('-');
            // Get the absolute value string
            const absoluteValueStr = isNegative ? valueStr.substring(1) : valueStr;
            // Split the number into integer and decimal parts
            const parts = absoluteValueStr.split('.');
            let integerPart = parts[0] || '0'; // Default to '0' if empty
            let decimalPart = parts.length > 1 ? parts[1] : '';
            // If there's no decimal part and exp > 0, we should add zeros
            if (decimalPart === '' && exp > 0) {
                decimalPart = '0'.repeat(exp);
            }
            // Pad decimal part with zeros if needed
            if (decimalPart.length < exp) {
                decimalPart = decimalPart.padEnd(exp, '0');
            }
            // Determine if we need to round up
            let roundUp = false;
            if (decimalPart.length > exp) {
                const nextDigit = parseInt(decimalPart.charAt(exp), 10);
                roundUp = nextDigit >= 5;
            }
            // Trim the decimal part to the required precision
            decimalPart = decimalPart.substring(0, exp);
            // Handle rounding
            if (roundUp) {
                if (exp === 0) {
                    // If exp is 0, we need to round the integer part
                    integerPart = (BigInt(integerPart) + 1n).toString();
                }
                else {
                    // Create a number from the decimal part
                    let decimalNum = parseInt(decimalPart, 10);
                    // Add 1 to the decimal part
                    decimalNum += 1;
                    // Check if we need to carry over to the integer part
                    if (decimalNum.toString().length > exp) {
                        integerPart = (BigInt(integerPart) + 1n).toString();
                        decimalNum = 0;
                    }
                    // Convert back to string and pad with leading zeros if needed
                    decimalPart = decimalNum.toString().padStart(exp, '0');
                }
            }
            // Combine the parts
            let result;
            if (exp > 0) {
                // Remove trailing zeros if they're not significant
                let trimmedDecimalPart = decimalPart;
                while (trimmedDecimalPart.length > 0 && trimmedDecimalPart.charAt(trimmedDecimalPart.length - 1) === '0') {
                    trimmedDecimalPart = trimmedDecimalPart.substring(0, trimmedDecimalPart.length - 1);
                }
                result = trimmedDecimalPart.length > 0 ? `${integerPart}.${trimmedDecimalPart}` : integerPart;
            }
            else {
                result = integerPart;
            }
            // Restore the negative sign if needed
            return isNegative ? '-' + result : result;
        }
        catch (error) {
            console.error('Error in decimalAdjust:', error);
            // If there's an error, return a formatted original value or '0'
            return valueStr || '0';
        }
    }
    /**
     * Checks whether a value is defined or not
     *
     * @param value
     */
    isDefined(value) {
        return value !== undefined && value !== null;
    }
    /**
     * Check if the value is a valid number. Take into account the Big numbers
     * more than 16 digits. Check if string contains only digits and dots.
     * The number value must not be formatted.
     * @param value the value to check
     * @private
     */
    isItaNumber(value) {
        const length = value?.split('.')[0].length;
        return length > 15 ? /^\d+(\.\d+)?$/.test(value) : !isNaN(Number(value));
    }
    /**
     * Parse the value to a number. For large numbers, the value is a string.
     * The number value must not be formatted.
     * @param value the value to parse
     * @private
     */
    parseBigNumber(value) {
        // for large numbers, the value is a string
        const length = value?.split('.')[0].length;
        return length > 15 ? value : Number.parseFloat(value);
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: EuiInputNumberComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "16.1.0", version: "19.2.17", type: EuiInputNumberComponent, isStandalone: true, selector: "input[euiInputNumber]", inputs: { min: ["min", "min", numberAttribute], max: ["max", "max", numberAttribute], leadingZero: ["leadingZero", "leadingZero", numberAttribute], isInvalid: "isInvalid", fractionDigits: "fractionDigits", digits: ["digits", "digits", numberAttribute], fillFraction: ["fillFraction", "fillFraction", booleanAttribute], roundUp: ["roundUp", "roundUp", numberAttribute], noFormat: ["noFormat", "noFormat", booleanAttribute], value: "value" }, host: { listeners: { "blur": "onTouched()", "paste": "onPaste($event)", "keydown": "onKeyDown($event)", "focusout": "onFocusout()" }, properties: { "class": "this.cssClasses", "attr.type": "this.type" } }, usesInheritance: true, usesOnChanges: true, hostDirectives: [{ directive: i1.EuiClearableDirective, inputs: ["euiClearable", "euiClearable", "readonly", "readonly", "disabled", "disabled"] }, { directive: i1.EuiLoadingDirective, inputs: ["euiLoading", "euiLoading", "readonly", "readonly"] }], ngImport: i0, template: '', isInline: true, styles: [".eui-19 :host.eui-input-number{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:var(--eui-f-m);appearance:none;background-color:var(--eui-c-surface-container);border:1px solid var(--eui-c-s-secondary-border-light);border-radius:var(--eui-br-m);box-shadow:none;color:var(--eui-c-text);padding:calc(var(--eui-s-xs) - 1px) calc(var(--eui-s-m) - 1px);width:100%}.eui-19 :host.eui-input-number:focus:not([readonly]){outline:2px solid var(--eui-c-focus)!important;outline-offset:-2px!important;transition:none}.eui-19 :host.eui-input-number:focus-visible:not([readonly]){outline:2px solid var(--eui-c-focus-visible)!important;outline-offset:-2px!important;transition:none}.eui-19 :host.eui-input-number [tabindex=\"0\"]:focus:not([readonly]){outline:2px solid var(--eui-c-focus-visible)!important;outline-offset:-2px!important;transition:none}.eui-19 :host.eui-input-number:not([hidden]){display:block}.eui-19 :host.eui-input-number::placeholder{color:var(--eui-c-text-lighter)!important;opacity:1}.eui-19 :host.eui-input-number[readonly]{background-color:transparent;border-color:transparent;box-shadow:none;height:inherit;padding-left:0;padding-right:0;pointer-events:none}.eui-19 :host.eui-input-number[readonly]+.eui-feedback-message,.eui-19 :host.eui-input-number[readonly]+.eui-input-maxlength{appearance:none;display:none}.eui-19 :host.eui-input-number[disabled]:not([readonly]),.eui-19 :host.eui-input-number--disabled:not([readonly]){background-color:var(--eui-c-s-secondary-surface-light)!important;border:1px solid var(--eui-c-s-secondary-border-lighter);color:var(--eui-c-text-light);pointer-events:none}.eui-19 :host.eui-input-number--invalid,.eui-19 :host.eui-input-number--danger{border:1px solid var(--eui-c-s-danger-border)}.eui-19 :host.eui-input-number--loading{padding-right:var(--eui-s-4xl)}.eui-19 :host.eui-input-number--loading-icon{align-items:center;display:flex}.eui-19 :host.eui-input-number--loading-icon:after,.eui-19 :host.eui-input-number--loading-icon:before{content:\"\";height:var(--eui-s-l);position:absolute;right:var(--eui-s-s);width:var(--eui-s-l)}.eui-19 :host.eui-input-number--loading-icon:before{border:var(--eui-s-2xs) solid rgba(0,0,0,.35);border-radius:100%}.eui-19 :host.eui-input-number--loading-icon:after{animation:loading .6s linear;animation-iteration-count:infinite;border-color:var(--eui-c-white) transparent transparent;border-radius:100%;border-style:solid;border-width:var(--eui-s-2xs);box-shadow:0 0 0 1px transparent}.eui-19 :host.eui-input-number--loading-icon--sm:after,.eui-19 :host.eui-input-number--loading-icon--sm:before{height:var(--eui-s-m);width:var(--eui-s-m)}@keyframes loading{to{transform:rotate(360deg)}}.eui-19 :host.eui-input-number--clearable{padding-right:var(--eui-s-4xl)}.eui-19 :host.eui-input-number[readonly]{pointer-events:auto}\n"] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: EuiInputNumberComponent, decorators: [{
            type: Component,
            args: [{ selector: 'input[euiInputNumber]', template: '', hostDirectives: [
                        {
                            directive: EuiClearableDirective,
                            inputs: ['euiClearable', 'readonly', 'disabled'],
                        },
                        {
                            directive: EuiLoadingDirective,
                            inputs: ['euiLoading', 'readonly'],
                        },
                    ], host: {
                        '(blur)': 'onTouched()',
                    }, styles: [".eui-19 :host.eui-input-number{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:var(--eui-f-m);appearance:none;background-color:var(--eui-c-surface-container);border:1px solid var(--eui-c-s-secondary-border-light);border-radius:var(--eui-br-m);box-shadow:none;color:var(--eui-c-text);padding:calc(var(--eui-s-xs) - 1px) calc(var(--eui-s-m) - 1px);width:100%}.eui-19 :host.eui-input-number:focus:not([readonly]){outline:2px solid var(--eui-c-focus)!important;outline-offset:-2px!important;transition:none}.eui-19 :host.eui-input-number:focus-visible:not([readonly]){outline:2px solid var(--eui-c-focus-visible)!important;outline-offset:-2px!important;transition:none}.eui-19 :host.eui-input-number [tabindex=\"0\"]:focus:not([readonly]){outline:2px solid var(--eui-c-focus-visible)!important;outline-offset:-2px!important;transition:none}.eui-19 :host.eui-input-number:not([hidden]){display:block}.eui-19 :host.eui-input-number::placeholder{color:var(--eui-c-text-lighter)!important;opacity:1}.eui-19 :host.eui-input-number[readonly]{background-color:transparent;border-color:transparent;box-shadow:none;height:inherit;padding-left:0;padding-right:0;pointer-events:none}.eui-19 :host.eui-input-number[readonly]+.eui-feedback-message,.eui-19 :host.eui-input-number[readonly]+.eui-input-maxlength{appearance:none;display:none}.eui-19 :host.eui-input-number[disabled]:not([readonly]),.eui-19 :host.eui-input-number--disabled:not([readonly]){background-color:var(--eui-c-s-secondary-surface-light)!important;border:1px solid var(--eui-c-s-secondary-border-lighter);color:var(--eui-c-text-light);pointer-events:none}.eui-19 :host.eui-input-number--invalid,.eui-19 :host.eui-input-number--danger{border:1px solid var(--eui-c-s-danger-border)}.eui-19 :host.eui-input-number--loading{padding-right:var(--eui-s-4xl)}.eui-19 :host.eui-input-number--loading-icon{align-items:center;display:flex}.eui-19 :host.eui-input-number--loading-icon:after,.eui-19 :host.eui-input-number--loading-icon:before{content:\"\";height:var(--eui-s-l);position:absolute;right:var(--eui-s-s);width:var(--eui-s-l)}.eui-19 :host.eui-input-number--loading-icon:before{border:var(--eui-s-2xs) solid rgba(0,0,0,.35);border-radius:100%}.eui-19 :host.eui-input-number--loading-icon:after{animation:loading .6s linear;animation-iteration-count:infinite;border-color:var(--eui-c-white) transparent transparent;border-radius:100%;border-style:solid;border-width:var(--eui-s-2xs);box-shadow:0 0 0 1px transparent}.eui-19 :host.eui-input-number--loading-icon--sm:after,.eui-19 :host.eui-input-number--loading-icon--sm:before{height:var(--eui-s-m);width:var(--eui-s-m)}@keyframes loading{to{transform:rotate(360deg)}}.eui-19 :host.eui-input-number--clearable{padding-right:var(--eui-s-4xl)}.eui-19 :host.eui-input-number[readonly]{pointer-events:auto}\n"] }]
        }], ctorParameters: () => [], propDecorators: { min: [{
                type: Input,
                args: [{ transform: numberAttribute }]
            }], max: [{
                type: Input,
                args: [{ transform: numberAttribute }]
            }], leadingZero: [{
                type: Input,
                args: [{ transform: numberAttribute }]
            }], isInvalid: [{
                type: Input
            }], cssClasses: [{
                type: HostBinding,
                args: ['class']
            }], fractionDigits: [{
                type: Input
            }], digits: [{
                type: Input,
                args: [{ transform: numberAttribute }]
            }], fillFraction: [{
                type: Input,
                args: [{ transform: booleanAttribute }]
            }], roundUp: [{
                type: Input,
                args: [{ transform: numberAttribute }]
            }], noFormat: [{
                type: Input,
                args: [{ transform: booleanAttribute }]
            }], type: [{
                type: HostBinding,
                args: ['attr.type']
            }], value: [{
                type: Input
            }], onPaste: [{
                type: HostListener,
                args: ['paste', ['$event']]
            }], onKeyDown: [{
                type: HostListener,
                args: ['keydown', ['$event']]
            }], onFocusout: [{
                type: HostListener,
                args: ['focusout']
            }] } });

/**
 * @description
 * Directive for the {@link EuiInputNumberComponent}. This directive is used to
 * handle the value changes of the input element and update the value of the
 * directive and the form control. It also implements the ControlValueAccessor
 * interface to allow the directive to be used with reactive forms.
 */
class EuiInputNumberDirective {
    constructor() {
        this.elementRef = inject(ElementRef);
        this.euiNumberComponent = inject(EuiInputNumberComponent, { optional: true });
        this.document = inject(DOCUMENT);
        this.platformId = inject(PLATFORM_ID);
    }
    ngOnInit() {
        this.euiNumberComponent['initCleave'](this.valueChanges.bind(this));
    }
    // TODO: find the correct type or turn into a generic, https://www.typescriptlang.org/docs/handbook/2/generics.html
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    writeValue(obj) {
        if (isPlatformServer(this.platformId)) {
            return;
        }
        const cleave = new Cleave(this.document.createElement('input'), { ...this.euiNumberComponent['options'] });
        cleave.setRawValue(obj);
        if (this.euiNumberComponent.fillFraction && obj !== '' && obj) {
            this.euiNumberComponent['applyFractionFill'](obj, cleave);
        }
        let valueOfElement;
        // fill leading zero
        if (this.euiNumberComponent.leadingZero) {
            const size = this.euiNumberComponent.leadingZero > this.euiNumberComponent.digits && this.euiNumberComponent.digits > 0
                ? this.euiNumberComponent.digits
                : this.euiNumberComponent.leadingZero;
            valueOfElement = this.euiNumberComponent['padZero'](cleave.getFormattedValue(), size);
        }
        else {
            valueOfElement = cleave.getFormattedValue();
        }
        this.elementRef.nativeElement.value = valueOfElement;
        const { canConvert } = this.canSafelyConvertToNumber(cleave.getRawValue());
        this.value = !canConvert ? cleave.getRawValue() : Number.parseFloat(cleave.getRawValue());
        cleave.destroy();
    }
    // TODO: find the correct type or turn into a generic, https://www.typescriptlang.org/docs/handbook/2/generics.html
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    registerOnChange(fn) {
        this.onChange = (t) => {
            this.value = t;
            fn(t);
        };
    }
    // TODO: find the correct type or turn into a generic, https://www.typescriptlang.org/docs/handbook/2/generics.html
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    registerOnTouched(fn) {
        this.onTouched = fn;
    }
    /**
     * Set the disabled state of the input element.
     *
     * @param isDisabled
     */
    setDisabledState(isDisabled) {
        this.euiNumberComponent.disabled = isDisabled;
    }
    onTouched() {
        // this.euiNumberComponent.isInvalid = this.control.invalid;
    }
    /**
     * Handle the value changes of the input element and update the value of the
     * directive and the form control. For large numbers, the value is a string.
     *
     * @param event
     */
    valueChanges(event) {
        const { target } = event;
        this.euiNumberComponent['onValueChanged'](event);
        const { canConvert, value } = this.canSafelyConvertToNumber(target.rawValue);
        // Only emit change if the value has actually changed
        if (this.value !== target.rawValue && this.onChange) {
            this.onChange(!canConvert ? target.rawValue : value);
        }
    }
    /**
     * Check if a numeric string can be safely converted to a number without
     * losing precision or exceeding JavaScript's maximum safe integer limit.
     * This is important for very large numbers that may be represented
     * as strings to avoid precision loss.
     *
     * @param numString The numeric string to check
     * @return An object indicating if conversion is safe, the reason if not, and the converted value if safe
     */
    canSafelyConvertToNumber(numString) {
        // Remove whitespace
        const trimmed = numString.trim();
        if (trimmed === '') {
            return {
                canConvert: false,
                reason: 'Empty string converts to null',
                value: null,
            };
        }
        // Convert to number
        const numValue = Number(trimmed);
        // Check if it's infinity (exceeds MAX_VALUE)
        if (!isFinite(numValue)) {
            return {
                canConvert: false,
                reason: 'Number exceeds maximum value',
                value: null,
            };
        }
        // Convert back to string
        const convertedBack = numValue.toString();
        // Normalize BOTH strings without converting to number
        const normalizedOriginal = this.normalizeStringOnly(trimmed);
        const normalizedConverted = this.normalizeStringOnly(convertedBack);
        if (normalizedOriginal !== normalizedConverted) {
            return {
                canConvert: false,
                reason: 'Precision loss detected',
                value: null,
                original: trimmed,
                converted: numValue,
            };
        }
        return {
            canConvert: true,
            reason: 'Safe to convert',
            value: numValue,
        };
    }
    /**
     * Normalize a numeric string by removing leading/trailing zeros and signs,
     * without converting to a number. This helps compare the original and converted
     * strings for equivalence.
     *
     * @param str The numeric string to normalize
     * @returns The normalized string
     */
    normalizeStringOnly(str) {
        let s = str.trim();
        // Remove leading + sign
        if (s.startsWith('+')) {
            s = s.substring(1);
        }
        // Handle decimal numbers
        if (s.includes('.')) {
            let [intPart, decPart] = s.split('.');
            // Remove leading zeros from integer part (but keep at least one zero)
            intPart = intPart.replace(/^0+/, '') || '0';
            // Remove trailing zeros from decimal part
            decPart = decPart.replace(/0+$/, '');
            // If no decimal digits left, return just integer
            if (decPart === '') {
                return intPart;
            }
            return intPart + '.' + decPart;
        }
        else {
            // Integer - remove leading zeros
            return s.replace(/^0+/, '') || '0';
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: EuiInputNumberDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
    static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "19.2.17", type: EuiInputNumberDirective, isStandalone: true, selector: "input[euiInputNumber][formControl],input[euiInputNumber][formControlName],input[euiInputNumber][ngModel]", providers: [
            {
                provide: NG_VALUE_ACCESSOR,
                useExisting: forwardRef(() => EuiInputNumberDirective),
                multi: true,
            },
        ], ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: EuiInputNumberDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: 'input[euiInputNumber][formControl],input[euiInputNumber][formControlName],input[euiInputNumber][ngModel]',
                    providers: [
                        {
                            provide: NG_VALUE_ACCESSOR,
                            useExisting: forwardRef(() => EuiInputNumberDirective),
                            multi: true,
                        },
                    ],
                }]
        }] });

/**
 * @description
 * Module for the {@link EuiInputNumberComponent} and {@link EuiInputNumberDirective}.
 *
 * @deprecated Use {@link EUI_INPUT_NUMBER} instead.
 */
class EuiInputNumberModule {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: EuiInputNumberModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.2.17", ngImport: i0, type: EuiInputNumberModule, imports: [EuiInputNumberComponent, EuiInputNumberDirective], exports: [EuiInputNumberComponent, EuiInputNumberDirective] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: EuiInputNumberModule }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: EuiInputNumberModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [EuiInputNumberComponent, EuiInputNumberDirective],
                    exports: [EuiInputNumberComponent, EuiInputNumberDirective],
                }]
        }] });

const EUI_INPUT_NUMBER = [
    EuiInputNumberComponent,
    EuiInputNumberDirective,
];

/**
 * Generated bundle index. Do not edit.
 */

export { EUI_INPUT_NUMBER, EuiInputNumberComponent, EuiInputNumberDirective, EuiInputNumberModule };
//# sourceMappingURL=eui-components-eui-input-number.mjs.map
