import { AXPlatform } from '@acorex/core/platform';
import { TemplatePortal, ComponentPortal, CdkPortalOutlet, PortalModule } from '@angular/cdk/portal';
import * as i0 from '@angular/core';
import { inject, NgZone, ViewContainerRef, TemplateRef, HostListener, ViewEncapsulation, ChangeDetectionStrategy, Component, Injectable, NgModule } from '@angular/core';
import { MXBaseComponent, AXClosableComponent, AXComponent, AXComponentClosedPromise, AXCommonModule } from '@acorex/cdk/common';
import { AXDecoratorCloseButtonComponent, AXDecoratorModule } from '@acorex/components/decorators';
import { AXLoadingService } from '@acorex/components/loading';
import { AXTranslatorPipe, AXTranslationModule } from '@acorex/core/translation';
import { CdkTrapFocus, A11yModule } from '@angular/cdk/a11y';
import { DIALOG_DATA, DialogRef, Dialog, DialogModule } from '@angular/cdk/dialog';
import { CdkDrag, CdkDragHandle, DragDropModule } from '@angular/cdk/drag-drop';
import { AsyncPipe, CommonModule } from '@angular/common';
import { AXHtmlUtil } from '@acorex/core/utils';

/**
 * The Button is a component which detects user interaction and triggers a corresponding event
 *
 * @category Components
 */
class AXPopupComponent extends MXBaseComponent {
    constructor() {
        super(...arguments);
        this._zone = inject(NgZone);
        this._viewContainerRef = inject(ViewContainerRef);
        this.loadingService = inject(AXLoadingService);
        this._platform = inject(AXPlatform);
        this.data = inject(DIALOG_DATA);
        this.dialogRef = inject(DialogRef);
        /**
         * Indicates whether the component is loading.
         * @defaultValue true
         */
        this.isLoading = true;
    }
    /** @ignore */
    ngOnInit() {
        super.ngOnInit();
        if (this._platform.is('SM')) {
            this.data.draggable = false;
        }
        this._loadingId = this.loadingService.show({
            location: this.getHostElement(),
        });
        //
        if (this.data.content instanceof TemplateRef) {
            this._selectedPortal = new TemplatePortal(this.data.content, this._viewContainerRef, {
                $implicit: this.data,
                ref: this,
            });
            this.cdr.markForCheck();
        }
        else if (typeof this.data.content === 'function') {
            this._selectedPortal = new ComponentPortal(this.data.content);
            this.cdr.markForCheck();
        }
    }
    /** @ignore */
    _handleAttched(ref) {
        ref = ref;
        if (ref.instance) {
            this._componentRef = ref.instance;
            Object.assign(this._componentRef, this.data.data);
            Object.assign(this._componentRef, { _isPopup: true });
            Object.assign(this._componentRef, {
                setTitle: (title) => {
                    this.data.title = title;
                },
            });
            if (ref.instance.onClosed) {
                ref.instance.onClosed.subscribe((e) => {
                    this.close(e.data);
                });
            }
        }
        this._zone.runOutsideAngular(() => {
            setTimeout(() => {
                const body = this.getHostElement().querySelector('.ax-popup-body-container');
                const content = body.children[0];
                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?.append(footer);
                }
                if (header) {
                    popHeader.innerHTML = '';
                    popHeader.append(header);
                }
                this.focus();
            });
        });
        this.loadingService.hide(this._loadingId);
        this.cdr.markForCheck();
    }
    /** @ignore */
    onKeydownHandler(event) {
        const focusedOrHasFocused = this.getHostElement().matches(':focus-within');
        if (this.data.closeButton && focusedOrHasFocused) {
            this.close();
        }
    }
    /** @ignore */
    _handleCloseClick() {
        this.close();
    }
    /** @ignore */
    ngOnDestroy() {
        this.loadingService.hide(this._loadingId);
    }
    /**
     * 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 dialog, emitting component reference, host element, and optional data.
     * @param {unknown} [data]
     */
    close(data) {
        const closeFn = () => {
            this.dialogRef.close({
                component: this._componentRef,
                htmlElement: this.getHostElement(),
                data: data,
            });
        };
        if (typeof this._componentRef?.onClosing === 'function') {
            const ee = {
                cancel: false,
                data,
            };
            const closingResult = this._componentRef?.onClosing(ee);
            if (closingResult instanceof Promise) {
                closingResult.then(() => {
                    if (!ee.cancel) {
                        closeFn();
                    }
                });
            }
            else {
                if (!ee.cancel) {
                    closeFn();
                }
            }
        }
        else {
            closeFn();
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: AXPopupComponent, deps: null, target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "20.3.9", type: AXPopupComponent, isStandalone: true, selector: "ax-popup", host: { listeners: { "keydown.escape": "onKeydownHandler($event)" } }, providers: [
            { provide: AXClosableComponent, useExisting: AXPopupComponent },
            { provide: AXComponent, useExisting: AXPopupComponent },
        ], usesInheritance: true, ngImport: i0, template: "<div class=\"ax-popup-wrapper\" aria-modal=\"true\" [cdkTrapFocus]=\"true\">\n  <div class=\"ax-popup ax-popup-{{ data.size }}\" tabindex=\"0\" cdkDrag [cdkDragDisabled]=\"!data.draggable\">\n    <div cdkDragHandle class=\"ax-popup-header-container\">\n      @if (data.header) {\n        <div class=\"ax-popup-header\">\n          <span class=\"ax-popup-title\">{{ data.title | translate | async }}</span>\n          @if (data.closeButton) {\n            <ax-close-button tabindex=\"1\"></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\">\n        <ng-template [cdkPortalOutlet]=\"_selectedPortal\" (attached)=\"_handleAttched($event)\"></ng-template>\n      </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{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: "directive", type: CdkTrapFocus, selector: "[cdkTrapFocus]", inputs: ["cdkTrapFocus", "cdkTrapFocusAutoCapture"], exportAs: ["cdkTrapFocus"] }, { kind: "directive", type: CdkDrag, selector: "[cdkDrag]", inputs: ["cdkDragData", "cdkDragLockAxis", "cdkDragRootElement", "cdkDragBoundary", "cdkDragStartDelay", "cdkDragFreeDragPosition", "cdkDragDisabled", "cdkDragConstrainPosition", "cdkDragPreviewClass", "cdkDragPreviewContainer", "cdkDragScale"], outputs: ["cdkDragStarted", "cdkDragReleased", "cdkDragEnded", "cdkDragEntered", "cdkDragExited", "cdkDragDropped", "cdkDragMoved"], exportAs: ["cdkDrag"] }, { kind: "directive", type: CdkDragHandle, selector: "[cdkDragHandle]", inputs: ["cdkDragHandleDisabled"] }, { kind: "component", type: AXDecoratorCloseButtonComponent, selector: "ax-close-button", inputs: ["closeAll", "icon"] }, { kind: "directive", type: CdkPortalOutlet, selector: "[cdkPortalOutlet]", inputs: ["cdkPortalOutlet"], outputs: ["attached"], exportAs: ["cdkPortalOutlet"] }, { 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.9", 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: [
                        CdkTrapFocus,
                        CdkDrag,
                        CdkDragHandle,
                        AXDecoratorCloseButtonComponent,
                        CdkPortalOutlet,
                        AsyncPipe,
                        AXTranslatorPipe,
                    ], template: "<div class=\"ax-popup-wrapper\" aria-modal=\"true\" [cdkTrapFocus]=\"true\">\n  <div class=\"ax-popup ax-popup-{{ data.size }}\" tabindex=\"0\" cdkDrag [cdkDragDisabled]=\"!data.draggable\">\n    <div cdkDragHandle class=\"ax-popup-header-container\">\n      @if (data.header) {\n        <div class=\"ax-popup-header\">\n          <span class=\"ax-popup-title\">{{ data.title | translate | async }}</span>\n          @if (data.closeButton) {\n            <ax-close-button tabindex=\"1\"></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\">\n        <ng-template [cdkPortalOutlet]=\"_selectedPortal\" (attached)=\"_handleAttched($event)\"></ng-template>\n      </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{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: { onKeydownHandler: [{
                type: HostListener,
                args: ['keydown.escape', ['$event']]
            }] } });

/**
 * This is a service which you can create popup with it
 *
 * @category Components
 */
class AXPopupService {
    constructor() {
        this.dialog = inject(Dialog);
        this.#platform = inject(AXPlatform);
    }
    #platform;
    /**
     *  @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 dialogRef = this.dialog.open(AXPopupComponent, {
            data: Object.assign(config, { content: arg1 }),
            autoFocus: true,
            restoreFocus: true,
            closeOnNavigation: true,
            closeOnDestroy: true,
            hasBackdrop: config.hasBackdrop,
            backdropClass: config.backdropClass,
            disableClose: config.closeOnBackdropClick ? false : true,
            viewContainerRef: config.viewContainerRef,
            providers: config.providers,
            panelClass: config.panelClass ? config.panelClass : [this.#platform.isDark() ? 'ax-dark' : ''],
            direction: config.direction ? config.direction : AXHtmlUtil.isRtl() ? 'rtl' : 'ltr',
        });
        const promise = new AXComponentClosedPromise((resolve) => {
            dialogRef.closed.subscribe((d) => {
                if (resolve) {
                    resolve({
                        sender: d?.component,
                        data: d?.data,
                    });
                }
            });
        });
        return promise;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: AXPopupService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: AXPopupService }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.9", ngImport: i0, type: AXPopupService, decorators: [{
            type: Injectable
        }] });

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

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

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