// #region Imports
var __decorate = (this && this.__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;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { waitForEvent } from '@breadstone/mosaik-elements';
import { DomServiceLocator } from '../../../../Dom/Dom';
import { Appearanceable } from '../../../Behaviors/Appearanceable';
import { Disableable } from '../../../Behaviors/Disableable';
import { Invalidable } from '../../../Behaviors/Invalidable';
import { Themeable } from '../../../Behaviors/Themeable';
import { Valueable } from '../../../Behaviors/Valueable';
import { Variantable } from '../../../Behaviors/Variantable';
import { KeyboardController } from '../../../Controllers/KeyboardController';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Component } from '../../../Decorators/ComponentDecorator';
import { Key } from '../../../Types/Key';
import { PinMode } from '../../../Types/PinMode';
import { FocusRingElement } from '../../Primitives/FocusRing/FocusRingElement';
import { InputBaseElement } from '../Abstracts/InputBase';
import { pinBoxElementTemplate } from './PinBoxElementTemplate';
import { pinBoxElementCosmopolitanStyle } from './Themes/PinBoxElement.Cosmopolitan';
import { pinBoxElementJoyStyle } from './Themes/PinBoxElement.Joy';
import { pinBoxElementMemphisStyle } from './Themes/PinBoxElement.Memphis';
// #endregion
/**
 * Pin Box - A secure multi-field input control for entering PIN codes and verification numbers.
 *
 * @description
 * The Pin Box component provides a specialized interface for entering personal identification numbers (PINs),
 * verification codes, and other secure numeric sequences. It displays a series of individual input fields,
 * each accepting a single character, creating a familiar PIN entry experience. Features include automatic
 * cursor advancement between fields, backspace navigation, support for both visible and masked input modes,
 * keyboard navigation with arrow keys, paste support for quick entry, configurable field count, validation
 * support, and comprehensive accessibility features. The component ensures secure input handling and provides
 * visual feedback for each character position. Ideal for authentication flows, two-factor authentication,
 * security verification, and any scenario requiring secure code entry.
 *
 * @name Pin Box
 * @element mosaik-pinbox
 * @category Inputs
 *
 * @csspart root - The root container for all PIN input fields.
 * @csspart focusRing - The focus ring indicator for each input field.
 * @csspart input - Individual PIN digit input fields.
 *
 * @cssprop {Color} --pin-box-background-color - The background color.
 * @cssprop {Color} --pin-box-border-color - The border color.
 * @cssprop {String} --pin-box-border-radius - The border radius.
 * @cssprop {String} --pin-box-border-style - The border style.
 * @cssprop {String} --pin-box-border-width - The border width.
 * @cssprop {String} --pin-box-font-family - The font family.
 * @cssprop {String} --pin-box-font-size - The font size.
 * @cssprop {String} --pin-box-font-weight - The font weight.
 * @cssprop {Color} --pin-box-foreground-color - The foreground color.
 * @cssprop {String} --pin-box-gap - The gap between input fields.
 * @cssprop {String} --pin-box-height - The height.
 * @cssprop {String} --pin-box-padding-bottom - The padding bottom.
 * @cssprop {String} --pin-box-padding-left - The padding left.
 * @cssprop {String} --pin-box-padding-right - The padding right.
 * @cssprop {String} --pin-box-padding-top - The padding top.
 * @cssprop {String} --pin-box-shadow - The shadow.
 * @cssprop {String} --pin-box-transition-duration - The transition duration.
 * @cssprop {String} --pin-box-width - The width.
 *
 * @dependency mosaik-focus-ring - Used for focus indication on each input field.
 *
 * @keyhandle Backspace - Deletes the character to the left of the cursor.
 * @keyhandle LeftArrow - Moves the cursor to the left.
 * @keyhandle RightArrow - Moves the cursor to the right.
 *
 * @example
 * ```html
 * <mosaik-pinbox
 *   length="6"
 *   mode="password"
 *   placeholder="•">
 * </mosaik-pinbox>
 * ```
 *
 * @example
 * ```html
 * <mosaik-pinbox
 *   length="4"
 *   mode="text"
 *   pattern="[0-9]"
 *   required>
 * </mosaik-pinbox>
 * ```
 *
 * @public
 */
let PinBoxElement = class PinBoxElement extends Themeable(Disableable(Invalidable(Valueable(Variantable(Appearanceable(InputBaseElement)))))) {
    // #region Fields
    _keyboardController;
    _inputElement;
    _value;
    _readonly;
    _required;
    _autofocus;
    _name;
    _pattern;
    _placeholder;
    _autocomplete;
    _length;
    _focusedIndex;
    _mode;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        this._value = '';
        this._readonly = false;
        this._required = false;
        this._autofocus = false;
        this._name = '';
        this._pattern = '';
        this._placeholder = '';
        this._autocomplete = false;
        this._length = 4;
        this._focusedIndex = -1;
        this._mode = PinMode.Text;
        this._keyboardController = new KeyboardController(this);
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `{@link is}` property.
     * The `{@link is}` property represents natural name of this element.
     *
     * @public
     * @static
     * @readonly
     */
    static get is() {
        return 'mosaik-pinbox';
    }
    /**
     * Gets or sets the `value` property.
     *
     * @public
     * @override
     */
    get value() {
        return this._value;
    }
    set value(value) {
        if (this._value !== value) {
            this._value = value;
            this.requestUpdate('value');
        }
    }
    /**
     * Gets or sets the `readonly` property.
     *
     * @public
     * @attr
     */
    get readonly() {
        return this._readonly;
    }
    set readonly(value) {
        if (this._readonly !== value) {
            this._readonly = value;
            this.requestUpdate('readonly');
        }
    }
    /**
     * Gets or sets the `required` property.
     *
     * @public
     * @attr
     */
    get required() {
        return this._required;
    }
    set required(value) {
        if (this._required !== value) {
            this._required = value;
            this.requestUpdate('required');
        }
    }
    /**
     * Gets or sets the `autofocus` property.
     *
     * @public
     * @override
     */
    get autofocus() {
        return this._autofocus;
    }
    set autofocus(value) {
        if (this._autofocus !== value) {
            this._autofocus = value;
            this.requestUpdate('autofocus');
        }
    }
    /**
     * Gets or sets the `name` property.
     *
     * @public
     * @attr
     */
    get name() {
        return this._name;
    }
    set name(value) {
        if (this._name !== value) {
            this._name = value;
            this.requestUpdate('name');
        }
    }
    /**
     * Gets or sets the `pattern` property.
     *
     * @public
     * @attr
     */
    get pattern() {
        return this._pattern;
    }
    set pattern(value) {
        if (this._pattern !== value) {
            this._pattern = value;
            this.requestUpdate('pattern');
        }
    }
    /**
     * Gets or sets the `placeholder` property.
     *
     * @public
     * @attr
     */
    get placeholder() {
        return this._placeholder;
    }
    set placeholder(value) {
        if (this._placeholder !== value) {
            this._placeholder = value;
            this.requestUpdate('placeholder');
        }
    }
    /**
     * Gets or sets the `autocomplete` property.
     *
     * @public
     * @attr
     */
    get autocomplete() {
        return this._autocomplete;
    }
    set autocomplete(value) {
        if (this._autocomplete !== value) {
            this._autocomplete = value;
            this.requestUpdate('autocomplete');
        }
    }
    /**
     * Gets or sets the `length` property.
     *
     * @public
     * @attr
     */
    get length() {
        return this._length;
    }
    set length(value) {
        if (this._length !== value) {
            this._length = value;
            this.requestUpdate('length');
        }
    }
    /**
     * Gets or sets the `mode` property.
     *
     * @public
     * @attr
     */
    get mode() {
        return this._mode;
    }
    set mode(value) {
        if (this._mode !== value) {
            this._mode = value;
            this.requestUpdate('mode');
        }
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    connectedCallback() {
        super.connectedCallback();
        this.on('paste', (e) => {
            e.preventDefault();
            this.setValue(e.clipboardData?.getData('text/plain') ?? '');
        });
        this._keyboardController
            .add([
            Key.Backspace,
            Key.LeftArrow
        ], () => {
            const current = this.getInputs()[this._focusedIndex];
            requestAnimationFrame(() => {
                if (!current.value.length || current.selectionStart === 0) {
                    this.getInputs()[this._focusedIndex - 1]?.focus();
                }
            });
        })
            .add([Key.RightArrow], () => {
            const current = this.getInputs()[this._focusedIndex];
            requestAnimationFrame(() => {
                if (!current.value.length || current.selectionStart === 1) {
                    this.getInputs()[this._focusedIndex + 1]?.focus();
                }
            });
        });
    }
    /**
     * @public
     * @override
     */
    focus() {
        if (this.shadowRoot) {
            DomServiceLocator.current.findDescendant(this.shadowRoot, 'input')?.focus();
        }
    }
    /**
     * @public
     * @override
     */
    blur() {
        if (this.shadowRoot) {
            DomServiceLocator.current.findDescendant(this.shadowRoot, 'input')?.blur();
        }
    }
    /**
     * @public
     */
    clear() {
        this.value = '';
        this.removeAttribute('value');
        this.emit('change', {
            bubbles: true,
            composed: true
        });
        // afterwards focus the input
        this.focus();
    }
    /**
     * Resets the value, all kinds of validation and errors.
     *
     * @public
     * @override
     */
    reset() {
        super.reset();
        this.clear();
        this.invalid = false;
    }
    /**
     * Checks the validity of the element and returns `true` if it is valid; otherwise, `false`.
     *
     * @public
     * @override
     */
    checkValidity() {
        return this.shadowRoot
            ? this._inputElement.checkValidity()
            : true;
    }
    /**
     * @protected
     * @template
     */
    onChange(event) {
        this.setValue(event.target.value);
        this.emit('change', { detail: this.value });
    }
    /**
     * @protected
     * @override
     * @template
     */
    onInput(event) {
        super.onInput(event);
        this.setValue(event.target.value);
        this.emit('input', { detail: this.value });
    }
    /**
     * @protected
     * @override
     * @template
     */
    onFocus(event) {
        super.onFocus(event);
        this._focusedIndex = this.getInputs().indexOf(event.target);
        this.emit('focus', { detail: event });
    }
    /**
     * @protected
     * @override
     */
    onBlur(event) {
        super.onBlur(event);
        this._focusedIndex = -1;
        this.emit('blur', { detail: event });
    }
    /**
     * @protected
     * @override
     */
    onApplyTemplate() {
        super.onApplyTemplate();
        this._inputElement = this.getTemplatePart('input');
    }
    /**
     * @private
     */
    getInputValues() {
        return this.getInputs().map((x) => x.value);
    }
    /**
     * @private
     */
    getInputs() {
        return this.shadowRoot
            ? DomServiceLocator.current.findDescendants(this.shadowRoot, 'input') ?? []
            : [];
    }
    /**
     * @private
     */
    replaceAt(array, index, value) {
        const newArray = [...array];
        newArray[index] = value;
        return newArray;
    }
    /**
     * @private
     */
    setValue(value) {
        const startIndex = this._focusedIndex;
        const rangeValue = value.substring(0, this._length);
        const rangeValueLength = rangeValue.length;
        if (rangeValueLength > 1) {
            for (let i = startIndex; i < rangeValue.length; i++) {
                const char = rangeValue[i];
                const input = this.getInputs()[i];
                // set value of input
                input.value = char;
                // afterwards, focus next input
                void waitForEvent(input, 'blur').then(() => {
                    this.getInputs()[i + 1]?.focus();
                });
                input.blur();
            }
        }
        else {
            const char = rangeValue;
            const input = this.getInputs()[startIndex];
            // set value of input
            input.value = char;
            // afterwards, focus next input
            void waitForEvent(input, 'blur').then(() => {
                this.getInputs()[startIndex + 1]?.focus();
            });
            input.blur();
        }
        this.value = this.getInputValues().join('');
    }
};
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], PinBoxElement.prototype, "value", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], PinBoxElement.prototype, "readonly", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], PinBoxElement.prototype, "required", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], PinBoxElement.prototype, "autofocus", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], PinBoxElement.prototype, "name", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], PinBoxElement.prototype, "pattern", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], PinBoxElement.prototype, "placeholder", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], PinBoxElement.prototype, "autocomplete", null);
__decorate([
    Attribute({ type: Number }),
    __metadata("design:type", Number),
    __metadata("design:paramtypes", [Number])
], PinBoxElement.prototype, "length", null);
__decorate([
    Attribute({ type: PinMode }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], PinBoxElement.prototype, "mode", null);
PinBoxElement = __decorate([
    Component({
        selector: 'mosaik-pinbox',
        template: pinBoxElementTemplate,
        themes: {
            joy: pinBoxElementJoyStyle,
            memphis: pinBoxElementMemphisStyle,
            cosmopolitan: pinBoxElementCosmopolitanStyle
        },
        host: {
            tabIndex: '0'
        },
        imports: [FocusRingElement]
    }),
    __metadata("design:paramtypes", [])
], PinBoxElement);
export { PinBoxElement };
//# sourceMappingURL=PinBoxElement.js.map