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 { UmbPreviewRepository } from '../repository/preview.repository.js';
import { UMB_PREVIEW_CONTEXT } from '../context/preview.context-token.js';
import { css, customElement, html, nothing, repeat, state } from '../../../external/lit/index.js';
import { umbExtensionsRegistry } from '../../core/extension-registry/index.js';
import { umbPeekError } from '../../core/notification/index.js';
import { UmbLitElement } from '../../core/lit-element/index.js';
let UmbPreviewEnvironmentsElement = class UmbPreviewEnvironmentsElement extends UmbLitElement {
    #fallbackIcon;
    #previewRepository;
    constructor() {
        super();
        this.#fallbackIcon = 'icon-multiple-windows';
        this._items = [];
        this._popoverOpen = false;
        this.#previewRepository = new UmbPreviewRepository(this);
        this.consumeContext(UMB_PREVIEW_CONTEXT, (context) => {
            this.observe(context?.unique, (unique) => (this._unique = unique), '_observeUnique');
            this.observe(context?.culture, (culture) => (this._culture = culture), '_observeCulture');
            this.observe(context?.segment, (segment) => (this._segment = segment), '_observeSegment');
        });
    }
    connectedCallback() {
        super.connectedCallback();
        this.hidden = true;
        this.#getPreviewOptions();
    }
    async #getPreviewOptions() {
        this.observe(umbExtensionsRegistry.byTypeAndFilter('workspaceActionMenuItem', (ext) => ext.kind === 'previewOption'), (manifests) => {
            this._items = manifests.map((manifest) => ({
                alias: manifest.alias,
                label: manifest.meta.label || manifest.name,
                icon: manifest.meta.icon || this.#fallbackIcon,
                urlProviderAlias: manifest.meta.urlProviderAlias,
            }));
            this.hidden = !this._items.length;
        });
    }
    async #onClick(item) {
        if (!this._unique)
            return;
        if (!item.urlProviderAlias)
            return;
        const previewUrlData = await this.#previewRepository.getPreviewUrl(this._unique, item.urlProviderAlias, this._culture, this._segment);
        if (previewUrlData.url) {
            // Add cache-busting parameter to ensure the preview tab reloads with the new preview session
            const previewUrl = new URL(previewUrlData.url, window.document.baseURI);
            previewUrl.searchParams.set('rnd', Date.now().toString());
            const previewWindow = window.open(previewUrl.toString(), `umbpreview-${this._unique}`);
            previewWindow?.focus();
            return;
        }
        if (previewUrlData.message) {
            umbPeekError(this, {
                color: 'danger',
                headline: this.localize.term('general_preview'),
                message: previewUrlData.message,
            });
        }
    }
    #onPopoverToggle(event) {
        this._popoverOpen = event.newState === 'open';
    }
    render() {
        if (!this._items.length)
            return nothing;
        return html `
			<uui-button look="primary" popovertarget="options-popover">
				<div>
					<uui-icon name=${this.#fallbackIcon}></uui-icon>
					<span>Preview environments</span>
				</div>
				<uui-symbol-expand slot="extra" id="expand-symbol" .open=${this._popoverOpen}></uui-symbol-expand>
			</uui-button>
			<uui-popover-container id="options-popover" placement="top-end" @toggle=${this.#onPopoverToggle}>
				<umb-popover-layout>
					${repeat(this._items, (item) => item.alias, (item) => html `
							<uui-menu-item label=${this.localize.string(item.label)} @click=${() => this.#onClick(item)}>
								<uui-icon slot="icon" name=${item.icon}></uui-icon>
							</uui-menu-item>
						`)}
				</umb-popover-layout>
			</uui-popover-container>
		`;
    }
    static { this.styles = [
        css `
			:host {
				display: flex;
				border-left: 1px solid var(--uui-color-header-contrast);
				--uui-button-font-weight: 400;
				--uui-button-padding-left-factor: 3;
				--uui-button-padding-right-factor: 3;
				--uui-menu-item-flat-structure: 1;
			}

			:host([hidden]) {
				display: none;
			}

			#expand-symbol {
				transform: rotate(-90deg);
				margin-left: var(--uui-size-space-3, 9px);

				&[open] {
					transform: rotate(0deg);
				}
			}

			uui-button > div {
				display: flex;
				align-items: center;
				gap: var(--uui-size-2, 6px);
			}

			umb-popover-layout {
				--uui-color-surface: var(--uui-color-header-surface);
				--uui-color-border: var(--uui-color-header-surface);
				color: var(--uui-color-header-contrast);
			}
		`,
    ]; }
};
__decorate([
    state()
], UmbPreviewEnvironmentsElement.prototype, "_culture", void 0);
__decorate([
    state()
], UmbPreviewEnvironmentsElement.prototype, "_items", void 0);
__decorate([
    state()
], UmbPreviewEnvironmentsElement.prototype, "_popoverOpen", void 0);
__decorate([
    state()
], UmbPreviewEnvironmentsElement.prototype, "_segment", void 0);
__decorate([
    state()
], UmbPreviewEnvironmentsElement.prototype, "_unique", void 0);
UmbPreviewEnvironmentsElement = __decorate([
    customElement('umb-preview-environments')
], UmbPreviewEnvironmentsElement);
export { UmbPreviewEnvironmentsElement };
export { UmbPreviewEnvironmentsElement as element };
