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_WORKSPACE_VIEW_PATH_PATTERN } from '../../paths.js';
import { UmbWorkspaceEditorContext } from './workspace-editor.context.js';
import { css, customElement, html, nothing, property, repeat, state, when } from '../../../../../external/lit/index.js';
import { createExtensionElement } from '../../../../../libs/extension-api/index.js';
import { UmbLitElement } from '../../../lit-element/index.js';
import { UmbTextStyles } from '../../../style/index.js';
/**
 * @element umb-workspace-editor
 * @description
 * @slot header - Slot for workspace header
 * @slot action-menu - Slot for workspace header
 * @slot footer-info - Slot for workspace footer
 * @slot actions - Slot for workspace footer actions
 * @slot - slot for main content
 * @class UmbWorkspaceEditorElement
 * @augments {UmbLitElement}
 */
let UmbWorkspaceEditorElement = class UmbWorkspaceEditorElement extends UmbLitElement {
    //
    #navigationContext;
    #workspaceViewHintObservers;
    get variantId() {
        return this._variantId;
    }
    set variantId(value) {
        if (value && this._variantId?.equal(value)) {
            return;
        }
        this._variantId = value;
        this.#navigationContext.setVariantId(value);
        this.#observeWorkspaceViewHints();
    }
    set overrides(value) {
        this.#navigationContext.setOverrides(value);
    }
    get overrides() {
        return undefined;
    }
    constructor() {
        super();
        //
        this.#navigationContext = new UmbWorkspaceEditorContext(this);
        this.#workspaceViewHintObservers = [];
        this.headline = '';
        this.hideNavigation = false;
        this.enforceNoFooter = false;
        this.loading = false;
        this._workspaceViews = [];
        this._hintMap = new Map();
        this.observe(this.#navigationContext.views, (views) => {
            this._workspaceViews = views;
            this.#observeWorkspaceViewHints();
            this.#createRoutes();
        }, null);
    }
    #observeWorkspaceViewHints() {
        this.#workspaceViewHintObservers.forEach((observer) => observer.destroy());
        this._hintMap = new Map();
        this.#workspaceViewHintObservers = this._workspaceViews.map((view, index) => this.observe(view.firstHintOfVariant, (hint) => {
            if (hint) {
                this._hintMap.set(view.manifest.alias, hint);
            }
            else {
                this._hintMap.delete(view.manifest.alias);
            }
            this.requestUpdate('_hintMap');
        }, 'umbObserveState_' + index));
    }
    #currentProvidedView;
    #createRoutes() {
        const newRoutes = [];
        if (this._workspaceViews.length > 0) {
            this._workspaceViews.forEach((context) => {
                const manifest = context.manifest;
                const path = UMB_WORKSPACE_VIEW_PATH_PATTERN.generateLocal({ viewPathname: manifest.meta.pathname });
                newRoutes.push({
                    unique: manifest.alias,
                    path,
                    component: () => createExtensionElement(manifest),
                    setup: (component) => {
                        if (this.#currentProvidedView !== context) {
                            this.#currentProvidedView?.unprovide();
                        }
                        if (component) {
                            this.#currentProvidedView = context;
                            context.provideAt(component);
                            component.manifest = manifest;
                        }
                    },
                });
            });
            // Duplicate first workspace and use it for the empty path scenario. [NL]
            newRoutes.push({ ...newRoutes[0], unique: newRoutes[0].path, path: '' });
        }
        // Add a catch-all route for not found
        // This will be the last route, so it will only match if no other routes match or if no workspace views are defined.
        newRoutes.push({
            path: `**`,
            component: async () => (await import('../../../router/index.js')).UmbRouteNotFoundElement,
        });
        this._routes = newRoutes;
    }
    render() {
        // Notice if no routes then fallback to use a slot.
        // TODO: Deprecate the slot feature, to rely purely on routes, cause currently bringing an additional route would mean the slotted content would never be shown. [NL]
        return html `
			<umb-body-layout main-no-padding .headline=${this.headline} ?loading=${this.loading}>
				${this.#renderBackButton()}
				<slot name="header" slot="header"></slot>
				<slot name="action-menu" slot="action-menu"></slot>
				${this.#renderViews()} ${this.#renderRoutes()}
				<slot></slot>
				${when(!this.enforceNoFooter, () => html `
						<umb-workspace-footer slot="footer" data-mark="workspace:footer">
							<slot name="footer-info"></slot>
							<slot name="actions" slot="actions" data-mark="workspace:footer-actions"></slot>
						</umb-workspace-footer>
					`)}
			</umb-body-layout>
		`;
    }
    #renderViews() {
        return html `
			${!this.hideNavigation && this._workspaceViews.length > 1
            ? html `
						<uui-tab-group slot="navigation" data-mark="workspace:view-links">
							${repeat(this._workspaceViews, (view) => view.manifest.alias, (view, index) => {
                const manifest = view.manifest;
                const displayName = manifest.meta.label ? this.localize.string(manifest.meta.label) : manifest.name;
                const hint = this._hintMap.get(manifest.alias);
                const active = 'view/' + manifest.meta.pathname === this._activePath || (index === 0 && this._activePath === '');
                // Notice how we use index 0 to determine which workspace that is active with empty path. [NL]
                return html `
										<uui-tab
											href="${this._routerPath}/view/${manifest.meta.pathname}"
											.label=${displayName}
											?active=${active}
											data-mark="workspace:view-link:${manifest.alias}">
											<div slot="icon">
												<umb-icon name=${manifest.meta.icon}></umb-icon> ${hint && !active
                    ? html `<umb-badge .color=${hint.color ?? 'default'} ?attention=${hint.color === 'invalid'}
															>${hint.text}</umb-badge
														>`
                    : nothing}
											</div>
											${displayName}
										</uui-tab>
									`;
            })}
						</uui-tab-group>
					`
            : nothing}
		`;
    }
    #renderBackButton() {
        if (!this.backPath)
            return nothing;
        return html `
			<uui-button
				slot="header"
				class="back-button"
				compact
				href=${this.backPath}
				label=${this.localize.term('general_back')}
				data-mark="action:back">
				<uui-icon name="icon-arrow-left"></uui-icon>
			</uui-button>
		`;
    }
    #renderRoutes() {
        if (!this._routes || this._routes.length === 0 || !this._workspaceViews || this._workspaceViews.length === 0) {
            return nothing;
        }
        return html `
			<umb-router-slot
				inherit-addendum
				id="router-slot"
				.routes=${this._routes}
				@init=${(event) => {
            this._routerPath = event.target.absoluteRouterPath;
        }}
				@change=${(event) => {
            this._activePath = event.target.localActiveViewPath;
        }}></umb-router-slot>
		`;
    }
    static { this.styles = [
        UmbTextStyles,
        css `
			:host {
				display: block;
				width: 100%;
				height: 100%;
			}

			#router-slot {
				display: flex;
				flex-direction: column;
				height: 100%;
			}

			.back-button {
				margin-right: var(--uui-size-space-4);
			}

			uui-input {
				width: 100%;
			}

			uui-tab-group {
				--uui-tab-divider: var(--uui-color-border);
				border-left: 1px solid var(--uui-color-border);
				border-right: 1px solid var(--uui-color-border);
			}

			div[slot='icon'] {
				position: relative;
			}

			umb-badge {
				font-size: var(--uui-type-small-size);
				right: -1.5em;
			}

			umb-extension-slot[slot='actions'] {
				display: flex;
				gap: var(--uui-size-space-2);
			}
		`,
    ]; }
};
__decorate([
    property()
], UmbWorkspaceEditorElement.prototype, "headline", void 0);
__decorate([
    property({ type: Boolean })
], UmbWorkspaceEditorElement.prototype, "hideNavigation", void 0);
__decorate([
    property({ type: Boolean })
], UmbWorkspaceEditorElement.prototype, "enforceNoFooter", void 0);
__decorate([
    property({ attribute: 'back-path' })
], UmbWorkspaceEditorElement.prototype, "backPath", void 0);
__decorate([
    property({ type: Boolean })
], UmbWorkspaceEditorElement.prototype, "loading", void 0);
__decorate([
    property({ attribute: false })
], UmbWorkspaceEditorElement.prototype, "variantId", null);
__decorate([
    property({ attribute: false })
], UmbWorkspaceEditorElement.prototype, "overrides", null);
__decorate([
    state()
], UmbWorkspaceEditorElement.prototype, "_workspaceViews", void 0);
__decorate([
    state()
], UmbWorkspaceEditorElement.prototype, "_hintMap", void 0);
__decorate([
    state()
], UmbWorkspaceEditorElement.prototype, "_routes", void 0);
__decorate([
    state()
], UmbWorkspaceEditorElement.prototype, "_routerPath", void 0);
__decorate([
    state()
], UmbWorkspaceEditorElement.prototype, "_activePath", void 0);
UmbWorkspaceEditorElement = __decorate([
    customElement('umb-workspace-editor')
], UmbWorkspaceEditorElement);
export { UmbWorkspaceEditorElement };
