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 { getQuerySnippet } from '../../utils/index.js';
import { UMB_TEMPLATE_QUERY_BUILDER_MODAL } from '../modals/query-builder/index.js';
import { UMB_TEMPLATING_SECTION_PICKER_MODAL } from '../../modals/templating-section-picker/templating-section-picker-modal.token.js';
import { UMB_TEMPLATE_PICKER_MODAL } from '../modals/index.js';
import { UMB_TEMPLATE_WORKSPACE_CONTEXT } from './template-workspace.context-token.js';
import { css, customElement, html, nothing, query, state } from '../../../../external/lit/index.js';
import { UmbLitElement, umbFocus } from '../../../core/lit-element/index.js';
import { UMB_MODAL_MANAGER_CONTEXT } from '../../../core/modal/index.js';
import { umbBindToValidation } from '../../../core/validation/index.js';
import { UMB_SERVER_CONTEXT } from '../../../core/server/index.js';
import '../../../code-editor/index.js';
import '../../local-components/insert-menu/index.js';
/**
 * Template alias pattern - allows first character to be a letter, digit, or underscore.
 * Mirrors server-side CleanStringType.UnderscoreAlias behavior.
 */
const UMB_TEMPLATE_ALIAS_PATTERN = '^[A-Za-z0-9_][A-Za-z0-9_-]{0,254}$';
let UmbTemplateWorkspaceEditorElement = class UmbTemplateWorkspaceEditorElement extends UmbLitElement {
    #modalContext;
    #templateWorkspaceContext;
    #isNew;
    #masterTemplateUnique;
    constructor() {
        super();
        this._name = '';
        this._content = '';
        this._alias = '';
        this._masterTemplateName = null;
        /**
         * Whether editing is restricted. True when in production mode OR when runtime mode is still unknown.
         * This ensures a safe default (restricted) until we confirm the runtime mode.
         */
        this._isRestricted = true;
        this.#isNew = false;
        this.#masterTemplateUnique = null;
        this.consumeContext(UMB_MODAL_MANAGER_CONTEXT, (instance) => {
            this.#modalContext = instance;
        });
        this.consumeContext(UMB_SERVER_CONTEXT, (context) => {
            this.observe(context?.isProductionMode, (isProductionMode) => {
                // Restricted until we confirm it's NOT production mode (safe default).
                this._isRestricted = isProductionMode !== false;
            });
        });
        this.consumeContext(UMB_TEMPLATE_WORKSPACE_CONTEXT, (workspaceContext) => {
            this.#templateWorkspaceContext = workspaceContext;
            this.observe(this.#templateWorkspaceContext?.name, (name) => {
                this._name = name;
            });
            this.observe(this.#templateWorkspaceContext?.alias, (alias) => {
                this._alias = alias;
            });
            this.observe(this.#templateWorkspaceContext?.content, (content) => {
                this._content = content;
            });
            this.observe(this.#templateWorkspaceContext?.masterTemplate, (masterTemplate) => {
                this.#masterTemplateUnique = masterTemplate?.unique ?? null;
                this._masterTemplateName = masterTemplate?.name ?? null;
            });
            this.observe(this.#templateWorkspaceContext?.isNew, (isNew) => {
                this.#isNew = !!isNew;
            });
        });
    }
    #onNameAndAliasChange(event) {
        this.#templateWorkspaceContext?.setName(event.target.value ?? '');
        this.#templateWorkspaceContext?.setAlias(event.target.alias ?? '');
    }
    #onCodeEditorInput(event) {
        const target = event.target;
        const value = target.code;
        this.#templateWorkspaceContext?.setContent(value);
    }
    #insertSnippet(event) {
        const target = event.target;
        const value = target.value;
        this._codeEditor?.insert(value);
    }
    #openInsertSectionModal() {
        const sectionModal = this.#modalContext?.open(this, UMB_TEMPLATING_SECTION_PICKER_MODAL);
        sectionModal
            ?.onSubmit()
            .then((insertSectionModalValue) => {
            if (insertSectionModalValue?.value) {
                this._codeEditor?.insert(insertSectionModalValue.value);
            }
        })
            .catch(() => undefined);
    }
    #resetMasterTemplate() {
        this.#templateWorkspaceContext?.setMasterTemplate(null, true);
    }
    #openMasterTemplatePicker() {
        const modalContext = this.#modalContext?.open(this, UMB_TEMPLATE_PICKER_MODAL, {
            data: {
                pickableFilter: (item) => {
                    return item.unique !== null && item.unique !== this.#templateWorkspaceContext?.getUnique();
                },
            },
            value: {
                selection: [this.#masterTemplateUnique],
            },
        });
        modalContext
            ?.onSubmit()
            .then((value) => {
            if (!value?.selection)
                return;
            this.#templateWorkspaceContext?.setMasterTemplate(value.selection[0] ?? null, true);
        })
            .catch(() => undefined);
    }
    #openQueryBuilder() {
        const queryBuilderModal = this.#modalContext?.open(this, UMB_TEMPLATE_QUERY_BUILDER_MODAL);
        queryBuilderModal
            ?.onSubmit()
            .then((queryBuilderModalValue) => {
            if (queryBuilderModalValue?.value) {
                this._codeEditor?.insert(getQuerySnippet(queryBuilderModalValue.value));
            }
        })
            .catch(() => undefined);
    }
    #renderMasterTemplatePicker() {
        return html `
			<uui-button-group>
				<uui-button
					@click=${this.#openMasterTemplatePicker}
					look="secondary"
					id="master-template-button"
					?disabled=${this._isRestricted}
					label="${this.localize.term('template_mastertemplate')}: ${this._masterTemplateName
            ? this._masterTemplateName
            : this.localize.term('template_noMaster')}"></uui-button>
				${this._masterTemplateName
            ? html `<uui-button
							look="secondary"
							label=${this.localize.term('actions_remove')}
							?disabled=${this._isRestricted}
							@click=${this.#resetMasterTemplate}
							compact>
							<uui-icon name="icon-delete"></uui-icon>
						</uui-button>`
            : nothing}
			</uui-button-group>
		`;
    }
    render() {
        // TODO: add correct UI elements
        return html `
			<umb-entity-detail-workspace-editor>
				<umb-input-with-alias
					slot="header"
					id="name"
					label=${this.localize.term('placeholders_entername')}
					placeholder=${this.localize.term('placeholders_entername')}
					.value=${this._name}
					.alias=${this._alias}
					alias-pattern=${UMB_TEMPLATE_ALIAS_PATTERN}
					?auto-generate-alias=${this.#isNew}
					?readonly=${this._isRestricted}
					@change=${this.#onNameAndAliasChange}
					required
					${umbBindToValidation(this)}
					${umbFocus()}>
				</umb-input-with-alias>

				<uui-box>
					<div slot="header" id="code-editor-menu-container">${this.#renderMasterTemplatePicker()}</div>
					<div slot="header-actions">
						<umb-templating-insert-menu @insert=${this.#insertSnippet} ?disabled=${this._isRestricted}>
						</umb-templating-insert-menu>
						<uui-button
							look="secondary"
							id="query-builder-button"
							label=${this.localize.term('template_queryBuilder')}
							?disabled=${this._isRestricted}
							@click=${this.#openQueryBuilder}>
							<uui-icon name="icon-wand"></uui-icon> ${this.localize.term('template_queryBuilder')}
						</uui-button>
						<uui-button
							look="secondary"
							id="sections-button"
							label=${this.localize.term('template_insertSections')}
							?disabled=${this._isRestricted}
							@click=${this.#openInsertSectionModal}>
							<uui-icon name="icon-indent"></uui-icon> ${this.localize.term('template_insertSections')}
						</uui-button>
					</div>

					${this.#renderCodeEditor()}
				</uui-box>
			</umb-entity-detail-workspace-editor>
		`;
    }
    #renderCodeEditor() {
        return html `
			<umb-code-editor
				id="content"
				language="razor"
				.code=${this._content ?? ''}
				?readonly=${this._isRestricted}
				@input=${this.#onCodeEditorInput}></umb-code-editor>
		`;
    }
    static { this.styles = [
        css `
			#loader-container {
				display: grid;
				place-items: center;
				min-height: calc(100dvh - 360px);
			}

			umb-code-editor {
				--editor-height: calc(100dvh - 300px);
			}

			uui-box {
				min-height: calc(100dvh - 300px);
				margin: var(--uui-size-layout-1);
				--uui-box-default-padding: 0;
				/* remove header border bottom as code editor looks better in this box */
				--uui-color-divider-standalone: transparent;
			}

			umb-input-with-alias {
				width: 100%;
			}

			#code-editor-menu-container uui-icon:not([name='icon-delete']) {
				margin-right: var(--uui-size-space-3);
			}

			#insert-menu {
				margin: 0;
				padding: 0;
				margin-top: var(--uui-size-space-3);
				background-color: var(--uui-color-surface);
				box-shadow: var(--uui-shadow-depth-3);
				min-width: calc(100% + var(--uui-size-8, 24px));
			}

			#insert-menu > li,
			ul {
				padding: 0;
				width: 100%;
				list-style: none;
			}

			.insert-menu-item {
				width: 100%;
			}

			#code-editor-menu-container {
				display: flex;
				justify-content: space-between;
				gap: var(--uui-size-space-3);
			}
		`,
    ]; }
};
__decorate([
    state()
], UmbTemplateWorkspaceEditorElement.prototype, "_name", void 0);
__decorate([
    state()
], UmbTemplateWorkspaceEditorElement.prototype, "_content", void 0);
__decorate([
    state()
], UmbTemplateWorkspaceEditorElement.prototype, "_alias", void 0);
__decorate([
    state()
], UmbTemplateWorkspaceEditorElement.prototype, "_masterTemplateName", void 0);
__decorate([
    state()
], UmbTemplateWorkspaceEditorElement.prototype, "_isRestricted", void 0);
__decorate([
    query('umb-code-editor')
], UmbTemplateWorkspaceEditorElement.prototype, "_codeEditor", void 0);
UmbTemplateWorkspaceEditorElement = __decorate([
    customElement('umb-template-workspace-editor')
], UmbTemplateWorkspaceEditorElement);
export { UmbTemplateWorkspaceEditorElement };
export default UmbTemplateWorkspaceEditorElement;
