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;
};
import { ensureArray, updateItemsSelectedState } from '../utils/property-editor-ui-state-manager.js';
import { css, customElement, html, map, nothing, property, state, when } from '../../../external/lit/index.js';
import { UmbChangeEvent } from '../../core/event/index.js';
import { UmbLitElement } from '../../core/lit-element/index.js';
import { UMB_VALIDATION_EMPTY_LOCALIZATION_KEY, UmbFormControlMixin } from '../../core/validation/index.js';
import { UUISelectElement } from '../../../external/uui/index.js';
/**
 * @element umb-property-editor-ui-dropdown
 */
let UmbPropertyEditorUIDropdownElement = class UmbPropertyEditorUIDropdownElement extends UmbFormControlMixin(UmbLitElement, undefined) {
    constructor() {
        super(...arguments);
        this.#selection = [];
        this._multiple = false;
        this._options = [];
        /**
         * Sets the input to readonly mode, meaning value cannot be changed but still able to read and select its content.
         * @type {boolean}
         * @attr
         * @default false
         */
        this.readonly = false;
        this.mandatoryMessage = UMB_VALIDATION_EMPTY_LOCALIZATION_KEY;
    }
    #selection;
    set value(value) {
        this.#selection = ensureArray(value);
        // Update the selected state of existing options when value changes
        this.#updateSelectedState();
    }
    get value() {
        return this.#selection;
    }
    set config(config) {
        if (!config)
            return;
        const items = config.getValueByAlias('items');
        if (Array.isArray(items) && items.length > 0) {
            this._options =
                typeof items[0] === 'string'
                    ? items.map((item) => ({ name: item, value: item, selected: this.#selection.includes(item) }))
                    : items.map((item) => ({
                        name: item.name,
                        value: item.value,
                        selected: this.#selection.includes(item.value),
                    }));
            // If selection includes a value that is not in the list, add it to the list
            this.#selection.forEach((value) => {
                if (value !== '' && !this._options.find((item) => item.value === value)) {
                    this._options.push({
                        name: `${value} (${this.localize.term('validation_legacyOption')})`,
                        value,
                        selected: true,
                        invalid: true,
                    });
                }
            });
        }
        this._multiple = config.getValueByAlias('multiple') ?? false;
    }
    firstUpdated() {
        if (this._multiple) {
            this.addFormControlElement(this.shadowRoot.querySelector('select'));
        }
        else {
            this.addFormControlElement(this.shadowRoot.querySelector('umb-input-dropdown-list'));
        }
        if (!this.mandatory && !this._multiple) {
            this._options.unshift({ name: '', value: '', selected: false, invalid: false });
        }
    }
    #onChange(event) {
        const value = event.target.value;
        this.#setValue(value ? [value] : []);
    }
    #onChangeMultiple(event) {
        const selected = event.target.selectedOptions;
        const value = selected ? Array.from(selected).map((option) => option.value) : [];
        this.#setValue(value);
    }
    #setValue(value) {
        if (!value)
            return;
        const selection = ensureArray(value);
        this._options.forEach((item) => (item.selected = selection.includes(item.value)));
        this.value = value;
        this.dispatchEvent(new UmbChangeEvent());
    }
    /**
     * Updates the selected state of all options based on current selection.
     * This fixes the issue where UI doesn't update when values are set programmatically.
     */
    #updateSelectedState() {
        // Only update if we have options loaded
        if (this._options.length > 0) {
            // Update state only if changes are needed
            const updatedOptions = updateItemsSelectedState(this._options, this.#selection, 'selected');
            if (updatedOptions !== this._options) {
                this._options = updatedOptions;
            }
        }
    }
    render() {
        return html `
			${when(this._multiple, () => this.#renderDropdownMultiple(), () => this.#renderDropdownSingle())}
			${this.#renderDropdownValidation()}
		`;
    }
    #renderDropdownMultiple() {
        if (this.readonly) {
            return html `<div>${this.value?.join(', ')}</div>`;
        }
        return html `
			<select id="native" multiple ?required=${this.mandatory} @change=${this.#onChangeMultiple}>
				${map(this._options, (item) => html `<option value=${item.value} ?selected=${item.selected}>${item.name}</option>`)}
			</select>
		`;
    }
    #renderDropdownSingle() {
        return html `
			<umb-input-dropdown-list
				.name=${this.name}
				.options=${this._options}
				.required=${this.mandatory}
				.requiredMessage=${this.mandatoryMessage}
				?readonly=${this.readonly}
				@change=${this.#onChange}>
			</umb-input-dropdown-list>
		`;
    }
    #renderDropdownValidation() {
        const selectionHasInvalids = this.#selection.some((value) => {
            const option = this._options.find((item) => item.value === value);
            return option ? option.invalid : false;
        });
        if (selectionHasInvalids) {
            return html `<div class="error"><umb-localize key="validation_legacyOptionDescription"></umb-localize></div>`;
        }
        return nothing;
    }
    static { this.styles = [
        UUISelectElement.styles,
        css `
			#native {
				height: auto;
			}

			.error {
				color: var(--uui-color-invalid);
				font-size: var(--uui-font-size-small);
			}
		`,
    ]; }
};
__decorate([
    state()
], UmbPropertyEditorUIDropdownElement.prototype, "_multiple", void 0);
__decorate([
    state()
], UmbPropertyEditorUIDropdownElement.prototype, "_options", void 0);
__decorate([
    property({ type: Array })
], UmbPropertyEditorUIDropdownElement.prototype, "value", null);
__decorate([
    property({ type: Boolean, reflect: true })
], UmbPropertyEditorUIDropdownElement.prototype, "readonly", void 0);
__decorate([
    property({ type: Boolean })
], UmbPropertyEditorUIDropdownElement.prototype, "mandatory", void 0);
__decorate([
    property({ type: String })
], UmbPropertyEditorUIDropdownElement.prototype, "mandatoryMessage", void 0);
__decorate([
    property({ type: String })
], UmbPropertyEditorUIDropdownElement.prototype, "name", void 0);
UmbPropertyEditorUIDropdownElement = __decorate([
    customElement('umb-property-editor-ui-dropdown')
], UmbPropertyEditorUIDropdownElement);
export { UmbPropertyEditorUIDropdownElement };
export default UmbPropertyEditorUIDropdownElement;
