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 { UMB_BLOCK_RTE, UMB_BLOCK_RTE_PROPERTY_EDITOR_SCHEMA_ALIAS } from '../../constants.js';
import { UmbBlockRteEntryContext } from '../../context/block-rte-entry.context.js';
import { css, customElement, html, nothing, property, state } from '../../../../../external/lit/index.js';
import { stringOrStringArrayContains } from '../../../../core/utils/index.js';
import { UmbLitElement } from '../../../../core/lit-element/index.js';
import { UmbDataPathBlockElementDataQuery } from '../../../block/index.js';
import { UmbObserveValidationStateController } from '../../../../core/validation/index.js';
import { UmbTextStyles } from '../../../../core/style/index.js';
import { UMB_CLIPBOARD_PROPERTY_CONTEXT } from '../../../../clipboard/index.js';
import { UMB_PROPERTY_DATASET_CONTEXT, UMB_PROPERTY_CONTEXT } from '../../../../core/property/index.js';
import '../ref-rte-block/index.js';
/**
 * @class UmbBlockRteEntryElement
 */
let UmbBlockRteEntryElement = class UmbBlockRteEntryElement extends UmbLitElement {
    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');
    }
    get contentKey() {
        return this._contentKey;
    }
    #context;
    #updateBlockViewProps(incoming) {
        this._blockViewProps = { ...this._blockViewProps, ...incoming };
        this.requestUpdate('_blockViewProps');
    }
    #clipboardContext;
    constructor() {
        super();
        this.#context = new UmbBlockRteEntryContext(this);
        this._showContentEdit = false;
        this._hasSettings = false;
        this._label = '';
        this._isReadOnly = false;
        this._blockViewProps = {
            contentKey: undefined,
            config: { showContentEdit: false, showSettingsEdit: false },
        }; // Set to undefined cause it will be set before we render.
        this.#filterBlockCustomViews = (manifest) => {
            const elementTypeAlias = this._contentTypeAlias ?? '';
            const isForBlockEditor = !manifest.forBlockEditor || stringOrStringArrayContains(manifest.forBlockEditor, UMB_BLOCK_RTE);
            const isForContentTypeAlias = !manifest.forContentTypeAlias || stringOrStringArrayContains(manifest.forContentTypeAlias, elementTypeAlias);
            return isForBlockEditor && isForContentTypeAlias;
        };
        this.#expose = () => {
            this.#context.expose();
        };
        this.#extensionSlotRenderMethod = (ext) => {
            ext.component?.setAttribute('part', 'component');
            if (this._exposed || this._isReadOnly) {
                return ext.component;
            }
            else {
                return html `<div>
				${ext.component}
				<umb-block-overlay-expose-button
					.contentTypeName=${this._contentTypeName}
					@click=${this.#expose}></umb-block-overlay-expose-button>
			</div>`;
            }
        };
        this.#renderBuiltinBlockView = () => {
            // TODO: Missing unsupported rendering [NL]
            /*if (this._unsupported) {
                return this.#renderUnsupportedBlock();
            }*/
            return this.#renderRefBlock();
        };
        // We do not have index for RTE Blocks at the moment.
        this.#context.setIndex(0);
        this.consumeContext(UMB_CLIPBOARD_PROPERTY_CONTEXT, (clipboardContext) => {
            this.#clipboardContext = clipboardContext;
        });
        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.contentElementTypeAlias, (alias) => {
            this._contentTypeAlias = alias;
        }, null);
        this.observe(this.#context.contentElementTypeName, (contentElementTypeName) => {
            this._contentTypeName = contentElementTypeName;
        }, null);
        this.observe(this.#context.blockType, (blockType) => {
            this.#updateBlockViewProps({ blockType });
        }, null);
        this.observe(this.#context.index, (index) => this.#updateBlockViewProps({ index }), null);
        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.actionsVisibility, (showActions) => {
            this._showActions = showActions;
        }, 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();
        this.setAttribute('contenteditable', 'false');
    }
    async #copyToClipboard() {
        if (!this.#clipboardContext) {
            console.warn('Clipboard context is not available.');
            return;
        }
        const propertyDatasetContext = await this.getContext(UMB_PROPERTY_DATASET_CONTEXT);
        const propertyContext = await this.getContext(UMB_PROPERTY_CONTEXT);
        if (!propertyDatasetContext || !propertyContext) {
            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, propertyLabel, blockLabel].filter(Boolean).join(' - ');
        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_RTE_PROPERTY_EDITOR_SCHEMA_ALIAS]: layout ? [structuredClone(layout)] : undefined },
            settingsData: settings ? [structuredClone(settings)] : [],
            expose: expose ? [structuredClone(expose)] : [],
        };
        const editorUiManifest = propertyContext.getEditorManifest();
        this.#clipboardContext.write({
            icon: this._icon,
            name: entryName,
            propertyValue,
            propertyEditorUiAlias: editorUiManifest?.alias ?? '',
        });
    }
    #filterBlockCustomViews;
    #expose;
    #extensionSlotRenderMethod;
    #renderBlock() {
        return this.contentKey && this._contentTypeAlias
            ? html `
					<div class="uui-text uui-font">
						<umb-extension-slot
							type="blockEditorCustomView"
							default-element="umb-ref-rte-block"
							.renderMethod=${this.#extensionSlotRenderMethod}
							.fallbackRenderMethod=${this.#renderBuiltinBlockView}
							.props=${this._blockViewProps}
							.filter=${this.#filterBlockCustomViews}
							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() {
        if (!this._showActions)
            return nothing;
        return html `
			<uui-action-bar>
				${this.#renderEditAction()} ${this.#renderEditSettingsAction()} ${this.#renderCopyToClipboardAction()}${this.#renderDeleteAction()}
			</uui-action-bar>
		`;
    }
    #renderBuiltinBlockView;
    #renderRefBlock() {
        return html `<umb-ref-rte-block
			.label=${this._label}
			.icon=${this._icon}
			.index=${this._blockViewProps.index}
			.unpublished=${!this._exposed}
			.content=${this._blockViewProps.content}
			.settings=${this._blockViewProps.settings}
			.config=${this._blockViewProps.config}></umb-ref-rte-block>`;
    }
    #renderEditAction() {
        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 ? '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}
		`;
    }
    #renderCopyToClipboardAction() {
        if (!this.#clipboardContext)
            return nothing;
        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>
		`;
    }
    #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>
		`;
    }
    render() {
        return this.#renderBlock();
    }
    static { this.styles = [
        UmbTextStyles,
        css `
			:host {
				position: relative;
				display: block;
				user-select: all;
				user-drag: auto;
				white-space: nowrap;
			}

			:host(.ProseMirror-selectednode) {
				umb-ref-rte-block {
					--uui-color-default-contrast: initial;
					outline: 3px solid var(--uui-color-focus);
				}
			}

			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);
			}

			:host([drag-placeholder]) {
				opacity: 0.2;
			}
		`,
    ]; }
};
__decorate([
    property({ type: String, attribute: 'data-content-key', reflect: true })
], UmbBlockRteEntryElement.prototype, "contentKey", null);
__decorate([
    state()
], UmbBlockRteEntryElement.prototype, "_showContentEdit", void 0);
__decorate([
    state()
], UmbBlockRteEntryElement.prototype, "_hasSettings", void 0);
__decorate([
    state()
], UmbBlockRteEntryElement.prototype, "_label", void 0);
__decorate([
    state()
], UmbBlockRteEntryElement.prototype, "_icon", void 0);
__decorate([
    state()
], UmbBlockRteEntryElement.prototype, "_exposed", void 0);
__decorate([
    state()
], UmbBlockRteEntryElement.prototype, "_showActions", void 0);
__decorate([
    state()
], UmbBlockRteEntryElement.prototype, "_workspaceEditContentPath", void 0);
__decorate([
    state()
], UmbBlockRteEntryElement.prototype, "_workspaceEditSettingsPath", void 0);
__decorate([
    state()
], UmbBlockRteEntryElement.prototype, "_contentTypeAlias", void 0);
__decorate([
    state()
], UmbBlockRteEntryElement.prototype, "_contentTypeName", void 0);
__decorate([
    state()
], UmbBlockRteEntryElement.prototype, "_isReadOnly", void 0);
__decorate([
    state()
], UmbBlockRteEntryElement.prototype, "_blockViewProps", void 0);
__decorate([
    property({ type: Boolean, attribute: 'content-invalid', reflect: true })
    // eslint-disable-next-line @typescript-eslint/naming-convention
], UmbBlockRteEntryElement.prototype, "_contentInvalid", void 0);
__decorate([
    property({ type: Boolean, attribute: 'settings-invalid', reflect: true })
    // eslint-disable-next-line @typescript-eslint/naming-convention
], UmbBlockRteEntryElement.prototype, "_settingsInvalid", void 0);
UmbBlockRteEntryElement = __decorate([
    customElement('umb-rte-block')
], UmbBlockRteEntryElement);
export { UmbBlockRteEntryElement };
export default UmbBlockRteEntryElement;
