// #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);
};
var ChipGroupElement_1;
import { HTMLElementEventEmitter } from '@breadstone/mosaik-elements';
import { Emit } from '../../../../events/Decorators/EmitDecorator';
import { EID } from '../../../../Utilities/EId';
import { Appearanceable } from '../../../Behaviors/Appearanceable';
import { Disableable } from '../../../Behaviors/Disableable';
import { Invalidable } from '../../../Behaviors/Invalidable';
import { Sizeable } from '../../../Behaviors/Sizeable';
import { Slottable } from '../../../Behaviors/Slottable';
import { Themeable } from '../../../Behaviors/Themeable';
import { Valueable } from '../../../Behaviors/Valueable';
import { Variantable } from '../../../Behaviors/Variantable';
import { addInheritanceProviderController } from '../../../Controllers/InheritanceProviderController';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Component } from '../../../Decorators/ComponentDecorator';
import { Watch } from '../../../Decorators/WatchDecorator';
import { SelectionMode } from '../../../Types/SelectionMode';
import { CustomElement } from '../../Abstracts/CustomElement';
import { ChipElement } from './ChipElement';
import { chipGroupElementTemplate } from './ChipGroupElementTemplate';
import { CHIP_GROUP_INHERITANCE_CONTEXT } from './ChipGroupInheritanceContext';
import { chipGroupElementCosmopolitanStyle } from './Themes/ChipGroupElement.Cosmopolitan';
import { chipGroupElementJoyStyle } from './Themes/ChipGroupElement.Joy';
import { chipGroupElementMemphisStyle } from './Themes/ChipGroupElement.Memphis';
// #endregion
/**
 * Chip Group - A container for grouping multiple chips.
 *
 * @description
 * The Chip Group component is used to organize and manage a set of chips,
 * allowing users to select one or more options from the group.
 * It supports both single and multiple selection modes.
 * Chip Groups are commonly used for filtering, tagging, or categorizing content.
 *
 * @element mosaik-chip-group
 * @category Media
 *
 * @slot - Default slot for chip elements.
 *
 * @csspart root - The root container element.
 *
 * @cssprop {String} --chip-group-background-color - The group background color CSS custom property.
 * @cssprop {String} --chip-group-border-color - The group border color CSS custom property.
 * @cssprop {String} --chip-group-border-radius - The group border radius CSS custom property.
 * @cssprop {String} --chip-group-border-style - The group border style CSS custom property.
 * @cssprop {String} --chip-group-border-width - The group border width CSS custom property.
 * @cssprop {String} --chip-group-font-family - The group font family CSS custom property.
 * @cssprop {String} --chip-group-font-letter-spacing - The group font letter spacing CSS custom property.
 * @cssprop {String} --chip-group-font-line-height - The group font line height CSS custom property.
 * @cssprop {String} --chip-group-font-size - The group font size CSS custom property.
 * @cssprop {String} --chip-group-font-text-decoration - The group font text decoration CSS custom property.
 * @cssprop {String} --chip-group-font-text-transform - The group font text transform CSS custom property.
 * @cssprop {String} --chip-group-font-weight - The group font weight CSS custom property.
 * @cssprop {String} --chip-group-foreground-color - The group foreground color CSS custom property.
 * @cssprop {String} --chip-group-gap - The group gap CSS custom property.
 * @cssprop {String} --chip-group-padding-bottom - The group padding bottom CSS custom property.
 * @cssprop {String} --chip-group-padding-left - The group padding left CSS custom property.
 * @cssprop {String} --chip-group-padding-right - The group padding right CSS custom property.
 * @cssprop {String} --chip-group-padding-top - The group padding top CSS custom property.
 * @cssprop {String} --chip-group-shadow - The group shadow CSS custom property.
 * @cssprop {String} --chip-group-shadow-blur - The group shadow blur CSS custom property.
 * @cssprop {String} --chip-group-shadow-color - The group shadow color CSS custom property.
 * @cssprop {String} --chip-group-shadow-offset-x - The group shadow offset x CSS custom property.
 * @cssprop {String} --chip-group-shadow-offset-y - The group shadow offset y CSS custom property.
 * @cssprop {String} --chip-group-shadow-spread - The group shadow spread CSS custom property.
 * @cssprop {String} --chip-group-transition-duration - The group transition duration CSS custom property.
 * @cssprop {String} --chip-group-transition-mode - The group transition mode CSS custom property.
 * @cssprop {String} --chip-group-transition-property - The group transition property CSS custom property.
 * @cssprop {String} --chip-group-translate - The group translate CSS custom property.
 *
 * @fires chipChanged {GroupChangedEvent} - Called when the selection in the group changes.
 *
 * @example
 * Single selection mode:
 * ```html
 * <mosaik-chip-group selection-mode="single">
 *   <mosaik-chip value="option-1" is-checkable></mosaik-chip>
 *   <mosaik-chip value="option-2" is-checkable></mosaik-chip>
 *   <mosaik-chip value="option-3" is-checkable></mosaik-chip>
 * </mosaik-chip-group>
 * ```
 *
 * @example
 * Multiple selection mode:
 * ```html
 * <mosaik-chip-group selection-mode="multiple">
 *   <mosaik-chip value="tag-1" is-checkable></mosaik-chip>
 *   <mosaik-chip value="tag-2" is-checkable></mosaik-chip>
 *   <mosaik-chip value="tag-3" is-checkable></mosaik-chip>
 * </mosaik-chip-group>
 * ```
 *
 * @public
 */
let ChipGroupElement = ChipGroupElement_1 = class ChipGroupElement extends Themeable(Sizeable(Invalidable(Disableable(Valueable(Appearanceable(Variantable(Slottable(CustomElement)))))))) {
    // #region Fields
    _chipChanged;
    _name;
    _required;
    _selectionMode;
    _wrap;
    _eventSubscriptions;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        addInheritanceProviderController(this, {
            context: CHIP_GROUP_INHERITANCE_CONTEXT,
            values: () => ({
                disabled: this.disabled,
                appearance: this.appearance,
                variant: this.variant,
                size: this.size,
                name: this.name,
                dir: this.dir
            })
        });
        this._name = EID.next(ChipGroupElement_1.is);
        this._required = false;
        this._selectionMode = SelectionMode.Single;
        this._wrap = false;
        this._chipChanged = new HTMLElementEventEmitter(this, 'chipChanged');
        this._eventSubscriptions = new Array();
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `is` property.
     * The `is` property represents natural name of this element.
     *
     * @public
     * @static
     * @readonly
     */
    static get is() {
        return 'mosaik-chip-group';
    }
    /**
     * 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 `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 `selectionMode` property.
     * Controls whether single or multiple chips can be selected.
     *
     * @public
     * @attr selection-mode
     */
    get selectionMode() {
        return this._selectionMode;
    }
    set selectionMode(value) {
        if (this._selectionMode !== value) {
            this._selectionMode = value;
            this.requestUpdate('selectionMode');
        }
    }
    /**
     * Gets or sets the `wrap` property.
     *
     * @public
     * @attr
     */
    get wrap() {
        return this._wrap;
    }
    set wrap(value) {
        if (this._wrap !== value) {
            this._wrap = value;
            this.requestUpdate('wrap');
        }
    }
    /**
     * Called when the selection in the group changes.
     * Provides reference to `IGroupChangedEventDetail` as event detail.
     *
     * @public
     * @readonly
     * @eventProperty
     */
    get chipChanged() {
        return this._chipChanged;
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @override
     */
    onSlotChanges() {
        this.clearEvents();
        const elements = this.getSlotAssignments('')
            .filter((x) => x instanceof ChipElement);
        for (const [i, e] of elements.entries()) {
            // Ensure chips are checkable only when selection is allowed
            e.isCheckable = this._selectionMode !== SelectionMode.None;
            // Assign a unique value to chips without one to prevent selection issues
            // when multiple chips have undefined/null values
            if (e.value === undefined || e.value === null || e.value === '') {
                e.value = e.label || `chip-${i}`;
            }
            // Set initial checked state based on current value
            if (this._selectionMode === SelectionMode.Single) {
                e.isChecked = this.value === e.value;
            }
            else {
                const values = Array.isArray(this.value) ? this.value : [];
                e.isChecked = values.includes(e.value);
            }
            e.classList.add('chip-group-chip');
            e.classList.toggle('first', i === 0);
            e.classList.toggle('inner', i > 0 && i < elements.length - 1);
            e.classList.toggle('last', i === elements.length - 1);
            this._eventSubscriptions.push(e.on('checked', (x) => this.onChipCheckChanged(x), { passive: true }), e.on('unchecked', (x) => this.onChipUncheckChanged(x), { passive: true }));
        }
    }
    /**
     * Returns whether a form will validate when it is submitted, without having to submit it.
     *
     * @public
     * @override
     */
    checkValidity() {
        const elements = this.getSlotAssignments('')
            .filter((x) => x instanceof ChipElement)
            .filter((x) => x.isChecked);
        return elements.length > 0;
    }
    /**
     * Resets the element to its initial state.
     *
     * @public
     */
    reset() {
        const elements = this.getSlotAssignments('')
            .filter((x) => x instanceof ChipElement);
        elements.forEach((x) => x.uncheck());
        if (this._selectionMode === SelectionMode.Single) {
            this.value = undefined;
        }
        else {
            this.value = [];
        }
        this.invalid = false;
    }
    /**
     * Selects all chips in the group (only works in multiple selection mode).
     *
     * @public
     */
    selectAll() {
        if (this._selectionMode !== SelectionMode.Multiple) {
            return;
        }
        const elements = this.getSlotAssignments('')
            .filter((x) => x instanceof ChipElement);
        elements.forEach((x) => x.check());
        this.updateValue();
    }
    /**
     * Deselects all chips in the group.
     *
     * @public
     */
    deselectAll() {
        const elements = this.getSlotAssignments('')
            .filter((x) => x instanceof ChipElement);
        elements.forEach((x) => x.uncheck());
        this.updateValue();
    }
    /**
     * Emits the `chipChanged` event.
     *
     * @protected
     */
    onChipChanged(args) {
        this._chipChanged.emit(args);
    }
    /**
     * @protected
     */
    onSelectionModePropertyChange(_prev, next) {
        const elements = this.getSlotAssignments('')
            .filter((x) => x instanceof ChipElement);
        if (next === SelectionMode.None) {
            elements.forEach((x) => {
                x.uncheck();
                x.isCheckable = false;
            });
            this.value = undefined;
        }
        else {
            elements.forEach((x) => x.isCheckable = true);
        }
    }
    /**
     * @protected
     */
    onValuePropertyChange(_prev, next) {
        const elements = this.getSlotAssignments('')
            .filter((x) => x instanceof ChipElement);
        if (this._selectionMode === SelectionMode.Single) {
            elements.forEach((x) => x.isChecked = next === x.value);
        }
        else {
            const values = Array.isArray(next) ? next : [];
            elements.forEach((x) => x.isChecked = values.includes(x.value));
        }
    }
    /**
     * @private
     */
    onChipCheckChanged(event) {
        if (this._selectionMode === SelectionMode.None) {
            return;
        }
        const target = event.target;
        if (this._selectionMode === SelectionMode.Single) {
            // In single mode, uncheck all other chips
            const elements = this.getSlotAssignments('')
                .filter((x) => x instanceof ChipElement);
            elements.filter((x) => x !== target)
                .forEach((x) => x.uncheck());
            this.value = target.value;
            this.onChipChanged({ value: target.value });
        }
        else {
            this.updateValue();
        }
    }
    /**
     * @private
     */
    onChipUncheckChanged(_event) {
        if (this._selectionMode === SelectionMode.None) {
            return;
        }
        if (this._selectionMode === SelectionMode.Multiple) {
            this.updateValue();
        }
        else {
            // In single mode, unchecking sets value to undefined
            this.value = undefined;
            this.onChipChanged({ value: undefined });
        }
    }
    /**
     * @private
     */
    updateValue() {
        const elements = this.getSlotAssignments('')
            .filter((x) => x instanceof ChipElement)
            .filter((x) => x.isChecked);
        const values = elements.map((x) => x.value);
        if (this._selectionMode === SelectionMode.Single) {
            this.value = values[0];
            this.onChipChanged({ value: values[0] });
        }
        else {
            this.value = values;
            this.onChipChanged({
                value: values,
                values
            });
        }
    }
    /**
     * @private
     */
    clearEvents() {
        this._eventSubscriptions.forEach((x) => x.dispose());
        this._eventSubscriptions = [];
    }
};
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], ChipGroupElement.prototype, "name", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], ChipGroupElement.prototype, "required", null);
__decorate([
    Attribute({
        type: SelectionMode,
        attribute: 'selection-mode'
    }),
    __metadata("design:type", String),
    __metadata("design:paramtypes", [String])
], ChipGroupElement.prototype, "selectionMode", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], ChipGroupElement.prototype, "wrap", null);
__decorate([
    Emit({ eventName: 'chipChanged' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], ChipGroupElement.prototype, "chipChanged", null);
__decorate([
    Watch('selectionMode'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", void 0)
], ChipGroupElement.prototype, "onSelectionModePropertyChange", null);
__decorate([
    Watch('value'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", void 0)
], ChipGroupElement.prototype, "onValuePropertyChange", null);
ChipGroupElement = ChipGroupElement_1 = __decorate([
    Component({
        selector: 'mosaik-chip-group',
        template: chipGroupElementTemplate,
        themes: {
            joy: chipGroupElementJoyStyle,
            memphis: chipGroupElementMemphisStyle,
            cosmopolitan: chipGroupElementCosmopolitanStyle
        },
        host: {
            role: 'group'
        },
        imports: [
            ChipElement
        ]
    }),
    __metadata("design:paramtypes", [])
], ChipGroupElement);
export { ChipGroupElement };
//# sourceMappingURL=ChipGroupElement.js.map