// #region Imports
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;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { HTMLElementEventEmitter } from '@breadstone/mosaik-elements';
import { DomServiceLocator } from '../../../../Dom/Dom';
import { RendererServiceLocator } from '../../../../Dom/Renderer';
import { Emit } from '../../../../events/Decorators/EmitDecorator';
import { EID } from '../../../../Utilities/EId';
import { Slottable } from '../../../Behaviors/Slottable';
import { Attribute } from '../../../Decorators/AttributeDecorator';
import { Component } from '../../../Decorators/ComponentDecorator';
import { Property } from '../../../Decorators/PropertyDecorator';
import { CustomElement } from '../../Abstracts/CustomElement';
import { MOSAIK_PORTAL_SCOPE_ATTRIBUTE } from './MosaikPortalScopeAttribute';
import { PORTAL_HOST_REGISTRY } from './Portal';
import { portalElementTemplate } from './PortalElementTemplate';
import { PortalProjectionElement } from './PortalProjectionElement';
/**
 * Portal - A teleportation mechanism that renders content in a different location in the DOM tree.
 *
 * @description
 * The Portal component enables rendering content outside its parent component's DOM hierarchy while maintaining
 * logical component relationships. It projects slotted content to a destination element (typically document.body
 * or a portal host), which is essential for modals, dialogs, toasts, and other overlay components that need to
 * escape z-index stacking contexts, overflow constraints, and CSS containment. The portal automatically manages
 * content lifecycle, style adoption, and cleanup when disconnected.
 *
 * @name Portal
 * @element mosaik-portal
 * @category Primitives
 *
 * @slot - The content to be portaled to the destination
 *
 * @cssprop {String} --portal-font-family - The font family CSS custom property.
 * @cssprop {String} --portal-font-letter-spacing - The font letter spacing CSS custom property.
 * @cssprop {String} --portal-font-line-height - The font line height CSS custom property.
 * @cssprop {String} --portal-font-size - The font size CSS custom property.
 * @cssprop {String} --portal-font-text-decoration - The font text decoration CSS custom property.
 * @cssprop {String} --portal-font-text-transform - The font text transform CSS custom property.
 * @cssprop {String} --portal-font-weight - The font weight CSS custom property.
 * @cssprop {String} --portal-gap - The gap CSS custom property.
 * @cssprop {String} --portal-padding-bottom - The padding bottom CSS custom property.
 * @cssprop {String} --portal-padding-left - The padding left CSS custom property.
 * @cssprop {String} --portal-padding-right - The padding right CSS custom property.
 * @cssprop {String} --portal-padding-top - The padding top CSS custom property.
 * @cssprop {String} --portal-shadow - The shadow CSS custom property.
 * @cssprop {String} --portal-shadow-blur - The shadow blur CSS custom property.
 * @cssprop {String} --portal-shadow-color - The shadow color CSS custom property.
 * @cssprop {String} --portal-shadow-offset-x - The shadow offset x CSS custom property.
 * @cssprop {String} --portal-shadow-offset-y - The shadow offset y CSS custom property.
 * @cssprop {String} --portal-shadow-spread - The shadow spread CSS custom property.
 * @cssprop {String} --portal-transition-duration - The transition duration CSS custom property.
 * @cssprop {String} --portal-transition-mode - The transition mode CSS custom property.
 * @cssprop {String} --portal-transition-property - The transition property CSS custom property.
 * @cssprop {String} --portal-translate - The translate CSS custom property.
 *
 * @fires portalAttached {PortalAttachedEvent} - Fired when the portal is attached to the DOM
 * @fires portalDetached {PortalDetachedEvent} - Fired when the portal is detached from the DOM
 *
 * @example
 * Basic portal to document body:
 * ```html
 * <div class="app-container">
 *   <mosaik-portal>
 *     <mosaik-dialog>This renders in document.body</mosaik-dialog>
 *   </mosaik-portal>
 * </div>
 * ```
 *
 * @example
 * Portal to named host:
 * ```html
 * <!-- Somewhere in layout -->
 * <mosaik-portal-host name="modals"></mosaik-portal-host>
 *
 * <!-- Portal content to host -->
 * <mosaik-portal destination="modals">
 *   <mosaik-modal>Content renders in modals host</mosaik-modal>
 * </mosaik-portal>
 * ```
 *
 * @example
 * Toast notification portal:
 * ```html
 * <mosaik-portal id="toastPortal">
 *   <div class="toast">Operation successful!</div>
 * </mosaik-portal>
 * <script>
 *   const portal = document.querySelector('#toastPortal');
 *   portal.addEventListener('portalAttached', () => {
 *     console.log('Toast is now visible');
 *   });
 * </script>
 * ```
 *
 * @public
 */
let PortalElement = class PortalElement extends Slottable(CustomElement) {
    // #region Fields
    _attached;
    _detached;
    _projection;
    _destination;
    _adoptedStyles;
    _isProjected;
    // #endregion
    // #region Ctor
    /**
     * @public
     */
    constructor() {
        super();
        this._projection = null;
        this._destination = document.body;
        this._adoptedStyles = undefined;
        this._isProjected = false;
        this._attached = new HTMLElementEventEmitter(this, 'portalAttached');
        this._detached = new HTMLElementEventEmitter(this, 'portalDetached');
    }
    // #endregion
    // #region Properties
    /**
     * Returns the `is` property.
     *
     * @public
     * @static
     * @readonly
    */
    static get is() {
        return 'mosaik-portal';
    }
    /**
     * Gets or sets the `destination` property.
     *
     * @public
     * @attr
     */
    get destination() {
        return this._destination;
    }
    set destination(value) {
        if (this._destination !== value) {
            this._destination = value;
            this.requestUpdate('destination');
        }
    }
    /**
     * Gets or sets the `adoptedStyles` property.
     *
     * @public
     */
    get adoptedStyles() {
        return this._adoptedStyles;
    }
    set adoptedStyles(value) {
        if (this._adoptedStyles !== value) {
            this._adoptedStyles = value;
            this.requestUpdate('adoptedStyles');
        }
    }
    /**
     * Gets or sets the `isProjected` property.
     *
     * @public
     * @attr
     * @readonly
     */
    get isProjected() {
        return this._isProjected;
    }
    set isProjected(value) {
        if (this._isProjected !== value) {
            this._isProjected = value;
            this.requestUpdate('isProjected');
        }
    }
    /**
     * Gets the `projection` property.
     *
     * @public
     * @readonly
     */
    get projection() {
        return this._projection;
    }
    /**
     * Called when a projection is attached to the DOM.
     * Provides reference to `IPortalAttachedEventDetail` as event argument.
     *
     * @public
     * @readonly
     * @eventProperty
     * @type IEventEmitter<IPortalAttachedEventDetail>
     */
    get attached() {
        return this._attached;
    }
    /**
     * Called when a projection is detached from the DOM.
     * Provides reference to `IPortalDetachedEventDetail` as event argument.
     *
     * @public
     * @readonly
     * @eventProperty
     * @type IEventEmitter<IPortalDetachedEventDetail>
     */
    get detached() {
        return this._detached;
    }
    // #endregion
    // #region Methods
    /**
     * @public
     * @overload
     */
    onSlotChanges(slotName) {
        // this is the slot to react on child menu changes
        if (slotName === '') {
            this.attach();
        }
    }
    /**
     * @public
     * @override
     */
    connectedCallback() {
        super.connectedCallback();
        // When the portal reconnects (e.g., after being moved in the DOM by
        // Lit's repeat() directive), re-project content that was restored
        // during detach(). The slotchange event should handle this as well,
        // but some browsers may not fire slotchange when an element is moved
        // within the same document, so we add an explicit check.
        if (!this._isProjected && this.children.length > 0) {
            queueMicrotask(() => {
                if (this.isConnected && !this._isProjected) {
                    this.attach();
                }
            });
        }
    }
    /**
     * @public
     * @override
     */
    disconnectedCallback() {
        this.detach();
        super.disconnectedCallback();
    }
    /**
     * @protected
     * @override
     */
    onApplyTemplate() {
        super.onApplyTemplate();
        this.attach();
    }
    /**
     * @protected
     */
    attach() {
        const projection = this.createProjection();
        const destination = this.getDestination();
        const elements = this.appendElements(projection, destination);
        // important: this is needed to let the projection element inherit the styles from the portal root element.
        //            but we have to wait until the projection is connected to the DOM.
        if (this._projection?.shadowRoot && this._adoptedStyles) {
            this._projection.shadowRoot.adoptedStyleSheets = [...this._adoptedStyles];
        }
        this.isProjected = true;
        this._attached.emit({
            destination: destination,
            projection: projection,
            elements: elements
        });
    }
    /**
     * @protected
     */
    detach() {
        if (this._projection) {
            const destination = this._projection.parentElement ?? this.getDestination();
            // Restore projected children back to the portal so they can be
            // re-projected when the portal reconnects (e.g., when Lit's
            // repeat() directive reorders DOM elements).
            while (this._projection.firstChild) {
                this.appendChild(this._projection.firstChild);
            }
            if (this._projection.parentNode) {
                this._projection.parentNode.removeChild(this._projection);
            }
            this.isProjected = false;
            this._detached.emit({
                destination: destination,
                projection: this._projection
            });
            this._projection = null;
        }
    }
    /**
     * @private
     */
    getDestination() {
        if (typeof this._destination === 'string') {
            const host = PORTAL_HOST_REGISTRY.get(this._destination);
            if (host) {
                return host;
            }
            return DomServiceLocator.current.findDescendant(document, this._destination, { strict: true });
        }
        // When the default destination (document.body) is used, prefer the
        // nearest ancestor that provides an overlay scope. This keeps focusable
        // projected content inside host-managed focus traps while preserving
        // top-layer paint behavior for native popovers and modal dialogs.
        if (this._destination === document.body) {
            const scopedDestination = this.findDefaultDestinationAncestor();
            if (scopedDestination) {
                return scopedDestination;
            }
        }
        return this._destination;
    }
    /**
     * Walks up from this portal through the DOM and enclosing shadow roots
     * looking for the closest default portal destination.
     *
     * @private
     */
    findDefaultDestinationAncestor() {
        let node = this;
        while (node) {
            if (node instanceof Element) {
                try {
                    if (node.matches(':popover-open') || node.matches(':modal')) {
                        return node;
                    }
                }
                catch {
                    // selector not supported in this environment - ignore
                }
                if (node.hasAttribute(MOSAIK_PORTAL_SCOPE_ATTRIBUTE)) {
                    return node;
                }
            }
            let next = node.parentNode;
            if (!next && node instanceof ShadowRoot) {
                next = node.host;
            }
            node = next;
        }
        return null;
    }
    /**
     * @private
     */
    createProjection() {
        if (!this._projection) {
            this._projection = RendererServiceLocator.current.createElement(PortalProjectionElement.is);
            RendererServiceLocator.current.setAttribute(this._projection, 'id', EID.next(PortalProjectionElement.is));
            this._projection.assign(this);
        }
        return this._projection;
    }
    /**
     * @private
     */
    appendElements(projection, destination) {
        const elements = this.getSlotAssignments('');
        // map portal slot elements to projection children.
        // afterwards append projection to destination.
        for (const element of elements) {
            projection.appendChild(element);
            destination.appendChild(projection);
        }
        return elements;
    }
};
__decorate([
    Attribute({ type: String }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [Object])
], PortalElement.prototype, "destination", null);
__decorate([
    Property({ type: Object }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [Object])
], PortalElement.prototype, "adoptedStyles", null);
__decorate([
    Attribute({
        type: Boolean,
        useDefault: true
    }),
    __metadata("design:type", Boolean),
    __metadata("design:paramtypes", [Boolean])
], PortalElement.prototype, "isProjected", null);
__decorate([
    Emit({ eventName: 'portalAttached' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], PortalElement.prototype, "attached", null);
__decorate([
    Emit({ eventName: 'portalDetached' }),
    __metadata("design:type", Object),
    __metadata("design:paramtypes", [])
], PortalElement.prototype, "detached", null);
PortalElement = __decorate([
    Component({
        selector: 'mosaik-portal',
        template: portalElementTemplate
    }),
    __metadata("design:paramtypes", [])
], PortalElement);
export { PortalElement };
//# sourceMappingURL=PortalElement.js.map