"use client";
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from "react";
import * as PopoverPrimitive from "@radix-ui/react-popover";
import { cn } from "../../lib/utils";
// Custom hook to handle iframe and document interactions for closing popovers
function addIframeWindowFocusListener(iframe, listener) {
    try {
        const iframeWindow = iframe.contentWindow;
        iframeWindow?.addEventListener("focus", listener, true);
        return () => {
            try {
                iframeWindow?.removeEventListener("focus", listener, true);
            }
            catch { }
        };
    }
    catch {
        return undefined;
    }
}
function useIframeClickDetection(isOpen, onShouldClose) {
    React.useEffect(() => {
        if (!isOpen)
            return;
        const handleDocumentInteraction = () => {
            onShouldClose();
        };
        const handleIframeInteraction = (event) => {
            // Delay to ensure this happens after popover state updates
            setTimeout(onShouldClose, 50);
        };
        // Listen for iframe focus events which indicate user clicked in iframe
        // Only target iframes with the class "page-iframe"
        const iframes = document.querySelectorAll("iframe.page-iframe");
        const cleanupIframeWindowListeners = [];
        iframes.forEach((iframe) => {
            // Use capture phase to catch events before they're handled
            const iframeElement = iframe;
            iframe.addEventListener("mousedown", handleIframeInteraction, true);
            const cleanupIframeWindowListener = addIframeWindowFocusListener(iframeElement, handleIframeInteraction);
            if (cleanupIframeWindowListener) {
                cleanupIframeWindowListeners.push(cleanupIframeWindowListener);
            }
        });
        // Also listen for window blur which can indicate focus moved to iframe
        window.addEventListener("blur", handleDocumentInteraction);
        return () => {
            window.removeEventListener("blur", handleDocumentInteraction);
            iframes.forEach((iframe) => {
                iframe.removeEventListener("mousedown", handleIframeInteraction, true);
            });
            cleanupIframeWindowListeners.forEach((cleanup) => cleanup());
        };
    }, [isOpen, onShouldClose]);
}
const PopoverRoot = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
export function syncClosedPopperWrapperPointerEvents(content, interactivePointerEvents = "") {
    const wrapper = content.parentElement;
    if (!wrapper?.hasAttribute("data-radix-popper-content-wrapper"))
        return;
    if (content.getAttribute("data-state") === "closed") {
        wrapper.style.pointerEvents = "none";
    }
    else if (interactivePointerEvents) {
        wrapper.style.pointerEvents = interactivePointerEvents;
    }
    else {
        wrapper.style.removeProperty("pointer-events");
    }
}
function assignReactRef(ref, value) {
    if (typeof ref === "function") {
        ref(value);
    }
    else if (ref) {
        ref.current = value;
    }
}
export function useNonInteractiveClosedPopperWrapper(forwardedRef) {
    const cleanupRef = React.useRef(undefined);
    return React.useCallback((content) => {
        cleanupRef.current?.();
        cleanupRef.current = undefined;
        assignReactRef(forwardedRef, content);
        if (!content)
            return;
        const wrapper = content?.parentElement;
        if (!content ||
            !wrapper?.hasAttribute("data-radix-popper-content-wrapper")) {
            return;
        }
        const interactivePointerEvents = wrapper.style.pointerEvents;
        // Radix keeps its positioning wrapper mounted while the content's exit
        // animation runs. The content itself disables pointer events when closed,
        // but the generated wrapper otherwise continues to cover controls beneath
        // it. Mirror the content state onto that wrapper for the whole animation.
        const syncPointerEvents = () => syncClosedPopperWrapperPointerEvents(content, interactivePointerEvents);
        syncPointerEvents();
        const observer = new MutationObserver(syncPointerEvents);
        observer.observe(content, {
            attributes: true,
            attributeFilter: ["data-state"],
        });
        cleanupRef.current = () => {
            observer.disconnect();
            if (interactivePointerEvents) {
                wrapper.style.pointerEvents = interactivePointerEvents;
            }
            else {
                wrapper.style.removeProperty("pointer-events");
            }
        };
    }, [forwardedRef]);
}
// Enhanced Popover component with iframe click detection
const Popover = ({ enableIframeClickDetection = true, ...props }) => {
    const [internalOpen, setInternalOpen] = React.useState(false);
    const isControlled = props.open !== undefined;
    const isOpen = isControlled ? props.open : internalOpen;
    const handleOpenChange = React.useCallback((open) => {
        if (isControlled) {
            props.onOpenChange?.(open);
        }
        else {
            setInternalOpen(open);
        }
    }, [isControlled, props.onOpenChange]);
    // Use iframe click detection if enabled
    useIframeClickDetection(Boolean(enableIframeClickDetection && isOpen), () => handleOpenChange(false));
    return (_jsx(PopoverRoot, { ...props, open: isOpen, onOpenChange: handleOpenChange }));
};
Popover.displayName = "Popover";
const PopoverContent = React.forwardRef(({ className, align = "center", sideOffset = 4, container, ...props }, ref) => {
    const contentRef = useNonInteractiveClosedPopperWrapper(ref);
    return (_jsx(PopoverPrimitive.Portal, { container: container, children: _jsx(PopoverPrimitive.Content, { ref: contentRef, align: align, sideOffset: sideOffset, "data-slot": "popover-content", className: cn("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-250 w-72 rounded-md border p-4 shadow-md outline-none data-[state=closed]:pointer-events-none", className), ...props }) }));
});
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
function PopoverAnchor({ ...props }) {
    return _jsx(PopoverPrimitive.Anchor, { "data-slot": "popover-anchor", ...props });
}
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };
//# sourceMappingURL=popover.js.map