import { r as registerInstance, c as createEvent, h, H as Host, g as getElement } from './index-BdVwMG9u.js';
import { _ as __decorate, a as __metadata } from './tslib.es6-dfXERft2.js';
import { i as isNil } from './index-zWZxKBfo.js';
import { a as ariaBooleanToString } from './aria-DBsOHTWj.js';
import { i as inheritAttributes } from './attributes-C4sZQbkT.js';
import { B as BEM } from './bem-ByiN-QjD.js';
import { i as isCtrlOrCommandKey, A as ACTION_KEYS, N as NUMBER_KEYS } from './keys.constant-xVPGsAdF.js';
import { d as defaultBalAriaForm } from './form-FCLKfv6B.js';
import { g as getInputTarget, a as inputHandleFocus, b as inputHandleBlur, e as inputHandleChange, s as stopEventBubbling, f as inputHandleClick, i as inputHandleHostClick, h as inputListenOnClick, j as inputHandleReset, c as inputSetFocus, d as inputSetBlur } from './form-input-DYvzaBlM.js';
import { n as debounceEvent } from './helpers-BNj87EbG.js';
import { L as Logger } from './log-CwssmmaV.js';
import './_commonjsHelpers-BFTU3MAI.js';
import './browser-B1u-Mq75.js';
import './config.utils-B7jugjyM.js';

/**
 *
 * @param value - input number
 * @output 123.456.789
 * @private
 */
function formatVehicleRegistrationNumber(value) {
    if (!value) {
        return '';
    }
    const newValue = value.replace(/\D/g, '').trim();
    const parts = [
        newValue.substring(0, 3),
        newValue.substring(3, 6),
        newValue.substring(6, 9),
        newValue.substring(9, 12),
    ].filter(val => val.length > 0);
    switch (parts.length) {
        case 1:
            return `${value}`;
        case 2:
            return `${parts[0]}.${parts[1]}`;
        case 3:
            return `${parts[0]}.${parts[1]}.${parts[2]}`;
        default:
            return `${parts[0]}.${parts[1]}.${parts[2]}.${parts[3]}`;
    }
}
/**
 *
 * @param value - input number
 * @output 73/001217/16.9
 * @private
 */
function formatClaim(value) {
    if (!value) {
        return '';
    }
    const newValue = `${value}`.trim().toUpperCase();
    const parts = [
        newValue.substring(0, 2),
        newValue.substring(2, 8),
        newValue.substring(8, 10),
        newValue.substring(10, 11),
    ].filter(val => val.length > 0);
    switch (parts.length) {
        case 1:
            return `${value}`;
        case 2:
            return `${parts[0]}/${parts[1]}`;
        case 3:
            return `${parts[0]}/${parts[1]}/${parts[2]}`;
        default:
            return `${parts[0]}/${parts[1]}/${parts[2]}.${parts[3]}`;
    }
}
/**
 *
 * @param value: input number
 * @output 99/1.234.567-1
 * @private
 */
function formatPolicy(value) {
    if (!value) {
        return '';
    }
    let newValue = `${value}`.trim();
    const parts = [newValue.substring(0, 9), newValue.substring(9, 10)].filter(val => val.length > 0);
    newValue = formatOffer(parts[0]);
    return parts[1] ? `${newValue}-${parts[1]}` : newValue;
}
/**
 *
 * @param value: input number
 * @output 98/7.654.321
 * @private
 */
function formatOffer(value) {
    if (!value) {
        return '';
    }
    const newValue = `${value}`.trim();
    const parts = [
        newValue.substring(0, 2),
        newValue.substring(2, 3),
        newValue.substring(3, 6),
        newValue.substring(6, 9),
    ].filter(val => val.length > 0);
    switch (parts.length) {
        case 1:
            return `${newValue}`;
        case 2:
            return `${parts[0]}/${parts[1]}`;
        case 3:
            return `${parts[0]}/${parts[1]}.${parts[2]}`;
        default:
            return `${parts[0]}/${parts[1]}.${parts[2]}.${parts[3]}`;
    }
}
/**
 *
 * @param value: input number
 * @output 1234.567.890
 * @private
 */
function formatBeEnterpriseNumber(value) {
    if (!value) {
        return '';
    }
    const newValue = `${value}`.trim();
    const parts = [newValue.substring(0, 4), newValue.substring(4, 7), newValue.substring(7, 10)].filter(val => val.length > 0);
    switch (parts.length) {
        case 1:
            return `${newValue}`;
        case 2:
            return `${parts[0]}.${parts[1]}`;
        default:
            return `${parts[0]}.${parts[1]}.${parts[2]}`;
    }
}
/**
 *
 * @param value: input number
 * @output BE68 5390 0754 7034
 * @private
 */
function formatBeIBAN(value) {
    if (!value) {
        return '';
    }
    const newValue = `${value}`.trim();
    const parts = [
        newValue.substring(0, 2),
        newValue.substring(2, 6),
        newValue.substring(6, 10),
        newValue.substring(10, 14),
    ].filter(val => val.length > 0);
    switch (parts.length) {
        case 1:
            return `BE${newValue}`;
        case 2:
            return `BE${parts[0]} ${parts[1]}`;
        case 3:
            return `BE${parts[0]} ${parts[1]} ${parts[2]}`;
        default:
            return `BE${parts[0]} ${parts[1]} ${parts[2]} ${parts[3]}`;
    }
}
const MAX_LENGTH_CONTRACT_NUMBER = 10;
const MAX_LENGTH_VEHICLE_REGISTRATION_NUMBER = 12;
const MAX_LENGTH_BASIC_CONTRACT_NUMBER = 9;
const MAX_LENGTH_OFFER_NUMBER = 9;
const MAX_LENGTH_CLAIM_NUMBER = 11;
const MAX_LENGTH_BE_ENTERPRISE_NUMBER = 10;
const MAX_LENGTH_BE_IBAN = 14;

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

const Input = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.balInput = createEvent(this, "balInput");
        this.balBlur = createEvent(this, "balBlur");
        this.balKeyPress = createEvent(this, "balKeyPress");
        this.balFocus = createEvent(this, "balFocus");
        this.balChange = createEvent(this, "balChange");
        this.inputId = `bal-input-${InputIds++}`;
        this.inheritedAttributes = {};
        this.inputValue = this.value;
        this.initialValue = this.value || '';
        this.focused = false;
        this.ariaForm = defaultBalAriaForm;
        /**
         * The name of the control, which is submitted with the form data.
         */
        this.name = this.inputId;
        /**
         * If `true` the component gets a invalid style.
         */
        this.invalid = false;
        /**
         * Defines the text align of the input value.
         */
        this.textAlign = 'left';
        /**
         * Defines the type of the input (text, number, email ...).
         */
        this.type = 'text';
        /**
         * Indicates whether and how the text value should be automatically capitalized as it is entered/edited by the user.
         * Available options: `"off"`, `"none"`, `"on"`, `"sentences"`, `"words"`, `"characters"`.
         */
        this.autocapitalize = 'off';
        /**
         * Indicates whether the value of the control can be automatically completed by the browser.
         */
        this.autocomplete = 'off';
        /**
         * Whether auto correction should be enabled when the user is entering/editing the text value.
         */
        this.autocorrect = 'off';
        /**
         * This Boolean attribute lets you specify that a form control should have input focus when the page loads.
         */
        this.autofocus = false;
        /**
         * Set the amount of time, in milliseconds, to wait to trigger the `balChange` event after each keystroke. This also impacts form bindings such as `ngModel` or `v-model`.
         */
        this.debounce = 0;
        /**
         * If `true`, the user must fill in a value before submitting a form.
         */
        this.required = false;
        /**
         * If `true`, the element will have its spelling and grammar checked.
         */
        this.spellcheck = false;
        /**
         * If `true`, the element is not mutable, focusable, or even submitted with the form. The user can neither edit nor focus on the control, nor its form control descendants.
         */
        this.disabled = false;
        /**
         * If `true` the element can not mutated, meaning the user can not edit the control.
         */
        this.readonly = false;
        /**
         * If `true` the input gets a clickable cursor style
         */
        this.clickable = false;
        /**
         * @internal
         * If `true` the input will get some right padding.
         */
        this.hasIconRight = false;
        /**
         * The value of the input.
         */
        this.value = undefined;
        /**
         * Mask of the input field. It defines what the user can enter and how the format looks like. Currently, only for Switzerland formatted with addition of Belgian enterprisenumber and IBAN.
         * Formatting for 'contract-number': '99/1.234.567-1'
         * Formatting for 'basic-contract-number': '99/1.234.567'
         * Formatting for 'claim-number': ('73/001217/16.9')
         * Formatting for 'offer-number': ('98/7.654.321')
         * Formatting for 'be-enterprise-number': ('1234.567.890')
         * Formatting for 'be-iban': ('BE68 5390 0754 7034')
         */
        this.mask = undefined;
        /**
         * If `true`, in Angular reactive forms the control will not be set invalid
         */
        this.autoInvalidOff = false;
        this.getInputValue = () => {
            var _a;
            const input = this.nativeInput;
            let inputValue = '';
            if (input) {
                if (this.allowedKeyPress && input && !this.mask) {
                    const regex = new RegExp('^' + this.allowedKeyPress + '$');
                    const value = input.value
                        .split('')
                        .filter(val => regex.test(val))
                        .join('');
                    input.value = value;
                    return value;
                }
                if (input.value) {
                    if (this.mask) {
                        switch (this.mask) {
                            case 'vehicle-registration-number': {
                                inputValue = input.value.replace(/\D/g, '');
                                if (inputValue.length > MAX_LENGTH_VEHICLE_REGISTRATION_NUMBER) {
                                    inputValue = inputValue.substring(0, MAX_LENGTH_VEHICLE_REGISTRATION_NUMBER);
                                }
                                return inputValue;
                            }
                            case 'contract-number': {
                                inputValue = input.value.replace(/\D/g, '');
                                // Removing the leading zero if presented
                                if (inputValue.charAt(0) === '0') {
                                    inputValue = inputValue.substring(1);
                                }
                                if (inputValue.length > MAX_LENGTH_CONTRACT_NUMBER) {
                                    inputValue = inputValue.substring(0, MAX_LENGTH_CONTRACT_NUMBER);
                                }
                                return inputValue;
                            }
                            case 'basic-contract-number': {
                                inputValue = input.value.replace(/\D/g, '');
                                // Removing the leading zero if presented
                                if (inputValue.charAt(0) === '0') {
                                    inputValue = inputValue.substring(1);
                                }
                                if (inputValue.length > MAX_LENGTH_BASIC_CONTRACT_NUMBER) {
                                    inputValue = inputValue.substring(0, MAX_LENGTH_BASIC_CONTRACT_NUMBER);
                                }
                                return inputValue;
                            }
                            case 'offer-number': {
                                inputValue = input.value.replace(/\D/g, '');
                                if (inputValue.length > MAX_LENGTH_OFFER_NUMBER) {
                                    inputValue = inputValue.substring(0, MAX_LENGTH_OFFER_NUMBER);
                                }
                                return inputValue;
                            }
                            case 'claim-number': {
                                inputValue = input.value.replace(/[^\dXx]/g, '');
                                const inputParts = [
                                    inputValue.substring(0, MAX_LENGTH_CLAIM_NUMBER - 1),
                                    inputValue.substring(MAX_LENGTH_CLAIM_NUMBER - 1, MAX_LENGTH_CLAIM_NUMBER),
                                    inputValue.substring(MAX_LENGTH_CLAIM_NUMBER),
                                ].filter(val => val.length > 0);
                                switch (inputParts.length) {
                                    case 1:
                                        inputValue = `${inputParts[0].replace(/\D/g, '')}`;
                                        break;
                                    case 2:
                                        inputValue = `${inputParts[0].replace(/\D/g, '')}${inputParts[1]}`;
                                        break;
                                    default:
                                        inputValue = `${inputParts[0].replace(/\D/g, '')}${inputParts[1]}${(_a = inputParts[2]) === null || _a === void 0 ? void 0 : _a.replace(/\D/g, '')}`;
                                }
                                if (inputValue.length > MAX_LENGTH_CLAIM_NUMBER) {
                                    inputValue = inputValue.substring(0, MAX_LENGTH_CLAIM_NUMBER);
                                }
                                return inputValue;
                            }
                            case 'be-enterprise-number': {
                                inputValue = input.value.replace(/\D/g, '');
                                if (inputValue.length > MAX_LENGTH_BE_ENTERPRISE_NUMBER) {
                                    inputValue = inputValue.substring(0, MAX_LENGTH_BE_ENTERPRISE_NUMBER);
                                }
                                return inputValue;
                            }
                            case 'be-iban': {
                                inputValue = input.value.replace(/\D/g, '');
                                if (inputValue.length > MAX_LENGTH_BE_IBAN) {
                                    inputValue = inputValue.substring(0, MAX_LENGTH_BE_IBAN);
                                }
                                return inputValue;
                            }
                            default:
                                return input.value;
                        }
                    }
                }
                else {
                    this.inputValue = input.value;
                }
            }
            return '';
        };
        this.onInput = (ev) => {
            var _a, _b;
            const input = getInputTarget(ev);
            const cursorPositionStart = (_a = ev.target) === null || _a === void 0 ? void 0 : _a.selectionStart;
            const cursorPositionEnd = (_b = ev.target) === null || _b === void 0 ? void 0 : _b.selectionEnd;
            this.inputValue = this.getInputValue();
            if (input) {
                if (input.value) {
                    switch (this.mask) {
                        case 'vehicle-registration-number': {
                            input.value = formatVehicleRegistrationNumber(this.inputValue);
                            if (cursorPositionStart < this.inputValue.length) {
                                input.setSelectionRange(cursorPositionStart, cursorPositionEnd);
                            }
                            break;
                        }
                        case 'contract-number':
                        case 'basic-contract-number': {
                            input.value = formatPolicy(this.inputValue);
                            if (cursorPositionStart < this.inputValue.length) {
                                input.setSelectionRange(cursorPositionStart, cursorPositionEnd);
                            }
                            break;
                        }
                        case 'offer-number': {
                            input.value = formatOffer(this.inputValue);
                            if (cursorPositionStart < this.inputValue.length) {
                                input.setSelectionRange(cursorPositionStart, cursorPositionEnd);
                            }
                            break;
                        }
                        case 'claim-number': {
                            input.value = formatClaim(this.inputValue);
                            if (cursorPositionStart < this.inputValue.length) {
                                input.setSelectionRange(cursorPositionStart, cursorPositionEnd);
                            }
                            break;
                        }
                        case 'be-enterprise-number': {
                            input.value = formatBeEnterpriseNumber(this.inputValue);
                            if (cursorPositionStart < this.inputValue.length) {
                                input.setSelectionRange(cursorPositionStart, cursorPositionEnd);
                            }
                            break;
                        }
                        case 'be-iban': {
                            input.value = formatBeIBAN(this.inputValue);
                            if (cursorPositionStart < this.inputValue.length) {
                                input.setSelectionRange(cursorPositionStart, cursorPositionEnd);
                            }
                            break;
                        }
                        default:
                            this.inputValue = input.value;
                    }
                }
                else {
                    this.inputValue = input.value;
                }
            }
            this.balInput.emit(this.inputValue);
        };
        this.onFocus = (ev) => inputHandleFocus(this, ev);
        this.onBlur = (ev) => {
            inputHandleBlur(this, ev);
            const input = ev.target;
            if (input) {
                if (this.mask === undefined) {
                    input.value = this.getFormattedValue();
                }
                inputHandleChange(this);
            }
        };
        this.onKeydown = (ev) => {
            if (this.mask !== undefined && !isNil(ev) && !isCtrlOrCommandKey(ev)) {
                let inputLength = 0;
                if (this.inputValue) {
                    inputLength = this.inputValue.length;
                }
                if (!(this.getMaskAllowedKeys().includes(ev.key) ||
                    (this.mask === 'claim-number' &&
                        (ev.key === 'X' || ev.key === 'x') &&
                        inputLength >= MAX_LENGTH_CLAIM_NUMBER - 1))) {
                    // do not trigger next event -> on input
                    return stopEventBubbling(ev);
                }
            }
            if (this.allowedKeyPress && !this.mask && !isNil(ev) && !isCtrlOrCommandKey(ev)) {
                const regex = new RegExp('^' + this.allowedKeyPress + '$');
                if (!regex.test(ev.key) && ![...ACTION_KEYS].includes(ev.key)) {
                    return stopEventBubbling(ev);
                }
            }
        };
        this.onClick = (ev) => inputHandleClick(this, ev);
        this.handleClick = (ev) => inputHandleHostClick(this, ev);
    }
    createLogger(log) {
        this.log = log;
    }
    debounceChanged() {
        this.balChange = debounceEvent(this.balChange, this.debounce);
    }
    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);
        }
    }
    connectedCallback() {
        this.debounceChanged();
        this.initialValue = this.value || '';
    }
    componentWillLoad() {
        this.inheritedAttributes = inheritAttributes(this.el, ['aria-label', 'tabindex', 'title', 'data-hj-allow']);
    }
    componentDidLoad() {
        this.inputValue = this.value;
    }
    /**
     * Sets focus on the native `input` in `bal-input`. Use this method instead of the global
     * `input.focus()`.
     */
    async setFocus() {
        inputSetFocus(this);
    }
    /**
     * Sets blur on the native `input` in `bal-input`. Use this method instead of the global
     * `input.blur()`.
     * @internal
     */
    async setBlur() {
        inputSetBlur(this);
    }
    /**
     * Returns the native `<input>` element used under the hood.
     */
    getInputElement() {
        return Promise.resolve(this.nativeInput);
    }
    /**
     * @internal
     */
    async setAriaForm(ariaForm) {
        this.ariaForm = Object.assign({}, ariaForm);
    }
    getRawValue() {
        const value = (this.value || '').toString();
        return value;
    }
    getFormattedValue() {
        const value = this.getRawValue();
        const suffix = this.suffix !== undefined && value !== undefined && value !== '' ? ' ' + this.suffix : '';
        return `${value}${suffix}`;
    }
    getMaskAllowedKeys() {
        return [...NUMBER_KEYS, ...ACTION_KEYS];
    }
    render() {
        let value = this.focused ? this.getRawValue() : this.getFormattedValue();
        if (this.mask !== undefined) {
            switch (this.mask) {
                case 'contract-number':
                case 'basic-contract-number':
                    value = formatPolicy(value);
                    break;
                case 'claim-number':
                    value = formatClaim(value);
                    break;
                case 'offer-number':
                    value = formatOffer(value);
                    break;
                case 'be-enterprise-number':
                    value = formatBeEnterpriseNumber(value);
                    break;
                case 'be-iban':
                    value = formatBeIBAN(value);
                    break;
                case 'vehicle-registration-number':
                    value = formatVehicleRegistrationNumber(value);
                    break;
            }
        }
        let inputProps = {};
        if (this.pattern) {
            inputProps = { pattern: this.pattern };
        }
        const block = BEM.block('input');
        const id = this.ariaForm.controlId || this.inputId;
        return (h(Host, { key: 'b23e60aee1d98ef130c5a6526f0d8d4b59295732', onClick: this.handleClick, "aria-disabled": ariaBooleanToString(this.disabled), class: Object.assign({}, block.class()) }, h("input", Object.assign({ key: '9a62bde670992ae4357f6e2747a2a10170d890c2', class: {
                'input': true,
                'is-disabled': this.disabled || this.readonly,
                'is-danger': this.invalid,
                'is-clickable': this.clickable,
                'bal-focusable': !this.disabled,
                'has-icon-right': this.hasIconRight,
                'has-text-centered': this.textAlign === 'center',
                'has-text-right': this.textAlign === 'right',
            }, "data-testid": "bal-input", ref: inputEl => (this.nativeInput = inputEl), id: id, "aria-labelledby": this.ariaForm.labelId, "aria-describedby": this.ariaForm.messageId, "aria-invalid": this.invalid === true ? 'true' : 'false', "aria-disabled": ariaBooleanToString(this.disabled), disabled: this.disabled, accept: this.accept, inputMode: this.inputmode, autoCapitalize: this.autocapitalize, autocomplete: this.autocomplete, autocorrect: this.autocorrect, autofocus: this.autofocus, min: this.min, max: this.max, minLength: this.minLength, maxLength: this.maxLength, multiple: this.multiple, name: this.name, placeholder: this.placeholder || '', readonly: this.readonly, required: this.required, spellcheck: this.spellcheck, type: this.type, value: value, onFocus: this.onFocus, onInput: ev => this.onInput(ev), onKeyDown: e => this.onKeydown(e), onBlur: this.onBlur, onClick: this.onClick, onKeyPress: e => this.balKeyPress.emit(e) }, inputProps, this.inheritedAttributes))));
    }
    get el() { return getElement(this); }
    static get watchers() { return {
        "debounce": ["debounceChanged"]
    }; }
};
__decorate([
    Logger('bal-input'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Function]),
    __metadata("design:returntype", void 0)
], Input.prototype, "createLogger", null);
let InputIds = 0;
Input.style = balInputCss;

export { Input as bal_input };
