import { Host, h } from "@stencil/core";
export class CpslCodeInput {
    constructor() {
        this.handleInput = (ind, ev) => {
            var _a;
            const inputElements = this.inputs;
            // If getting an insertFromPaste remove the last element value since the value setting is handled in the paste event
            if (ev.inputType === 'insertFromPaste') {
                inputElements[Math.min(this.length - 1, ind)].value = '';
                return;
            }
            if (ev.inputType === 'insertText') {
                if (this.type === 'number' && isNaN(parseInt(ev.data))) {
                    inputElements[ind].value = '';
                    return;
                }
                // Prevent input beyond the maximum length
                if (this.code && this.code.length >= this.length) {
                    inputElements[ind].value = this.code[ind] || '';
                    return;
                }
                const newCode = `${(_a = this.code) !== null && _a !== void 0 ? _a : ''}${ev.data}`;
                // Ensure we don't exceed the maximum length
                if (newCode.length > this.length) {
                    const truncatedCode = newCode.substring(0, this.length);
                    this.cpslInput.emit({ value: truncatedCode });
                    this.code = truncatedCode;
                    // Set each input to its corresponding character
                    inputElements.forEach((input, index) => {
                        input.value = truncatedCode[index] || '';
                    });
                }
                else {
                    inputElements[Math.min(this.length - 1, newCode.length)].focus();
                    this.cpslInput.emit({ value: newCode });
                    this.code = newCode;
                }
            }
        };
        this.handleKeyDown = (ind, ev) => {
            const inputElements = this.inputs;
            switch (ev.key) {
                case 'Backspace': {
                    let newCode;
                    if (!inputElements[ind].value) {
                        inputElements[Math.max(0, ind - 1)].value = '';
                        inputElements[Math.max(0, ind - 1)].focus();
                        newCode = this.code.substring(0, ind - 1);
                    }
                    else {
                        newCode = this.code.substring(0, ind);
                    }
                    this.cpslInput.emit({ value: newCode });
                    this.code = newCode;
                    break;
                }
                case 'ArrowLeft': {
                    setTimeout(() => {
                        this.inputs[ind].setSelectionRange(1, 1);
                    }, 0);
                    break;
                }
                default: {
                    break;
                }
            }
        };
        this.handleFocus = (ind) => {
            const inputElements = this.inputs;
            for (const input of inputElements) {
                if (!input.value) {
                    input.focus();
                    break;
                }
                else if (input.id === `code-input-${this.length - 1}`) {
                    input.focus();
                    break;
                }
            }
            setTimeout(() => {
                inputElements[ind].setSelectionRange(1, 1);
            }, 0);
        };
        this.handlePaste = (e) => {
            const inputElements = this.inputs;
            let pastedCode = e.clipboardData.getData('text');
            // Filter based on type
            if (this.type === 'number') {
                // Remove all non-numeric characters
                pastedCode = pastedCode.replace(/\D/g, '');
                // If no valid numbers remain, clear and return
                if (!pastedCode) {
                    setTimeout(() => {
                        inputElements[0].value = '';
                    }, 0);
                    return;
                }
            }
            // Truncate pasted code to match the expected length
            const truncatedCode = pastedCode.substring(0, this.length);
            this.cpslInput.emit({
                value: truncatedCode,
            });
            inputElements.forEach((input, index) => {
                input.value = truncatedCode.charAt(index) || '';
            });
            inputElements[Math.min(this.length - 1, truncatedCode.length)].focus();
        };
        this.code = undefined;
        this.errorText = undefined;
        this.helperText = undefined;
        this.length = undefined;
        this.type = 'number';
    }
    get inputs() {
        return Array.from(this.el.shadowRoot.querySelectorAll('input'));
    }
    render() {
        var _a;
        return (h(Host, { key: '090ef84f543cea35b4e128c5ec2bbcd188bb2a86' }, h("div", { key: '93d16d0a74e81cd367f8ee23bfbfea8118b39b0c', class: "code-container" }, new Array(this.length).fill(0).map((_, i) => {
            var _a, _b;
            return (h("input", { class: { 'code-input': true, 'error': Boolean(this.errorText), 'has-value': ((_a = this.code) === null || _a === void 0 ? void 0 : _a[i]) !== undefined }, id: `code-input-${i}`, onKeyDown: ev => this.handleKeyDown(i, ev), onInput: ev => this.handleInput(i, ev), onFocus: () => this.handleFocus(i), onPaste: this.handlePaste, min: 0, max: 9, value: (_b = this.code) === null || _b === void 0 ? void 0 : _b[i], inputMode: this.type === 'number' ? 'numeric' : 'text' }));
        })), (this.errorText || this.helperText) && (h("div", { key: 'ae9ccf7cb7736ab4ad186f6d317afbb0f58a518c', class: { 'helper-text-container': true, 'error-text': Boolean(this.errorText) } }, h("cpsl-icon", { key: '1fb36b201fe1aa1640b39900881e8b1eaeff614d', icon: this.errorText ? 'alertCircle' : 'infoCircle' }), h("span", { key: '30cc9abb139ef14dca8fae44dfcbb61002e1ca6d' }, (_a = this.errorText) !== null && _a !== void 0 ? _a : this.helperText)))));
    }
    static get is() { return "cpsl-code-input"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["cpsl-code-input.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["cpsl-code-input.css"]
        };
    }
    static get properties() {
        return {
            "code": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Value of the code."
                },
                "attribute": "code",
                "reflect": false
            },
            "errorText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Error text to show below the input. If this is provided the input will enter an error state."
                },
                "attribute": "error-text",
                "reflect": false
            },
            "helperText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Helper text to show below the input. If `\"errorText\"` is provided that will take precedence."
                },
                "attribute": "helper-text",
                "reflect": false
            },
            "length": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Length of the code."
                },
                "attribute": "length",
                "reflect": false
            },
            "type": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "'number' | 'string'",
                    "resolved": "\"number\" | \"string\"",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Type of characters to accept in the code.\nDefaults to number."
                },
                "attribute": "type",
                "reflect": false,
                "defaultValue": "'number'"
            }
        };
    }
    static get events() {
        return [{
                "method": "cpslInput",
                "name": "cpslInput",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "The `cpslInput` event is fired each time the user modifies the input's value."
                },
                "complexType": {
                    "original": "CodeChangeEventDetail",
                    "resolved": "CodeChangeEventDetail",
                    "references": {
                        "CodeChangeEventDetail": {
                            "location": "import",
                            "path": "./code-change-interface.js",
                            "id": "src/components/cpsl-code-input/code-change-interface.ts::CodeChangeEventDetail"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "el"; }
}
//# sourceMappingURL=cpsl-code-input.js.map
