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, property, state } from '../../../../external/lit/index.js';
import { generateAlias } from '../../utils/index.js';
import { UmbChangeEvent } from '../../event/index.js';
import { UMB_VALIDATION_EMPTY_LOCALIZATION_KEY, UmbFormControlMixin } from '../../validation/index.js';
import { UmbLitElement } from '../../lit-element/index.js';
import { UUIInputEvent } from '../../../../external/uui/index.js';
const DEFAULT_ALIAS_PATTERN = '^[A-Za-z][A-Za-z0-9_-]{0,254}$';
let UmbInputWithAliasElement = class UmbInputWithAliasElement extends UmbFormControlMixin(UmbLitElement) {
    constructor() {
        super(...arguments);
        this.label = '';
        this.alias = '';
        this.required = false;
        this.readonly = false;
        this.aliasReadonly = false;
        this.aliasPattern = DEFAULT_ALIAS_PATTERN;
        this._aliasLocked = true;
    }
    firstUpdated() {
        this.addValidator('valueMissing', () => UMB_VALIDATION_EMPTY_LOCALIZATION_KEY, () => this.required && !this.value);
        this.addValidator('patternMismatch', () => this.localize.term('validation_aliasInvalidFormat'), () => {
            if (!this.alias)
                return false;
            try {
                const re = new RegExp(this.aliasPattern);
                return !re.test(this.alias);
            }
            catch {
                return false;
            }
        });
        this.shadowRoot?.querySelectorAll('uui-input').forEach((x) => this.addFormControlElement(x));
    }
    focus() {
        return this.shadowRoot?.querySelector('uui-input')?.focus();
    }
    #onNameChange(e) {
        if (!(e instanceof UUIInputEvent))
            return;
        const target = e.composedPath()[0];
        if (typeof target?.value === 'string') {
            this.value = e.target.value.toString();
            if (this.autoGenerateAlias && this._aliasLocked) {
                // Generate alias if it's locked and auto-generate is enabled
                this.alias = generateAlias(this.value);
            }
            this.dispatchEvent(new UmbChangeEvent());
        }
    }
    #onAliasChange(e) {
        e.stopPropagation();
        if (!(e instanceof UUIInputEvent))
            return;
        const target = e.composedPath()[0];
        if (typeof target?.value === 'string') {
            this.alias = target.value;
            this.dispatchEvent(new UmbChangeEvent());
        }
    }
    #onAliasBlur() {
        // If the alias is empty, then try to generate one [NL]
        if (!this.alias && this._aliasLocked === false) {
            this.alias = generateAlias(this.value ?? '');
            this.dispatchEvent(new UmbChangeEvent());
        }
        this._aliasLocked = true;
    }
    #onToggleAliasLock(event) {
        this._aliasLocked = !this._aliasLocked;
        if (!this.alias && this._aliasLocked) {
            // Reenable auto-generate if alias is empty and locked.
            this.autoGenerateAlias = true;
        }
        else {
            this.autoGenerateAlias = false;
        }
        if (!this._aliasLocked) {
            const input = event.target;
            input?.focus();
            requestAnimationFrame(() => {
                input?.select();
            });
        }
    }
    render() {
        const nameLabel = this.label ?? this.localize.term('placeholders_entername');
        const aliasLabel = this.localize.term('placeholders_enterAlias');
        return html `
			<uui-input
				id="name"
				placeholder=${ifDefined(this.placeholder)}
				label=${nameLabel}
				.value=${this.value ?? ''}
				@input=${this.#onNameChange}
				?required=${this.required}
				?readonly=${this.readonly}>
				${!this.readonly
            ? html `
							<uui-input-lock
								name="alias"
								slot="append"
								label=${aliasLabel}
								placeholder=${aliasLabel}
								.value=${this.alias}
								?auto-width=${!!this.value}
								?locked=${this._aliasLocked && !this.aliasReadonly}
								?readonly=${this._aliasLocked || this.aliasReadonly}
								?required=${this.required}
								@input=${this.#onAliasChange}
								@blur=${this.#onAliasBlur}
								@lock-change=${this.#onToggleAliasLock}>
							</uui-input-lock>
						`
            : html `<span id="alias" class="muted" slot="append">${this.alias}</span>`}
			</uui-input>
		`;
    }
    static { this.styles = css `
		:host {
			display: contents;
		}
		#name {
			width: 100%;
			flex: 1 1 auto;
			align-items: center;
		}

		uui-input-lock {
			transition: opacity 80ms;
			&.muted {
				opacity: 0.55;
				padding: var(--uui-size-1, 3px) var(--uui-size-space-3, 9px);
			}
		}

		:host(:invalid:not([pristine])) {
			color: var(--uui-color-invalid);
		}
		:host(:invalid:not([pristine])) > uui-input {
			border-color: var(--uui-color-invalid);
		}
		:host(:not(invalid):not(:hover):not(:focus-within)) uui-input-lock {
			--uui-button-contrast: transparent;
			--uui-input-background-color-readonly: transparent;
		}
	`; }
};
__decorate([
    property({ type: String })
], UmbInputWithAliasElement.prototype, "label", void 0);
__decorate([
    property({ type: String })
], UmbInputWithAliasElement.prototype, "placeholder", void 0);
__decorate([
    property({ type: String, reflect: false })
], UmbInputWithAliasElement.prototype, "alias", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], UmbInputWithAliasElement.prototype, "required", void 0);
__decorate([
    property({ type: Boolean, reflect: true })
], UmbInputWithAliasElement.prototype, "readonly", void 0);
__decorate([
    property({ type: Boolean, reflect: true, attribute: 'alias-readonly' })
], UmbInputWithAliasElement.prototype, "aliasReadonly", void 0);
__decorate([
    property({ type: Boolean, attribute: 'auto-generate-alias' })
], UmbInputWithAliasElement.prototype, "autoGenerateAlias", void 0);
__decorate([
    property({ type: String, attribute: 'alias-pattern' })
], UmbInputWithAliasElement.prototype, "aliasPattern", void 0);
__decorate([
    state()
], UmbInputWithAliasElement.prototype, "_aliasLocked", void 0);
UmbInputWithAliasElement = __decorate([
    customElement('umb-input-with-alias')
], UmbInputWithAliasElement);
export { UmbInputWithAliasElement };
export { UmbInputWithAliasElement as element };
