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 { css, customElement, html, ifDefined, nothing, property, repeat, when, } from '../../../../../external/lit/index.js';
import { extractUmbColorVariable } from '../../../../core/resources/index.js';
import { simpleHashCode } from '../../../../../libs/observable-api/index.js';
import { UmbLitElement } from '../../../../core/lit-element/index.js';
import { UmbSorterController } from '../../../../core/sorter/index.js';
import { UmbChangeEvent } from '../../../../core/event/index.js';
import { UmbTextStyles } from '../../../../core/style/index.js';
import { UMB_ICON_PICKER_MODAL } from '../../../../core/icon-registry/index.js';
/**
 * @element umb-property-editor-ui-collection-layout-configuration
 */
let UmbPropertyEditorUICollectionLayoutConfigurationElement = class UmbPropertyEditorUICollectionLayoutConfigurationElement extends UmbLitElement {
    #sorter = new UmbSorterController(this, {
        getUniqueOfElement: (element) => {
            return element.id;
        },
        getUniqueOfModel: (modelEntry) => {
            return this.#getUnique(modelEntry);
        },
        itemSelector: '.layout-item',
        containerSelector: '#layout-wrapper',
        onChange: ({ model }) => {
            this.value = model;
            this.dispatchEvent(new UmbChangeEvent());
        },
    });
    set value(value) {
        this.#value = value ?? [];
        this.#sorter.setModel(this.#value);
    }
    get value() {
        return this.#value;
    }
    #value = [];
    async #focusNewItem() {
        await this.updateComplete;
        const input = this.shadowRoot?.querySelector('.layout-item:last-of-type > uui-input');
        input.focus();
    }
    #onAdd(event) {
        const manifest = event.target.value;
        const duplicate = this.value?.find((config) => manifest?.value === config.collectionView);
        if (duplicate) {
            // TODO: Show error to user, can not add duplicate `collectionView` aliases. [LK]
            throw new Error('Duplicate `collectionView` aliases are not allowed.');
            return;
        }
        this.value = [
            ...(this.value ?? []),
            {
                icon: manifest?.icon,
                name: manifest?.label,
                collectionView: manifest?.value,
            },
        ];
        this.dispatchEvent(new UmbChangeEvent());
        this.#focusNewItem();
    }
    #onChangeLabel(e, index) {
        const values = [...(this.value ?? [])];
        values[index] = { ...values[index], name: e.target.value };
        this.value = values;
        this.dispatchEvent(new UmbChangeEvent());
    }
    #onRemove(unique) {
        const values = [...(this.value ?? [])];
        values.splice(unique, 1);
        this.value = values;
        this.dispatchEvent(new UmbChangeEvent());
    }
    async #onIconChange(icon, index) {
        const picked = await (await import('../../../../core/modal/index.js'))
            .umbOpenModal(this, UMB_ICON_PICKER_MODAL, { value: icon })
            .catch(() => undefined);
        if (!picked)
            return;
        const values = [...(this.value ?? [])];
        values[index] = { ...values[index], icon: `${picked.icon} color-${picked.color}` };
        this.value = values;
        this.dispatchEvent(new UmbChangeEvent());
    }
    #parseIcon(iconString) {
        const [icon, color] = iconString?.split(' ') ?? [];
        return { icon, color: color?.replace('color-', '') };
    }
    #getUnique(layout) {
        return 'x' + simpleHashCode('' + layout.collectionView + layout.name + layout.icon).toString(16);
    }
    render() {
        return html `
			<div id="layout-wrapper">${this.#renderLayouts()}</div>
			${this.#renderInput()}
		`;
    }
    #renderInput() {
        return html `<umb-input-manifest extension-type="collectionView" @change=${this.#onAdd}></umb-input-manifest>`;
    }
    #renderLayouts() {
        if (!this.value)
            return nothing;
        return repeat(this.value, (layout) => this.#getUnique(layout), (layout, index) => this.#renderLayout(layout, index));
    }
    #renderLayout(layout, index) {
        const icon = this.#parseIcon(layout.icon);
        const varName = icon.color ? extractUmbColorVariable(icon.color) : undefined;
        return html `
			<div class="layout-item" id=${this.#getUnique(layout)}>
				<uui-icon class="drag-handle" name="icon-grip"></uui-icon>

				<uui-button compact look="outline" label="pick icon" @click=${() => this.#onIconChange(icon, index)}>
					${when(icon.color, () => html `<uui-icon name=${ifDefined(icon.icon)} style="color:var(${varName})"></uui-icon>`, () => html `<uui-icon name=${ifDefined(icon.icon)}></uui-icon>`)}
				</uui-button>

				<uui-input
					label="name"
					value=${ifDefined(layout.name)}
					placeholder="Enter a label..."
					@change=${(e) => this.#onChangeLabel(e, index)}></uui-input>

				<div class="alias">
					<code>${layout.collectionView}</code>
				</div>

				<div class="actions">
					<uui-button
						label=${this.localize.term('general_remove')}
						look="secondary"
						@click=${() => this.#onRemove(index)}></uui-button>
				</div>
			</div>
		`;
    }
    static { this.styles = [
        UmbTextStyles,
        css `
			#layout-wrapper {
				display: flex;
				flex-direction: column;
				gap: 1px;
				margin-bottom: var(--uui-size-1);
			}

			.layout-item {
				background-color: var(--uui-color-surface-alt);
				display: flex;
				align-items: center;
				gap: var(--uui-size-6);
				padding: var(--uui-size-3) var(--uui-size-6);
			}

			.layout-item > uui-icon {
				flex: 0 0 var(--uui-size-6);
			}

			.layout-item > uui-button {
				flex: 0 0 var(--uui-size-10);
			}

			.layout-item > uui-input,
			.layout-item > .alias {
				flex: 1;
			}

			.layout-item > .actions {
				flex: 0 0 auto;
				display: flex;
				justify-content: flex-end;
			}

			.drag-handle {
				cursor: grab;
			}

			.drag-handle:active {
				cursor: grabbing;
			}
		`,
    ]; }
};
__decorate([
    property({ type: Array })
], UmbPropertyEditorUICollectionLayoutConfigurationElement.prototype, "value", null);
__decorate([
    property({ type: Object, attribute: false })
], UmbPropertyEditorUICollectionLayoutConfigurationElement.prototype, "config", void 0);
UmbPropertyEditorUICollectionLayoutConfigurationElement = __decorate([
    customElement('umb-property-editor-ui-collection-layout-configuration')
], UmbPropertyEditorUICollectionLayoutConfigurationElement);
export { UmbPropertyEditorUICollectionLayoutConfigurationElement };
export default UmbPropertyEditorUICollectionLayoutConfigurationElement;
