import { AXPlatform } from '@acorex/core/platform';
import * as i0 from '@angular/core';
import { inject, NgZone, input, signal, TemplateRef, ViewContainerRef, HostListener, ViewChild, ViewEncapsulation, ChangeDetectionStrategy, Component, Directive, ComponentRef, Injectable, NgModule } from '@angular/core';
import { MXBaseComponent, AXClosableComponent, AXComponent, AXComponentClosedPromise, AXCommonModule } from '@acorex/cdk/common';
import { AXFocusTrapDirective } from '@acorex/cdk/focus-trap';
import { AXDecoratorCloseButtonComponent, AXDecoratorModule } from '@acorex/components/decorators';
import { AXLoadingService } from '@acorex/components/loading';
import { AXComponentService } from '@acorex/core/components';
import { AXTranslatorPipe, AXTranslationModule } from '@acorex/core/translation';
import { AsyncPipe, CommonModule } from '@angular/common';
import { AXOverlayService } from '@acorex/cdk/overlay';
import { Subject } from 'rxjs';

/**
 * The Popup is a component which displays content in a dialog overlay
 *
 * @category Components
 */
class AXPopupComponent extends MXBaseComponent {
    constructor() {
        super(...arguments);
        this._zone = inject(NgZone);
        this.loadingService = inject(AXLoadingService);
        this._platform = inject(AXPlatform);
        this.componentService = inject(AXComponentService);
        // Inputs from overlay service
        this.__content__ = input(...(ngDevMode ? [undefined, { debugName: "__content__" }] : []));
        this.__config__ = input(...(ngDevMode ? [undefined, { debugName: "__config__" }] : []));
        this.__popupRef__ = input(...(ngDevMode ? [undefined, { debugName: "__popupRef__" }] : []));
        this.__id__ = input(...(ngDevMode ? [undefined, { debugName: "__id__" }] : []));
        /**
         * Indicates whether the component is loading.
         * @defaultValue true
         */
        this.isLoading = true;
        /** @ignore */
        this._componentRef = null;
        /** Current title */
        this.title = signal('', ...(ngDevMode ? [{ debugName: "title" }] : []));
        /** @ignore */
        this.isDragging = signal(false, ...(ngDevMode ? [{ debugName: "isDragging" }] : []));
        /** @ignore */
        this.dragOffset = signal({ x: 0, y: 0 }, ...(ngDevMode ? [{ debugName: "dragOffset" }] : []));
        /** @ignore */
        this.dragStartPos = { x: 0, y: 0 };
        /** @ignore */
        this.elementStartPos = { x: 0, y: 0 };
    }
    /** @ignore */
    ngOnInit() {
        super.ngOnInit();
        const config = this.__config__();
        if (this._platform.is('SM')) {
            // Disable dragging on small screens
            if (config) {
                config.draggable = false;
            }
        }
        this.title.set(config?.title ?? '');
        this._loadingId = this.loadingService.show({
            location: this.getHostElement(),
        });
        this.renderContent();
    }
    /** @ignore */
    async renderContent() {
        const content = this.__content__();
        const config = this.__config__();
        if (!content) {
            this.loadingService.hide(this._loadingId);
            return;
        }
        if (content instanceof TemplateRef) {
            // Render template using ViewContainerRef (supports context)
            this.contentContainerRef.createEmbeddedView(content, {
                $implicit: config?.data,
                ref: this,
            });
            this.handleContentRendered();
        }
        else if (typeof content === 'function') {
            // Render component
            const componentRef = this.componentService.createFromComponent(content);
            this._componentRef = componentRef;
            // Expose component instance to the popup ref
            const popupRef = this.__popupRef__();
            if (popupRef) {
                popupRef.componentInstance = componentRef.instance;
            }
            // Get component input definitions to check before setting inputs
            const inputDefs = componentRef.componentType?.ɵcmp
                ?.inputs;
            // Set data inputs (only if the component has the input defined)
            if (config?.data && typeof config.data === 'object') {
                Object.entries(config.data).forEach(([key, value]) => {
                    componentRef.instance[key] = value;
                });
            }
            if (config?.inputs && typeof config.inputs === 'object') {
                Object.entries(config.inputs).forEach(([key, value]) => {
                    if (inputDefs && key in inputDefs) {
                        componentRef.setInput(key, value);
                    }
                });
            }
            // Set popup reference (only if the component has this input)
            if (inputDefs && '__popup__' in inputDefs) {
                componentRef.setInput('__popup__', this.__popupRef__());
            }
            // Move component to container
            const hostElement = componentRef.location.nativeElement;
            this.contentContainerEl.nativeElement.appendChild(hostElement);
            // Subscribe to close event if available
            const instance = componentRef.instance;
            if (instance.onClosed) {
                instance.onClosed.subscribe((e) => {
                    this.close(e.data);
                });
            }
            this.handleContentRendered();
        }
    }
    /** @ignore */
    handleContentRendered() {
        this._zone.runOutsideAngular(() => {
            setTimeout(() => {
                const body = this.getHostElement().querySelector('.ax-popup-body-container');
                const content = body.children[0];
                if (!content || !body)
                    return;
                const popHeader = this.getHostElement().querySelector('.ax-popup-header-container');
                const popFooter = this.getHostElement().querySelector('.ax-popup-footer-container');
                const footer = content.querySelector(':scope > ax-footer');
                const header = content.querySelector(':scope > ax-header');
                if (footer && popFooter) {
                    popFooter.append(footer);
                }
                if (header && popHeader) {
                    popHeader.innerHTML = '';
                    popHeader.append(header);
                }
                this.focus();
            });
        });
        this.loadingService.hide(this._loadingId);
        this.cdr.markForCheck();
    }
    /** @ignore */
    onKeydownHandler() {
        const focusedOrHasFocused = this.getHostElement().matches(':focus-within');
        if (this.__config__()?.closeButton && focusedOrHasFocused) {
            this.close();
        }
    }
    /** @ignore */
    _handleCloseClick() {
        this.close();
    }
    /** @ignore */
    ngOnDestroy() {
        this.loadingService.hide(this._loadingId);
        if (this._componentRef) {
            this._componentRef.destroy();
            this._componentRef = null;
        }
    }
    /**
     * Sets focus on the `.ax-popup` element within the host element after a short delay.
     */
    focus() {
        setTimeout(() => this.getHostElement().querySelector('.ax-popup')?.focus());
    }
    /**
     * Closes the popup, emitting component reference, host element, and optional data.
     * @param {unknown} [data]
     */
    close(data) {
        const closeFn = () => {
            this.__popupRef__()?.close(data);
        };
        const componentInstance = this._componentRef?.instance;
        if (typeof componentInstance?.onClosing === 'function') {
            const ee = {
                cancel: false,
                data,
            };
            const closingResult = componentInstance.onClosing(ee);
            if (closingResult instanceof Promise) {
                closingResult.then(() => {
                    if (!ee.cancel) {
                        closeFn();
                    }
                });
            }
            else {
                if (!ee.cancel) {
                    closeFn();
                }
            }
        }
        else {
            closeFn();
        }
    }
    /**
     * Sets inputs on the content component.
     * @param values - Object containing input values to set
     */
    setContentInputs(values) {
        const componentRef = this._componentRef;
        if (componentRef) {
            Object.entries(values).forEach(([key, value]) => {
                componentRef.setInput(key, value);
            });
        }
    }
    /**
     * Sets the popup title.
     * @param title - The new title
     */
    setTitle(title) {
        this.title.set(title);
        this.cdr.markForCheck();
    }
    // Drag functionality
    onDragStart(event) {
        const config = this.__config__();
        if (!config?.draggable)
            return;
        this.isDragging.set(true);
        this.dragStartPos = { x: event.clientX, y: event.clientY };
        const popup = this.getHostElement().querySelector('.ax-popup');
        if (popup) {
            const rect = popup.getBoundingClientRect();
            this.elementStartPos = { x: rect.left, y: rect.top };
        }
        event.preventDefault();
    }
    onDragMove(event) {
        if (!this.isDragging())
            return;
        const deltaX = event.clientX - this.dragStartPos.x;
        const deltaY = event.clientY - this.dragStartPos.y;
        this.dragOffset.set({
            x: this.elementStartPos.x + deltaX,
            y: this.elementStartPos.y + deltaY,
        });
    }
    onDragEnd() {
        this.isDragging.set(false);
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.3", ngImport: i0, type: AXPopupComponent, deps: null, target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "20.3.3", type: AXPopupComponent, isStandalone: true, selector: "ax-popup", inputs: { __content__: { classPropertyName: "__content__", publicName: "__content__", isSignal: true, isRequired: false, transformFunction: null }, __config__: { classPropertyName: "__config__", publicName: "__config__", isSignal: true, isRequired: false, transformFunction: null }, __popupRef__: { classPropertyName: "__popupRef__", publicName: "__popupRef__", isSignal: true, isRequired: false, transformFunction: null }, __id__: { classPropertyName: "__id__", publicName: "__id__", isSignal: true, isRequired: false, transformFunction: null } }, host: { listeners: { "keydown.escape": "onKeydownHandler()", "document:mousemove": "onDragMove($event)", "document:mouseup": "onDragEnd()" } }, providers: [
            { provide: AXClosableComponent, useExisting: AXPopupComponent },
            { provide: AXComponent, useExisting: AXPopupComponent },
        ], viewQueries: [{ propertyName: "contentContainerRef", first: true, predicate: ["contentContainer"], descendants: true, read: ViewContainerRef, static: true }, { propertyName: "contentContainerEl", first: true, predicate: ["contentContainer"], descendants: true, static: true }], usesInheritance: true, ngImport: i0, template: "<div class=\"ax-popup-wrapper\" aria-modal=\"true\" axFocusTrap>\n  <div\n    class=\"ax-popup ax-popup-{{ __config__()?.size || 'md' }}\"\n    tabindex=\"0\"\n    [class.ax-popup-dragging]=\"isDragging()\"\n    [style.position]=\"dragOffset().x || dragOffset().y ? 'fixed' : null\"\n    [style.left.px]=\"dragOffset().x || null\"\n    [style.top.px]=\"dragOffset().y || null\"\n    [style.transform]=\"dragOffset().x || dragOffset().y ? 'none' : null\"\n  >\n    <div\n      class=\"ax-popup-header-container\"\n      [class.ax-popup-draggable]=\"__config__()?.draggable\"\n      (mousedown)=\"onDragStart($event)\"\n    >\n      @if (__config__()?.header) {\n        <div class=\"ax-popup-header\">\n          <span class=\"ax-popup-title\">{{ title() | translate | async }}</span>\n          @if (__config__()?.closeButton) {\n            <ax-close-button tabindex=\"1\" (click)=\"_handleCloseClick()\"></ax-close-button>\n          }\n        </div>\n      }\n    </div>\n    <div class=\"ax-popup-main-container ax-loading-container\">\n      <div class=\"ax-popup-body-container\" #contentContainer></div>\n      <div class=\"ax-popup-footer-container\"></div>\n    </div>\n  </div>\n</div>\n", styles: [":root{--ax-comp-popup-border-radius: var(--ax-sys-border-radius);--ax-comp-popup-border-color: var(--ax-sys-color-border-lightest-surface);--ax-comp-popup-body-bg-color: var(--ax-sys-color-lightest-surface);--ax-comp-popup-body-text-color: var(--ax-sys-color-on-lightest-surface);--ax-comp-popup-header-bg-color: var(--ax-sys-color-lighter-surface);--ax-comp-popup-header-border-color: var(--ax-sys-color-border-lighter-surface);--ax-comp-popup-footer-bg-color: var(--ax-sys-color-lighter-surface);--ax-comp-popup-footer-border-color: var(--ax-sys-color-border-lighter-surface)}.ax-popup-wrapper{display:contents}.ax-popup-header-container.ax-popup-draggable{cursor:move}.ax-popup.ax-popup-dragging{-webkit-user-select:none;user-select:none}.ax-popup{max-height:calc(var(--ax-overlay-full-width) * var(--ax-vh));margin-left:auto;margin-right:auto;display:flex;width:auto;flex-direction:column;overflow:hidden;border-radius:var(--ax-comp-popup-border-radius);border-width:1px;border-color:rgba(var(--ax-comp-popup-border-color));background-color:rgba(var(--ax-comp-popup-body-bg-color));padding:0;--ax-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--ax-shadow-colored: 0 10px 15px -3px var(--ax-shadow-color), 0 4px 6px -4px var(--ax-shadow-color);box-shadow:var(--ax-ring-offset-shadow, 0 0 rgba(0, 0, 0, 0)),var(--ax-ring-shadow, 0 0 rgba(0, 0, 0, 0)),var(--ax-shadow);outline:2px solid transparent;outline-offset:2px;color:rgba(var(--ax-comp-popup-body-text-color))}.ax-popup .ax-popup-header-container{background-color:rgba(var(--ax-comp-popup-header-bg-color))}.ax-popup .ax-popup-header-container .ax-popup-header{display:flex;align-items:center;justify-content:space-between;border-bottom-width:1px;border-color:rgba(var(--ax-comp-popup-header-border-color));padding:.75rem}.ax-popup .ax-popup-header-container .ax-popup-header .ax-popup-title{font-size:1rem;font-weight:500}@media (min-width: 768px){.ax-popup .ax-popup-header-container .ax-popup-header .ax-popup-title{font-size:1.125rem;line-height:1.75rem}}.ax-popup ax-footer{box-shadow:0 2px 10px #0000004d;display:flex;align-items:center;justify-content:space-between;border-top-width:1px;border-color:rgba(var(--ax-comp-popup-footer-border-color));background-color:rgba(var(--ax-comp-popup-footer-bg-color));padding:.75rem}.ax-popup:focus{outline:2px solid transparent;outline-offset:2px}.ax-popup:focus-visible{border-color:rgba(var(--ax-sys-color-primary-surface))}.ax-popup .ax-popup-main-container{display:flex;flex:1 1 0%;flex-direction:column;overflow:hidden}.ax-popup .ax-popup-main-container .ax-popup-body-container{flex:1 1 0%;overflow:auto;background-color:rgba(var(--ax-comp-popup-body-bg-color))}.ax-popup .ax-popup-main-container .ax-popup-footer-container{background-color:rgba(var(--ax-comp-popup-footer-bg-color))}.ax-popup.ax-popup-full{width:100vw;max-height:calc(100 * var(--ax-vh));height:calc(100 * var(--ax-vh));border-radius:0!important}.ax-popup.ax-fit{width:fit-content!important}.ax-popup.ax-fit .ax-popup-body-container{max-height:100vh}.ax-popup.ax-fit .ax-popup-body-container>ng-component>div{width:fit-content!important}@media (min-width: 320px) and (max-width: 640px){.ax-popup.ax-popup-sm,.ax-popup.ax-popup-md,.ax-popup.ax-popup-lg{width:93vw!important;height:fit-content;max-height:calc(var(--ax-overlay-full-width) * var(--ax-vh))!important}.ax-popup.ax-popup-sm .ax-popup-body-container>ng-component>div,.ax-popup.ax-popup-md .ax-popup-body-container>ng-component>div,.ax-popup.ax-popup-lg .ax-popup-body-container>ng-component>div{width:100%}}@media (min-width: 768px){.ax-popup.ax-popup-sm{width:55vw!important}.ax-popup.ax-popup-md{width:65vw!important}.ax-popup.ax-popup-lg{width:75vw!important}}@media (min-width: 1280px){.ax-popup.ax-popup-sm{width:30vw!important}.ax-popup.ax-popup-md{width:50vw!important}.ax-popup.ax-popup-lg{width:85vw!important}}@media (min-width: 1536px){.ax-popup.ax-popup-sm{width:25vw!important}.ax-popup.ax-popup-md{width:40vw!important}.ax-popup.ax-popup-lg{width:65vw!important}}.ax-dark .ax-popup{--ax-comp-popup-border-color: var(--ax-sys-color-border-darkest-surface);--ax-comp-popup-body-bg-color: var(--ax-sys-color-darker-surface);--ax-comp-popup-body-text-color: var(--ax-sys-color-on-darker-surface);--ax-comp-popup-header-bg-color: var(--ax-sys-color-dark-surface);--ax-comp-popup-header-border-color: var(--ax-sys-color-border-dark-surface);--ax-comp-popup-footer-bg-color: var(--ax-sys-color-dark-surface);--ax-comp-popup-footer-border-color: var(--ax-sys-color-border-dark-surface)}\n"], dependencies: [{ kind: "component", type: AXDecoratorCloseButtonComponent, selector: "ax-close-button", inputs: ["closeAll", "icon"] }, { kind: "directive", type: AXFocusTrapDirective, selector: "[axFocusTrap]" }, { kind: "pipe", type: AsyncPipe, name: "async" }, { kind: "pipe", type: AXTranslatorPipe, name: "translate" }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.3", ngImport: i0, type: AXPopupComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ax-popup', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, providers: [
                        { provide: AXClosableComponent, useExisting: AXPopupComponent },
                        { provide: AXComponent, useExisting: AXPopupComponent },
                    ], imports: [AXDecoratorCloseButtonComponent, AsyncPipe, AXTranslatorPipe, AXFocusTrapDirective], template: "<div class=\"ax-popup-wrapper\" aria-modal=\"true\" axFocusTrap>\n  <div\n    class=\"ax-popup ax-popup-{{ __config__()?.size || 'md' }}\"\n    tabindex=\"0\"\n    [class.ax-popup-dragging]=\"isDragging()\"\n    [style.position]=\"dragOffset().x || dragOffset().y ? 'fixed' : null\"\n    [style.left.px]=\"dragOffset().x || null\"\n    [style.top.px]=\"dragOffset().y || null\"\n    [style.transform]=\"dragOffset().x || dragOffset().y ? 'none' : null\"\n  >\n    <div\n      class=\"ax-popup-header-container\"\n      [class.ax-popup-draggable]=\"__config__()?.draggable\"\n      (mousedown)=\"onDragStart($event)\"\n    >\n      @if (__config__()?.header) {\n        <div class=\"ax-popup-header\">\n          <span class=\"ax-popup-title\">{{ title() | translate | async }}</span>\n          @if (__config__()?.closeButton) {\n            <ax-close-button tabindex=\"1\" (click)=\"_handleCloseClick()\"></ax-close-button>\n          }\n        </div>\n      }\n    </div>\n    <div class=\"ax-popup-main-container ax-loading-container\">\n      <div class=\"ax-popup-body-container\" #contentContainer></div>\n      <div class=\"ax-popup-footer-container\"></div>\n    </div>\n  </div>\n</div>\n", styles: [":root{--ax-comp-popup-border-radius: var(--ax-sys-border-radius);--ax-comp-popup-border-color: var(--ax-sys-color-border-lightest-surface);--ax-comp-popup-body-bg-color: var(--ax-sys-color-lightest-surface);--ax-comp-popup-body-text-color: var(--ax-sys-color-on-lightest-surface);--ax-comp-popup-header-bg-color: var(--ax-sys-color-lighter-surface);--ax-comp-popup-header-border-color: var(--ax-sys-color-border-lighter-surface);--ax-comp-popup-footer-bg-color: var(--ax-sys-color-lighter-surface);--ax-comp-popup-footer-border-color: var(--ax-sys-color-border-lighter-surface)}.ax-popup-wrapper{display:contents}.ax-popup-header-container.ax-popup-draggable{cursor:move}.ax-popup.ax-popup-dragging{-webkit-user-select:none;user-select:none}.ax-popup{max-height:calc(var(--ax-overlay-full-width) * var(--ax-vh));margin-left:auto;margin-right:auto;display:flex;width:auto;flex-direction:column;overflow:hidden;border-radius:var(--ax-comp-popup-border-radius);border-width:1px;border-color:rgba(var(--ax-comp-popup-border-color));background-color:rgba(var(--ax-comp-popup-body-bg-color));padding:0;--ax-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--ax-shadow-colored: 0 10px 15px -3px var(--ax-shadow-color), 0 4px 6px -4px var(--ax-shadow-color);box-shadow:var(--ax-ring-offset-shadow, 0 0 rgba(0, 0, 0, 0)),var(--ax-ring-shadow, 0 0 rgba(0, 0, 0, 0)),var(--ax-shadow);outline:2px solid transparent;outline-offset:2px;color:rgba(var(--ax-comp-popup-body-text-color))}.ax-popup .ax-popup-header-container{background-color:rgba(var(--ax-comp-popup-header-bg-color))}.ax-popup .ax-popup-header-container .ax-popup-header{display:flex;align-items:center;justify-content:space-between;border-bottom-width:1px;border-color:rgba(var(--ax-comp-popup-header-border-color));padding:.75rem}.ax-popup .ax-popup-header-container .ax-popup-header .ax-popup-title{font-size:1rem;font-weight:500}@media (min-width: 768px){.ax-popup .ax-popup-header-container .ax-popup-header .ax-popup-title{font-size:1.125rem;line-height:1.75rem}}.ax-popup ax-footer{box-shadow:0 2px 10px #0000004d;display:flex;align-items:center;justify-content:space-between;border-top-width:1px;border-color:rgba(var(--ax-comp-popup-footer-border-color));background-color:rgba(var(--ax-comp-popup-footer-bg-color));padding:.75rem}.ax-popup:focus{outline:2px solid transparent;outline-offset:2px}.ax-popup:focus-visible{border-color:rgba(var(--ax-sys-color-primary-surface))}.ax-popup .ax-popup-main-container{display:flex;flex:1 1 0%;flex-direction:column;overflow:hidden}.ax-popup .ax-popup-main-container .ax-popup-body-container{flex:1 1 0%;overflow:auto;background-color:rgba(var(--ax-comp-popup-body-bg-color))}.ax-popup .ax-popup-main-container .ax-popup-footer-container{background-color:rgba(var(--ax-comp-popup-footer-bg-color))}.ax-popup.ax-popup-full{width:100vw;max-height:calc(100 * var(--ax-vh));height:calc(100 * var(--ax-vh));border-radius:0!important}.ax-popup.ax-fit{width:fit-content!important}.ax-popup.ax-fit .ax-popup-body-container{max-height:100vh}.ax-popup.ax-fit .ax-popup-body-container>ng-component>div{width:fit-content!important}@media (min-width: 320px) and (max-width: 640px){.ax-popup.ax-popup-sm,.ax-popup.ax-popup-md,.ax-popup.ax-popup-lg{width:93vw!important;height:fit-content;max-height:calc(var(--ax-overlay-full-width) * var(--ax-vh))!important}.ax-popup.ax-popup-sm .ax-popup-body-container>ng-component>div,.ax-popup.ax-popup-md .ax-popup-body-container>ng-component>div,.ax-popup.ax-popup-lg .ax-popup-body-container>ng-component>div{width:100%}}@media (min-width: 768px){.ax-popup.ax-popup-sm{width:55vw!important}.ax-popup.ax-popup-md{width:65vw!important}.ax-popup.ax-popup-lg{width:75vw!important}}@media (min-width: 1280px){.ax-popup.ax-popup-sm{width:30vw!important}.ax-popup.ax-popup-md{width:50vw!important}.ax-popup.ax-popup-lg{width:85vw!important}}@media (min-width: 1536px){.ax-popup.ax-popup-sm{width:25vw!important}.ax-popup.ax-popup-md{width:40vw!important}.ax-popup.ax-popup-lg{width:65vw!important}}.ax-dark .ax-popup{--ax-comp-popup-border-color: var(--ax-sys-color-border-darkest-surface);--ax-comp-popup-body-bg-color: var(--ax-sys-color-darker-surface);--ax-comp-popup-body-text-color: var(--ax-sys-color-on-darker-surface);--ax-comp-popup-header-bg-color: var(--ax-sys-color-dark-surface);--ax-comp-popup-header-border-color: var(--ax-sys-color-border-dark-surface);--ax-comp-popup-footer-bg-color: var(--ax-sys-color-dark-surface);--ax-comp-popup-footer-border-color: var(--ax-sys-color-border-dark-surface)}\n"] }]
        }], propDecorators: { contentContainerRef: [{
                type: ViewChild,
                args: ['contentContainer', { read: ViewContainerRef, static: true }]
            }], contentContainerEl: [{
                type: ViewChild,
                args: ['contentContainer', { static: true }]
            }], onKeydownHandler: [{
                type: HostListener,
                args: ['keydown.escape']
            }], onDragMove: [{
                type: HostListener,
                args: ['document:mousemove', ['$event']]
            }], onDragEnd: [{
                type: HostListener,
                args: ['document:mouseup']
            }] } });

class AXPopupComponentBase {
    constructor() {
        this.__popup__ = input(...(ngDevMode ? [undefined, { debugName: "__popup__" }] : []));
    }
    close(data = null) {
        this.__popup__().close(data);
    }
    setTitle(title) {
        this.__popup__().setTitle(title);
    }
    bringToFront() {
        this.__popup__().bringToFront();
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.3", ngImport: i0, type: AXPopupComponentBase, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
    static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "20.3.3", type: AXPopupComponentBase, isStandalone: true, inputs: { __popup__: { classPropertyName: "__popup__", publicName: "__popup__", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.3", ngImport: i0, type: AXPopupComponentBase, decorators: [{
            type: Directive
        }] });

/**
 * This is a service which you can create popup with it
 *
 * @category Components
 */
class AXPopupService {
    constructor() {
        this.popupList = new Map();
        this.overlayService = inject(AXOverlayService);
    }
    /**
     *  @ignore
     */
    open(arg1, arg2) {
        let config = {
            closeButton: true,
            header: true,
            size: 'md',
            maximizable: false,
            draggable: true,
            hasBackdrop: true,
            closeOnBackdropClick: false,
            data: {},
        };
        if (typeof arg2 === 'string') {
            config.title = arg2;
        }
        else {
            config = Object.assign(config, arg2);
        }
        const promise = new AXComponentClosedPromise((resolve) => {
            this.openInternal(arg1, config).then((ref) => {
                ref.onClose.subscribe((data) => {
                    if (resolve) {
                        resolve({
                            sender: ref.componentInstance,
                            data: data,
                        });
                    }
                });
            });
        });
        return promise;
    }
    /**
     * Opens a popup with the specified content and configuration.
     * @param content - Component or template to display
     * @param config - Configuration options for the popup
     * @returns Promise<AXPopupRef> - Reference to the opened popup
     */
    async openInternal(content, config) {
        const randomId = Math.floor(Math.random() * 100000000000);
        const onClose = new Subject();
        const returnRef = {
            close: (data) => {
                this.close(randomId, data);
            },
            setInputs: (values) => {
                this.setInputs(randomId, values);
            },
            setTitle: (title) => {
                this.setTitle(randomId, title);
            },
            bringToFront: () => {
                this.bringToFront(randomId);
            },
            onClose,
        };
        // Build panel classes
        const panelClasses = ['ax-popup-overlay'];
        if (config.panelClass) {
            panelClasses.push(...config.panelClass);
        }
        const ref = await this.overlayService.create(AXPopupComponent, {
            backdrop: {
                enabled: config.hasBackdrop ?? true,
                background: true,
                closeOnClick: config.closeOnBackdropClick ?? false,
            },
            panelClass: panelClasses,
            inputs: {
                __content__: content,
                __config__: config,
                __popupRef__: returnRef,
                __id__: randomId,
            },
        });
        this.popupList.set(randomId, { overlay: ref, popup: returnRef });
        return returnRef;
    }
    /**
     * Closes a popup by its ID.
     * @param id - The popup ID to close
     * @param data - Optional data to pass to the close event
     */
    close(id, data) {
        const ref = this.popupList.get(id);
        if (!ref)
            return;
        ref.popup.onClose.next(data);
        ref.popup.onClose.complete();
        ref.overlay.dispose();
        this.popupList.delete(id);
    }
    /**
     * Sets input values for a popup by its ID.
     * @param id - The popup ID
     * @param values - Object containing input values to set
     */
    setInputs(id, values) {
        const ref = this.popupList.get(id)?.overlay.instance;
        if (!ref)
            return;
        if (ref instanceof ComponentRef) {
            const componentInstance = ref.instance;
            componentInstance.setContentInputs(values);
        }
    }
    /**
     * Sets the title for a popup by its ID.
     * @param id - The popup ID
     * @param title - The new title
     */
    setTitle(id, title) {
        const ref = this.popupList.get(id)?.overlay.instance;
        if (!ref)
            return;
        if (ref instanceof ComponentRef) {
            const componentInstance = ref.instance;
            componentInstance.setTitle(title);
        }
    }
    /**
     * Brings a popup to the front of all other overlays.
     * @param id - The popup ID to bring to front
     */
    bringToFront(id) {
        const ref = this.popupList.get(id);
        if (!ref)
            return;
        ref.overlay.bringToFront();
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.3", ngImport: i0, type: AXPopupService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.3", ngImport: i0, type: AXPopupService, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.3", ngImport: i0, type: AXPopupService, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root',
                }]
        }] });

const COMPONENT = [AXPopupComponent];
const MODULES = [CommonModule, AXCommonModule, AXDecoratorModule, AXTranslationModule];
class AXPopupModule {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.3", ngImport: i0, type: AXPopupModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "20.3.3", ngImport: i0, type: AXPopupModule, imports: [CommonModule, AXCommonModule, AXDecoratorModule, AXTranslationModule, AXPopupComponent], exports: [AXPopupComponent] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "20.3.3", ngImport: i0, type: AXPopupModule, providers: [AXPopupService], imports: [MODULES, COMPONENT] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.3", ngImport: i0, type: AXPopupModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [...MODULES, ...COMPONENT],
                    exports: [...COMPONENT],
                    providers: [AXPopupService],
                }]
        }] });

/**
 * Generated bundle index. Do not edit.
 */

export { AXPopupComponent, AXPopupComponentBase, AXPopupModule, AXPopupService };
//# sourceMappingURL=acorex-components-popup.mjs.map
