import * as i0 from '@angular/core';
import { inject, ElementRef, input, HostListener, Directive, ViewContainerRef, signal } from '@angular/core';
import { Overlay, OverlayPositionBuilder } from '@angular/cdk/overlay';
import { TemplatePortal } from '@angular/cdk/portal';
import { take, filter } from 'rxjs/operators';

/**
 * Generic directive that turns any element into a trigger for a dropdown component
 * implementing the DropdownOverlay interface.
 * Handles click and keyboard interactions to open/close the dropdown.
 */
class DropdownTriggerDirective {
    elementRef = inject((ElementRef));
    /** Reference to the dropdown component that this trigger controls */
    apDropdownTrigger = input.required(...(ngDevMode ? [{ debugName: "apDropdownTrigger" }] : /* istanbul ignore next */ []));
    /** Handles click events to toggle the dropdown */
    onClick(event) {
        event.preventDefault();
        event.stopPropagation();
        this.apDropdownTrigger().toggle(this.elementRef.nativeElement);
    }
    /** Handles keyboard events for accessibility (Enter, Space, Arrow Down, Escape) */
    onKeyDown(event) {
        const dropdown = this.apDropdownTrigger();
        switch (event.key) {
            case 'Enter':
            case ' ':
            case 'ArrowDown':
                event.preventDefault();
                dropdown.open(this.elementRef.nativeElement);
                break;
            case 'Escape':
                event.preventDefault();
                dropdown.close();
                break;
        }
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.16", ngImport: i0, type: DropdownTriggerDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
    static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "21.2.16", type: DropdownTriggerDirective, isStandalone: true, selector: "[apDropdownTrigger]", inputs: { apDropdownTrigger: { classPropertyName: "apDropdownTrigger", publicName: "apDropdownTrigger", isSignal: true, isRequired: true, transformFunction: null } }, host: { listeners: { "click": "onClick($event)", "keydown": "onKeyDown($event)" } }, ngImport: i0 });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.16", ngImport: i0, type: DropdownTriggerDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: '[apDropdownTrigger]',
                }]
        }], propDecorators: { apDropdownTrigger: [{ type: i0.Input, args: [{ isSignal: true, alias: "apDropdownTrigger", required: true }] }], onClick: [{
                type: HostListener,
                args: ['click', ['$event']]
            }], onKeyDown: [{
                type: HostListener,
                args: ['keydown', ['$event']]
            }] } });

/**
 * Creates a composable dropdown overlay helper that manages CDK overlay creation,
 * positioning, and disposal. Must be called within an Angular injection context
 * (e.g., in a component constructor or field initializer).
 */
function createDropdownOverlay() {
    const elementRef = inject(ElementRef);
    const overlay = inject(Overlay);
    const positionBuilder = inject(OverlayPositionBuilder);
    const viewContainerRef = inject(ViewContainerRef);
    let _overlayRef = null;
    let portal = null;
    const isOpen = signal(false, ...(ngDevMode ? [{ debugName: "isOpen" }] : /* istanbul ignore next */ []));
    function open(template, triggerElement, config) {
        if (isOpen())
            return;
        const target = triggerElement ?? elementRef.nativeElement;
        if (_overlayRef) {
            _overlayRef.dispose();
        }
        const positionStrategy = buildPositionStrategy(target, config?.defaultPosition ?? 'right');
        _overlayRef = overlay.create({
            positionStrategy,
            hasBackdrop: config?.showBackdrop ?? true,
            backdropClass: '',
            panelClass: '',
            scrollStrategy: overlay.scrollStrategies.reposition(),
        });
        portal = new TemplatePortal(template, viewContainerRef);
        _overlayRef.attach(portal);
        isOpen.set(true);
        const closeHandler = config?.onClose ?? (() => close());
        _overlayRef
            .backdropClick()
            .pipe(take(1))
            .subscribe(() => closeHandler());
        _overlayRef
            .keydownEvents()
            .pipe(filter((event) => event.key === 'Escape'), take(1))
            .subscribe(() => closeHandler());
    }
    function close() {
        if (!isOpen())
            return;
        if (_overlayRef) {
            _overlayRef.dispose();
            _overlayRef = null;
        }
        portal = null;
        isOpen.set(false);
    }
    function buildPositionStrategy(target, defaultPosition) {
        const gap = 4;
        const positions = defaultPosition === 'right'
            ? [
                {
                    originX: 'start',
                    originY: 'bottom',
                    overlayX: 'start',
                    overlayY: 'top',
                    offsetX: 0,
                    offsetY: gap,
                },
                {
                    originX: 'end',
                    originY: 'bottom',
                    overlayX: 'end',
                    overlayY: 'top',
                    offsetX: 0,
                    offsetY: gap,
                },
                {
                    originX: 'start',
                    originY: 'top',
                    overlayX: 'start',
                    overlayY: 'bottom',
                    offsetX: 0,
                    offsetY: -gap,
                },
                {
                    originX: 'end',
                    originY: 'top',
                    overlayX: 'end',
                    overlayY: 'bottom',
                    offsetX: 0,
                    offsetY: -gap,
                },
            ]
            : [
                {
                    originX: 'end',
                    originY: 'bottom',
                    overlayX: 'end',
                    overlayY: 'top',
                    offsetX: 0,
                    offsetY: gap,
                },
                {
                    originX: 'start',
                    originY: 'bottom',
                    overlayX: 'start',
                    overlayY: 'top',
                    offsetX: 0,
                    offsetY: gap,
                },
                {
                    originX: 'end',
                    originY: 'top',
                    overlayX: 'end',
                    overlayY: 'bottom',
                    offsetX: 0,
                    offsetY: -gap,
                },
                {
                    originX: 'start',
                    originY: 'top',
                    overlayX: 'start',
                    overlayY: 'bottom',
                    offsetX: 0,
                    offsetY: -gap,
                },
            ];
        return positionBuilder
            .flexibleConnectedTo(target)
            .withPositions(positions)
            .withFlexibleDimensions(true)
            .withPush(true)
            .withGrowAfterOpen(true)
            .withViewportMargin(8);
    }
    return {
        get overlayRef() {
            return _overlayRef;
        },
        isOpen: isOpen.asReadonly(),
        open,
        close,
    };
}

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

export { DropdownTriggerDirective, createDropdownOverlay };
//# sourceMappingURL=agorapulse-ui-components-dropdown-base.mjs.map
