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 { UmbBlockSingleEntryContext } from '../../context/block-single-entry.context.js';
import { UMB_BLOCK_SINGLE, UMB_BLOCK_SINGLE_PROPERTY_EDITOR_SCHEMA_ALIAS, UMB_BLOCK_SINGLE_PROPERTY_EDITOR_UI_ALIAS, } from '../../constants.js';
import { css, customElement, html, nothing, property, state } from '../../../../../external/lit/index.js';
import { UmbLitElement, umbDestroyOnDisconnect } from '../../../../core/lit-element/index.js';
import { stringOrStringArrayContains } from '../../../../core/utils/index.js';
import { UmbDataPathBlockElementDataQuery } from '../../../block/index.js';
import { UmbObserveValidationStateController } from '../../../../core/validation/index.js';
import { UUIBlinkAnimationValue, UUIBlinkKeyframes } from '../../../../../external/uui/index.js';
import { UMB_PROPERTY_CONTEXT, UMB_PROPERTY_DATASET_CONTEXT } from '../../../../core/property/index.js';
import { UMB_CLIPBOARD_PROPERTY_CONTEXT } from '../../../../clipboard/index.js';
import '../ref-single-block/index.js';
import '../inline-single-block/index.js';
import '../unsupported-single-block/index.js';
/**
 * @element umb-block-single-entry
 */
let UmbBlockSingleEntryElement = class UmbBlockSingleEntryElement extends UmbLitElement {
    //
    get index() {
        return this.#context.getIndex();
    }
    set index(value) {
        this.#context.setIndex(value);
    }
    get contentKey() {
        return this._contentKey;
    }
    set contentKey(value) {
        if (!value)
            return;
        this._contentKey = value;
        this.#context.setContentKey(value);
        new UmbObserveValidationStateController(this, `$.contentData[${UmbDataPathBlockElementDataQuery({ key: value })}]`, (hasMessages) => {
            this._contentInvalid = hasMessages;
            this._blockViewProps.contentInvalid = hasMessages;
        }, 'observeMessagesForContent');
    }
    #context;
    #updateBlockViewProps(incoming) {
        this._blockViewProps = { ...this._blockViewProps, ...incoming };
        this.requestUpdate('_blockViewProps');
    }
    constructor() {
        super();
        this.#context = new UmbBlockSingleEntryContext(this);
        this._showContentEdit = false;
        this._hasSettings = false;
        this._label = '';
        this._blockViewProps = {
            contentKey: undefined,
            config: { showContentEdit: false, showSettingsEdit: false },
        }; // Set to undefined cause it will be set before we render.
        this._isReadOnly = false;
        this.#expose = () => {
            this.#context.expose();
        };
        this.#extensionSlotFilterMethod = (manifest) => {
            if (this._unsupported) {
                // If the block is unsupported, we should not allow any custom views to render.
                return false;
            }
            if (manifest.forContentTypeAlias &&
                !stringOrStringArrayContains(manifest.forContentTypeAlias, this._contentTypeAlias)) {
                return false;
            }
            if (manifest.forBlockEditor && !stringOrStringArrayContains(manifest.forBlockEditor, UMB_BLOCK_SINGLE)) {
                return false;
            }
            return true;
        };
        this.#extensionSlotRenderMethod = (ext) => {
            ext.component?.setAttribute('part', 'component');
            if (this._exposed || this._isReadOnly) {
                return ext.component;
            }
            else {
                return html `<div style="min-height: var(--uui-size-16);">
				${ext.component}
				<umb-block-overlay-expose-button
					.contentTypeName=${this._contentTypeName}
					@click=${this.#expose}></umb-block-overlay-expose-button>
			</div>`;
            }
        };
        this.#renderBuiltinBlockView = () => {
            if (this._unsupported) {
                return this.#renderUnsupportedBlock();
            }
            if (this._inlineEditingMode) {
                return this.#renderInlineBlock();
            }
            return this.#renderRefBlock();
        };
        this.#init();
    }
    #init() {
        this.observe(this.#context.showContentEdit, (showContentEdit) => {
            this._showContentEdit = showContentEdit;
            this.#updateBlockViewProps({ config: { ...this._blockViewProps.config, showContentEdit } });
        }, null);
        this.observe(this.#context.settingsElementTypeKey, (key) => {
            this._hasSettings = !!key;
            this.#updateBlockViewProps({ config: { ...this._blockViewProps.config, showSettingsEdit: !!key } });
        }, null);
        this.observe(this.#context.blockType, (blockType) => {
            this.#updateBlockViewProps({ blockType });
        }, null);
        // TODO: Implement index.
        this.observe(this.#context.label, (label) => {
            this.#updateBlockViewProps({ label });
            this._label = label;
        }, null);
        this.observe(this.#context.contentElementTypeIcon, (icon) => {
            this.#updateBlockViewProps({ icon });
            this._icon = icon;
        }, null);
        this.observe(this.#context.hasExpose, (exposed) => {
            this.#updateBlockViewProps({ unpublished: !exposed });
            this._exposed = exposed;
        }, null);
        this.observe(this.#context.unsupported, (unsupported) => {
            if (unsupported === undefined)
                return;
            this.#updateBlockViewProps({ unsupported: unsupported });
            this._unsupported = unsupported;
            this.toggleAttribute('unsupported', unsupported);
        }, null);
        this.observe(this.#context.actionsVisibility, (showActions) => {
            this._showActions = showActions;
        }, null);
        this.observe(this.#context.inlineEditingMode, (mode) => {
            this._inlineEditingMode = mode;
        }, null);
        // Data props:
        this.observe(this.#context.layout, (layout) => {
            this.#updateBlockViewProps({ layout });
        }, null);
        this.#observeData();
        this.observe(this.#context.settingsKey, (settingsKey) => {
            this.removeUmbControllerByAlias('observeMessagesForSettings');
            if (settingsKey) {
                // Observe settings validation state:
                new UmbObserveValidationStateController(this, `$.settingsData[${UmbDataPathBlockElementDataQuery({ key: settingsKey })}]`, (hasMessages) => {
                    this._settingsInvalid = hasMessages;
                    this._blockViewProps.settingsInvalid = hasMessages;
                }, 'observeMessagesForSettings');
            }
        }, null);
        this.observe(this.#context.workspaceEditContentPath, (path) => {
            this._workspaceEditContentPath = path;
            this.#updateBlockViewProps({ config: { ...this._blockViewProps.config, editContentPath: path } });
        }, null);
        this.observe(this.#context.workspaceEditSettingsPath, (path) => {
            this._workspaceEditSettingsPath = path;
            this.#updateBlockViewProps({ config: { ...this._blockViewProps.config, editSettingsPath: path } });
        }, null);
        this.observe(this.#context.readOnlyGuard.permitted, (isReadOnly) => (this._isReadOnly = isReadOnly), 'umbReadOnlyObserver');
    }
    async #observeData() {
        this.observe(await this.#context.contentValues(), (content) => {
            this.#updateBlockViewProps({ content });
        }, null);
        this.observe(await this.#context.settingsValues(), (settings) => {
            this.#updateBlockViewProps({ settings });
        }, null);
    }
    connectedCallback() {
        super.connectedCallback();
        // element styling:
        this.observe(this.#context.contentElementTypeKey, (contentElementTypeKey) => {
            if (contentElementTypeKey) {
                this.setAttribute('data-content-element-type-key', contentElementTypeKey);
            }
        }, 'contentElementTypeKey');
        this.observe(this.#context.contentElementTypeAlias, (contentElementTypeAlias) => {
            if (contentElementTypeAlias) {
                this._contentTypeAlias = contentElementTypeAlias;
                this.setAttribute('data-content-element-type-alias', contentElementTypeAlias);
            }
        }, 'contentElementTypeAlias');
        this.observe(this.#context.contentElementTypeName, (contentElementTypeName) => {
            this._contentTypeName = contentElementTypeName;
        }, 'contentElementTypeName');
    }
    #expose;
    async #copyToClipboard() {
        const propertyDatasetContext = await this.getContext(UMB_PROPERTY_DATASET_CONTEXT);
        const propertyContext = await this.getContext(UMB_PROPERTY_CONTEXT);
        const clipboardContext = await this.getContext(UMB_CLIPBOARD_PROPERTY_CONTEXT);
        if (!propertyDatasetContext || !propertyContext || !clipboardContext) {
            throw new Error('Could not get required contexts to copy.');
        }
        const workspaceName = propertyDatasetContext?.getName();
        const propertyLabel = propertyContext?.getLabel();
        const blockLabel = this.#context.getName();
        const entryName = workspaceName
            ? `${workspaceName} - ${propertyLabel} - ${blockLabel}`
            : `${propertyLabel} - ${blockLabel}`;
        const content = this.#context.getContent();
        const layout = this.#context.getLayout();
        const settings = this.#context.getSettings();
        const expose = this.#context.getExpose();
        const propertyValue = {
            contentData: content ? [structuredClone(content)] : [],
            layout: {
                [UMB_BLOCK_SINGLE_PROPERTY_EDITOR_SCHEMA_ALIAS]: layout ? [structuredClone(layout)] : undefined,
            },
            settingsData: settings ? [structuredClone(settings)] : [],
            expose: expose ? [structuredClone(expose)] : [],
        };
        clipboardContext.write({
            icon: this._icon,
            name: entryName,
            propertyValue,
            propertyEditorUiAlias: UMB_BLOCK_SINGLE_PROPERTY_EDITOR_UI_ALIAS,
        });
    }
    #extensionSlotFilterMethod;
    #extensionSlotRenderMethod;
    #renderRefBlock() {
        return html `<umb-ref-single-block
			.label=${this._label}
			.icon=${this._icon}
			.unpublished=${!this._exposed}
			.config=${this._blockViewProps.config}
			.content=${this._blockViewProps.content}
			.settings=${this._blockViewProps.settings}
			${umbDestroyOnDisconnect()}></umb-ref-single-block>`;
    }
    #renderInlineBlock() {
        return html `<umb-inline-single-block
			.label=${this._label}
			.icon=${this._icon}
			.unpublished=${!this._exposed}
			.config=${this._blockViewProps.config}
			.content=${this._blockViewProps.content}
			.settings=${this._blockViewProps.settings}
			${umbDestroyOnDisconnect()}></umb-inline-single-block>`;
    }
    #renderUnsupportedBlock() {
        return html `<umb-unsupported-single-block
			.config=${this._blockViewProps.config}
			.content=${this._blockViewProps.content}
			.settings=${this._blockViewProps.settings}
			${umbDestroyOnDisconnect()}></umb-unsupported-single-block>`;
    }
    #renderBuiltinBlockView;
    #renderBlock() {
        return this.contentKey && (this._contentTypeAlias || this._unsupported)
            ? html `
					<div class="umb-block-single__block">
						<umb-extension-slot
							type="blockEditorCustomView"
							default-element=${this._inlineEditingMode ? 'umb-inline-single-block' : 'umb-ref-single-block'}
							.renderMethod=${this.#extensionSlotRenderMethod}
							.fallbackRenderMethod=${this.#renderBuiltinBlockView}
							.props=${this._blockViewProps}
							.filter=${this.#extensionSlotFilterMethod}
							single></umb-extension-slot>
						${this.#renderActionBar()}
						${!this._showContentEdit && this._contentInvalid
                ? html `<uui-badge attention color="invalid" label="Invalid content">!</uui-badge>`
                : nothing}
					</div>
				`
            : nothing;
    }
    #renderActionBar() {
        return this._showActions
            ? html `<uui-action-bar>
					${this.#renderEditContentAction()} ${this.#renderEditSettingsAction()} ${this.#renderCopyToClipboardAction()}
					${this.#renderDeleteAction()}
				</uui-action-bar>`
            : nothing;
    }
    #renderEditContentAction() {
        if (this._isReadOnly)
            return nothing;
        return this._showContentEdit && this._workspaceEditContentPath
            ? html `<uui-button
					label="edit"
					look="secondary"
					color=${this._contentInvalid ? 'invalid' : ''}
					href=${this._workspaceEditContentPath}>
					<uui-icon name=${this._exposed === false && this._isReadOnly === false ? 'icon-add' : 'icon-edit'}></uui-icon>
					${this._contentInvalid
                ? html `<uui-badge attention color="invalid" label="Invalid content">!</uui-badge>`
                : nothing}
				</uui-button>`
            : this._showContentEdit === false && this._exposed === false
                ? html `<uui-button
						@click=${this.#expose}
						label=${this.localize.term('blockEditor_createThisFor', this._contentTypeName)}
						look="secondary"
						><uui-icon name="icon-add"></uui-icon
					></uui-button>`
                : nothing;
    }
    #renderEditSettingsAction() {
        if (this._isReadOnly)
            return nothing;
        return html `
			${this._hasSettings && this._workspaceEditSettingsPath
            ? html `<uui-button
						label="Edit settings"
						look="secondary"
						color=${this._settingsInvalid ? 'invalid' : ''}
						href=${this._workspaceEditSettingsPath}>
						<uui-icon name="icon-settings"></uui-icon>
						${this._settingsInvalid
                ? html `<uui-badge attention color="invalid" label="Invalid settings">!</uui-badge>`
                : nothing}
					</uui-button>`
            : nothing}
		`;
    }
    #renderDeleteAction() {
        if (this._isReadOnly)
            return nothing;
        return html ` <uui-button label="delete" look="secondary" @click=${() => this.#context.requestDelete()}>
			<uui-icon name="icon-remove"></uui-icon>
		</uui-button>`;
    }
    #renderCopyToClipboardAction() {
        return html `
			<uui-button
				label=${this.localize.term('clipboard_labelForCopyToClipboard')}
				look="secondary"
				@click=${() => this.#copyToClipboard()}>
				<uui-icon name="icon-clipboard-copy"></uui-icon>
			</uui-button>
		`;
    }
    render() {
        return this.#renderBlock();
    }
    static { this.styles = [
        UUIBlinkKeyframes,
        css `
			:host {
				position: relative;
				display: block;
				--umb-block-single-entry-actions-opacity: 0;
			}

			:host([settings-invalid]),
			:host([content-invalid]),
			:host(:hover),
			:host(:focus-within) {
				--umb-block-single-entry-actions-opacity: 1;
			}

			:host::after {
				content: '';
				position: absolute;
				z-index: 1;
				pointer-events: none;
				inset: 0;
				border: 1px solid transparent;
				border-radius: var(--uui-border-radius);

				transition: border-color 240ms ease-in;
			}

			:host([settings-invalid])::after,
			:host([content-invalid])::after {
				border-color: var(--uui-color-invalid);
			}

			umb-extension-slot::part(component) {
				position: relative;
				z-index: 0;
			}

			uui-action-bar {
				position: absolute;
				top: var(--uui-size-2);
				right: var(--uui-size-2);
				opacity: var(--umb-block-single-entry-actions-opacity, 0);
				transition: opacity 120ms;
			}

			uui-badge {
				z-index: 2;
			}

			:host::after {
				content: '';
				position: absolute;
				z-index: 1;
				pointer-events: none;
				inset: 0;
				border: 1px solid transparent;
				border-radius: var(--uui-border-radius);

				transition: border-color 240ms ease-in;
			}
			:host(:hover):not(:drop)::after {
				display: block;
				border-color: var(--uui-color-interactive-emphasis);
				box-shadow:
					0 0 0 1px rgba(255, 255, 255, 0.7),
					inset 0 0 0 1px rgba(255, 255, 255, 0.7);
			}

			:host([drag-placeholder])::after {
				display: block;
				border-width: 2px;
				border-color: var(--uui-color-interactive-emphasis);
				animation: ${UUIBlinkAnimationValue};
			}
			:host([drag-placeholder])::before {
				content: '';
				position: absolute;
				pointer-events: none;
				inset: 0;
				border-radius: var(--uui-border-radius);
				background-color: var(--uui-color-interactive-emphasis);
				opacity: 0.12;
			}
			:host([drag-placeholder]) .umb-block-single__block {
				transition: opacity 50ms 16ms;
				opacity: 0;
			}
		`,
    ]; }
};
__decorate([
    property({ type: Number })
], UmbBlockSingleEntryElement.prototype, "index", null);
__decorate([
    property({ attribute: false })
], UmbBlockSingleEntryElement.prototype, "contentKey", null);
__decorate([
    state()
], UmbBlockSingleEntryElement.prototype, "_contentTypeAlias", void 0);
__decorate([
    state()
], UmbBlockSingleEntryElement.prototype, "_contentTypeName", void 0);
__decorate([
    state()
], UmbBlockSingleEntryElement.prototype, "_showContentEdit", void 0);
__decorate([
    state()
], UmbBlockSingleEntryElement.prototype, "_hasSettings", void 0);
__decorate([
    state()
], UmbBlockSingleEntryElement.prototype, "_label", void 0);
__decorate([
    state()
], UmbBlockSingleEntryElement.prototype, "_icon", void 0);
__decorate([
    state()
], UmbBlockSingleEntryElement.prototype, "_exposed", void 0);
__decorate([
    state()
], UmbBlockSingleEntryElement.prototype, "_unsupported", void 0);
__decorate([
    state()
], UmbBlockSingleEntryElement.prototype, "_showActions", void 0);
__decorate([
    state()
], UmbBlockSingleEntryElement.prototype, "_workspaceEditContentPath", void 0);
__decorate([
    state()
], UmbBlockSingleEntryElement.prototype, "_workspaceEditSettingsPath", void 0);
__decorate([
    state()
], UmbBlockSingleEntryElement.prototype, "_inlineEditingMode", void 0);
__decorate([
    property({ type: Boolean, attribute: 'content-invalid', reflect: true })
], UmbBlockSingleEntryElement.prototype, "_contentInvalid", void 0);
__decorate([
    property({ type: Boolean, attribute: 'settings-invalid', reflect: true })
], UmbBlockSingleEntryElement.prototype, "_settingsInvalid", void 0);
__decorate([
    state()
], UmbBlockSingleEntryElement.prototype, "_blockViewProps", void 0);
__decorate([
    state()
], UmbBlockSingleEntryElement.prototype, "_isReadOnly", void 0);
UmbBlockSingleEntryElement = __decorate([
    customElement('umb-block-single-entry')
], UmbBlockSingleEntryElement);
export { UmbBlockSingleEntryElement };
export default UmbBlockSingleEntryElement;
