// #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 { HTMLElementEventEmitter } from '@breadstone/mosaik-elements';
import { DomServiceLocator } from '../../../../Dom/Dom';
import { Emit } from '../../../../events/Decorators/EmitDecorator';
import { Appearanceable } from '../../../Behaviors/Appearanceable';
import { Clearable } from '../../../Behaviors/Clearable';
import { Disableable } from '../../../Behaviors/Disableable';
import { Invalidable } from '../../../Behaviors/Invalidable';
import { Labelable } from '../../../Behaviors/Labelable';
import { Slottable } from '../../../Behaviors/Slottable';
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, KeyName } from '../../../Types/Key';
import { ButtonElement } from '../../Buttons/Button/ButtonElement';
import { ChipElement } from '../../Media/Chip/ChipElement';
import { InputBaseElement } from '../Abstracts/InputBase';
import { chipBoxElementTemplate } from './ChipBoxElementTemplate';
import { chipBoxElementCosmopolitanStyle } from './Themes/ChipBoxElement.Cosmopolitan';
import { chipBoxElementJoyStyle } from './Themes/ChipBoxElement.Joy';
import { chipBoxElementMemphisStyle } from './Themes/ChipBoxElement.Memphis';
// #endregion
/**
 * Chip Box - A multi-selection input control for creating and managing collections of chip elements.
 *
 * @description
 * The Chip Box component provides an interactive interface for creating, managing, and displaying collections
 * of chip elements representing multiple selections or tags. Users can add new chips by typing and pressing
 * enter, remove existing chips with close buttons or backspace, and manage collections of related items.
 * Features include keyboard navigation, chip transformation functions, validation support, customizable
 * appearance and behavior, drag-and-drop reordering, and comprehensive accessibility features. The component
 * handles dynamic chip creation from text input, supports custom chip rendering, and integrates with form
 * validation systems. Perfect for tag inputs, multi-select filters, contact lists, skill collections,
 * and any interface requiring multiple item selection and management.
 *
 * @name Chip Box
 * @element mosaik-chipbox
 * @category Inputs
 *
 * @slot prefix - Content placed before the chip collection.
 * @slot suffix - Content placed after the chip collection.
 *
 * @csspart chip - Individual chip elements.
 * @csspart clear - The clear part.
 * @csspart focusRing - The focus ring indicator.
 * @csspart inner - The inner container wrapper.
 * @csspart input - The text input field for adding new chips.
 * @csspart label - The floating label element.
 * @csspart prefix - The prefix content container.
 * @csspart suffix - The suffix content container.
 * @csspart wrapper - The wrapper containing chips and input.
 *
 * @cssprop {Color} --chip-box-background-color - The background color.
 * @cssprop {Color} --chip-box-border-color - The border color.
 * @cssprop {String} --chip-box-border-radius - The border radius.
 * @cssprop {String} --chip-box-border-style - The border style.
 * @cssprop {String} --chip-box-border-width - The border width.
 * @cssprop {String} --chip-box-focus-ring-outward-offset - The box focus ring outward offset CSS custom property.
 * @cssprop {String} --chip-box-focus-ring-width - The box focus ring width CSS custom property.
 * @cssprop {String} --chip-box-font-family - The box font family CSS custom property.
 * @cssprop {String} --chip-box-font-letter-spacing - The box font letter spacing CSS custom property.
 * @cssprop {String} --chip-box-font-line-height - The box font line height CSS custom property.
 * @cssprop {String} --chip-box-font-size - The box font size CSS custom property.
 * @cssprop {String} --chip-box-font-text-decoration - The box font text decoration CSS custom property.
 * @cssprop {String} --chip-box-font-text-transform - The box font text transform CSS custom property.
 * @cssprop {String} --chip-box-font-weight - The box font weight CSS custom property.
 * @cssprop {Color} --chip-box-foreground-color - The foreground color.
 * @cssprop {String} --chip-box-gap - The gap between elements.
 * @cssprop {String} --chip-box-height - The height.
 * @cssprop {String} --chip-box-padding-bottom - The padding bottom.
 * @cssprop {String} --chip-box-padding-left - The padding left.
 * @cssprop {String} --chip-box-padding-right - The padding right.
 * @cssprop {String} --chip-box-padding-top - The padding top.
 * @cssprop {String} --chip-box-prefix-icon-size - The box prefix icon size CSS custom property.
 * @cssprop {String} --chip-box-shadow - The shadow.
 * @cssprop {String} --chip-box-shadow-blur - The box shadow blur CSS custom property.
 * @cssprop {String} --chip-box-shadow-color - The box shadow color CSS custom property.
 * @cssprop {String} --chip-box-shadow-offset-x - The box shadow offset x CSS custom property.
 * @cssprop {String} --chip-box-shadow-offset-y - The box shadow offset y CSS custom property.
 * @cssprop {String} --chip-box-shadow-spread - The box shadow spread CSS custom property.
 * @cssprop {String} --chip-box-suffix-icon-size - The box suffix icon size CSS custom property.
 * @cssprop {String} --chip-box-transition-duration - The box transition duration CSS custom property.
 * @cssprop {String} --chip-box-transition-mode - The box transition mode CSS custom property.
 * @cssprop {String} --chip-box-transition-property - The box transition property CSS custom property.
 * @cssprop {String} --chip-box-translate - The box translate CSS custom property.
 *
 * @fires cleared {ClearedEvent} - Fired when the value is cleared.
 * @fires chipAdded {ChipAddedEvent} - Fired when a chip is added.
 * @fires chipRemoved {ChipRemovedEvent} - Fired when a chip is removed.
 *
 * @dependency mosaik-button - The Button element.
 * @dependency mosaik-chip - Used for individual chip elements.
 * @dependency mosaik-focus-ring - Used for focus indication.
 *
 * @example
 * Basic chip box with label and placeholder:
 * ```html
 * <mosaik-chipbox
 *   label="Skills"
 *   placeholder="Add a skill...">
 * </mosaik-chipbox>
 * ```
 *
 * @example
 * Chip box pre-populated with chips:
 * ```html
 * <mosaik-chipbox
 *   label="Tags"
 *   chips="JavaScript TypeScript React">
 * </mosaik-chipbox>
 * ```
 *
 * @example
 * Chip box with clearable option and variant styling:
 * ```html
 * <mosaik-chipbox
 *   label="Selected items"
 *   placeholder="Add item..."
 *   is-clearable
 *   variant="primary">
 * </mosaik-chipbox>
 * ```
 *
 * @public
 */
let ChipBoxElement = class ChipBoxElement extends Themeable(Slottable(Clearable(Disableable(Invalidable(Valueable(Variantable(Appearanceable(Labelable(InputBaseElement))))))))) {
    // #region Fields
    _keyboardController;
    _chipAdded;
    _chipRemoved;
    _chipElements;
    _inputElement;
    _isEditable;
    _readonly;
    _pressBackspaceToRemove;
    _chips;
    _separatorKeys;
    _transform;
    _value;
    _required;
    _autofocus;
    _name;
    _pattern;
    _placeholder;
    _autocomplete;
    // #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._isEditable = false;
        this._readonly = false;
        this._chips = [];
        this._separatorKeys = new Array(Key.Enter, Key.Comma);
        this._pressBackspaceToRemove = false;
        this._transform = null;
        this._chipAdded = new HTMLElementEventEmitter(this, 'chipAdded');
        this._chipRemoved = new HTMLElementEventEmitter(this, 'chipRemoved');
        this._keyboardController = new KeyboardController(this);
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `is` property.
     * The `is` property represents natural name of this element.
     *
     * @public
     * @static
     * @readonly
     */
    static get is() {
        return 'mosaik-chipbox';
    }
    /**
     * 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 `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 `isEditable` property.
     *
     * @public
     * @attr
     */
    get isEditable() {
        return this._isEditable;
    }
    set isEditable(value) {
        if (this._isEditable !== value) {
            this._isEditable = value;
            this.requestUpdate('isEditable');
        }
    }
    /**
     * 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 `pressBackspaceToRemove` property.
     *
     * @public
     * @attr
     */
    get pressBackspaceToRemove() {
        return this._pressBackspaceToRemove;
    }
    set pressBackspaceToRemove(value) {
        if (this._pressBackspaceToRemove !== value) {
            this._pressBackspaceToRemove = value;
            this.requestUpdate('pressBackspaceToRemove');
        }
    }
    /**
     * Gets or sets the `chips` property.
     *
     * @public
     * @attr
     */
    get chips() {
        return this._chips;
    }
    set chips(value) {
        const safeValue = Array.isArray(value)
            ? [...value]
            : [];
        if (this._chips !== safeValue) {
            this._chips = safeValue;
            this.requestUpdate('chips');
        }
    }
    /**
     * Gets or sets the `separatorKeys` property.
     *
     * @public
     * @attr
     */
    get separatorKeys() {
        return this._separatorKeys;
    }
    set separatorKeys(value) {
        if (this._separatorKeys !== value) {
            this._separatorKeys = value;
            this.requestUpdate('separatorKeys');
        }
    }
    /**
     * Gets or sets the `transform` property.
     *
     * @public
     * @attr
     */
    get transform() {
        return this._transform;
    }
    set transform(value) {
        if (this._transform !== value) {
            this._transform = value;
            this.requestUpdate('transform');
        }
    }
    /**
     * Determines whether the element has a prefix or not.
     * The Prefix is a slot that is displayed before the input.
     *
     * @private
     * @readonly
     * @attr
     */
    get hasPrefix() {
        return this.hasSlotContent('prefix');
    }
    /**
     * Determines whether the element has a suffix or not.
     * The Suffix is a slot that is displayed after the input.
     *
     * @private
     * @readonly
     * @attr
     */
    get hasSuffix() {
        return this.hasSlotContent('suffix');
    }
    /**
     * Called when a chip is added.
     * Provides reference to `{chip: unknown}` as event argument.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get chipAdded() {
        return this._chipAdded;
    }
    /**
     * Called when a chip is removed.
     * Provides reference to `{chip: unknown}` as event argument.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get chipRemoved() {
        return this._chipRemoved;
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    connectedCallback() {
        super.connectedCallback();
        this._keyboardController
            .add([Key.LeftArrow], (event) => {
            // check if input is focused
            if (this.shadowRoot?.activeElement === this._inputElement) {
                // detect the cursor position of the input
                const isStart = this._inputElement.selectionStart === 0;
                if (isStart) {
                    event?.preventDefault();
                    // focus the last chip
                    this._chipElements[this.chips.length - 1]?.focus();
                }
                return;
            }
            // check if chip is focused
            if (this._chipElements.some((x) => x.isFocused)) {
                event?.preventDefault();
                // focus the previous chip
                const index = this._chipElements.findIndex((x) => x.isFocused);
                this._chipElements[index - 1]?.focus();
            }
        })
            .add([Key.RightArrow], (event) => {
            // check if chip is focused
            if (this._chipElements.some((x) => x.isFocused)) {
                event?.preventDefault();
                const index = this._chipElements.findIndex((x) => x.isFocused);
                if (index === this.chips.length - 1) {
                    // if the last chip is focused, focus the input
                    this._inputElement.focus();
                }
                else {
                    // focus the next chip
                    this._chipElements[index + 1]?.focus();
                }
            }
        })
            .add([
            Key.Delete,
            Key.Backspace
        ], (event) => {
            // check if chip is focused
            if (this._chipElements.some((x) => x.isFocused)) {
                event?.preventDefault();
                const index = this._chipElements.findIndex((x) => x.isFocused);
                const chip = this.chips[index];
                this.delete(chip);
                // after deleting the chip, focus the next chip or the input
                if (index === this.chips.length - 1) {
                    this._inputElement.focus();
                }
                else {
                    this._chipElements[index]?.focus();
                }
            }
        });
        this.on('click', () => this.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();
        }
    }
    /**
     * Clears the value of the element but not the validation.
     *
     * @public
     * @override
     */
    clear(force) {
        const isCleared = super.clear(force);
        if (isCleared) {
            if (!this.readonly) {
                this.emit('input', {
                    bubbles: true,
                    composed: true
                });
            }
            this.emit('change', {
                bubbles: true,
                composed: true
            });
        }
        return isCleared;
    }
    /**
     * 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;
    }
    /**
     * @public
     */
    add(chip) {
        // disallow duplicates
        if (this.chips.includes(chip)) {
            return;
        }
        this.chips = [
            ...this.chips,
            chip
        ];
        this.onChipAdded({ chip: chip });
        this.clear();
    }
    /**
     * @public
     */
    delete(chip) {
        if (!this._isEditable) {
            return;
        }
        // remove chip from chip list
        const index = this._chips.indexOf(chip);
        if (index > -1) {
            this.chips = [
                ...this._chips.slice(0, index),
                ...this._chips.slice(index + 1)
            ];
            this.onChipRemoved({ chip: chip });
        }
        this.clear();
    }
    /**
     * @private
     * @template
     */
    onKeyUp(event) {
        event.preventDefault();
        if (!this._isEditable) {
            return;
        }
        if (this._separatorKeys.includes(event.keyCode)) {
            if (this._inputElement.value.trim() !== '') {
                const chip = this._inputElement.value.replace(String.fromCharCode(event.keyCode), '');
                this.add(chip);
            }
            this.clear();
        }
    }
    /**
     * @private
     * @template
     */
    onKeyDown(event) {
        if (event.key !== KeyName.Backspace) {
            return;
        }
        const shouldHandleBackspace = this._pressBackspaceToRemove && this._inputElement.value === '' && this.chips.length > 0;
        if (!shouldHandleBackspace) {
            return;
        }
        event.preventDefault();
        const chips = this._chipElements;
        const isChipFocused = chips.some((chip) => chip.isFocused);
        const isInputFocused = this._inputElement === this.shadowRoot?.activeElement;
        if (!isInputFocused && isChipFocused) {
            const chip = this.chips[this.chips.length - 1];
            this.delete(chip);
            return;
        }
        this._chipElements[this.chips.length - 1]?.focus();
    }
    /**
     * @private
     * @template
     */
    onPaste(event) {
        event.stopPropagation();
        const paste = event.clipboardData?.getData('text') ?? '';
        const chips = paste.split('\n');
        const transform = this._transform ?? ((x) => x);
        chips.forEach((x) => this.add(transform(x)));
        this.clear();
    }
    /**
     * @protected
     */
    onChipClosed(chip) {
        this.delete(chip);
    }
    /**
     * Emits the `chipAdded` event.
     *
     * @protected
     */
    onChipAdded(args) {
        this._chipAdded.emit(args);
    }
    /**
     * Emits the `chipRemoved` event.
     *
     * @protected
     */
    onChipRemoved(args) {
        this._chipRemoved.emit(args);
    }
    /**
     * @protected
     * @override
     */
    onApplyTemplate() {
        super.onApplyTemplate();
        this._inputElement = this.getTemplatePart('input');
        this._chipElements = this.getTemplateParts('chip');
    }
    /**
     * @template
     * @protected
     */
    onChange(event) {
        this.value = event.target.value;
        this.emit('change', { detail: this.value });
    }
    /**
     * @template
     * @protected
     * @override
     */
    onInput(event) {
        super.onInput(event);
        this.value = event.target.value;
        this.emit('input', { detail: this.value });
    }
    /**
     * @template
     * @protected
     * @override
     */
    onFocus(event) {
        super.onFocus(event);
        this.emit('focus', { detail: event });
    }
    /**
     * @template
     * @protected
     * @override
     */
    onBlur(event) {
        super.onBlur(event);
        // // add chip if input is not empty
        // if (this._inputElement.value.trim() !== '') {
        //     const chip = this._inputElement.value;
        //     this.add(chip);
        //     this.clear();
        // }
        this.emit('blur', { detail: event });
    }
};
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], ChipBoxElement.prototype, "value", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], ChipBoxElement.prototype, "required", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], ChipBoxElement.prototype, "autofocus", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], ChipBoxElement.prototype, "name", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], ChipBoxElement.prototype, "pattern", null);
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], ChipBoxElement.prototype, "placeholder", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], ChipBoxElement.prototype, "autocomplete", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], ChipBoxElement.prototype, "isEditable", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], ChipBoxElement.prototype, "readonly", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], ChipBoxElement.prototype, "pressBackspaceToRemove", null);
__decorate([
    Attribute({
        type: (Array),
        converter: {
            fromAttribute: (value) => {
                if (!value) {
                    return [];
                }
                return value
                    .split(' ')
                    .map((v) => v.trim());
            },
            toAttribute: (value) => value.join(' ')
        }
    }),
    __metadata("design:type", Array),
    __metadata("design:paramtypes", [Array])
], ChipBoxElement.prototype, "chips", null);
__decorate([
    Attribute({ type: (Array) }),
    __metadata("design:type", Array),
    __metadata("design:paramtypes", [Array])
], ChipBoxElement.prototype, "separatorKeys", null);
__decorate([
    Attribute({ type: Function }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [Object])
], ChipBoxElement.prototype, "transform", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [])
], ChipBoxElement.prototype, "hasPrefix", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [])
], ChipBoxElement.prototype, "hasSuffix", null);
__decorate([
    Emit(),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], ChipBoxElement.prototype, "chipAdded", null);
__decorate([
    Emit(),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], ChipBoxElement.prototype, "chipRemoved", null);
ChipBoxElement = __decorate([
    Component({
        selector: 'mosaik-chipbox',
        template: chipBoxElementTemplate,
        themes: {
            joy: chipBoxElementJoyStyle,
            memphis: chipBoxElementMemphisStyle,
            cosmopolitan: chipBoxElementCosmopolitanStyle
        },
        host: {
            tabIndex: '0'
        },
        options: {
            mode: 'open',
            delegatesFocus: true
        },
        imports: [
            ChipElement,
            ButtonElement
        ]
    }),
    __metadata("design:paramtypes", [])
], ChipBoxElement);
export { ChipBoxElement };
//# sourceMappingURL=ChipBoxElement.js.map