import { jsx } from 'react/jsx-runtime';
import React__default, { useRef, useEffect, useCallback, useState } from 'react';
import { useReducedMotion, AnimatePresence, motion } from 'motion/react';
import { createPortal } from 'react-dom';
import { cn } from '../../../utils/cn.js';
import { usePopoverContext } from './PopoverContext.js';
import { useClickOutside } from '../../../hooks/useClickOutside.js';
import { popoverTransitions, popoverContentVariants } from './Popover.animations.js';
import { useSelectPortal } from '../../../hooks/useSelectPortal.js';
import { Overlay } from '../../effects/Overlay/Overlay.js';
import { useIsClient } from '../../../hooks/useIsClient.js';

/** Overlay backdrop animations (fade in/out) */
const overlayBackdropAnimations = {
    initial: { opacity: 0 },
    animate: { opacity: 1, transition: { duration: 0.15 } },
    exit: { opacity: 0, transition: { duration: 0.1 } },
};
/** Overlay content animations (scale + fade) */
const overlayContentAnimations = {
    initial: { opacity: 0, scale: 0.95 },
    animate: { opacity: 1, scale: 1, transition: { duration: 0.2 } },
    exit: { opacity: 0, scale: 0.95, transition: { duration: 0.15 } },
};
const useDarkMode = () => {
    const [isDark, setIsDark] = useState(false);
    useEffect(() => {
        if (typeof document === "undefined")
            return;
        const checkDarkMode = () => {
            const hasDarkClass = document.documentElement.classList.contains("dark") ||
                document.body.classList.contains("dark") ||
                document.querySelector(".dark") !== null;
            setIsDark(hasDarkClass);
        };
        checkDarkMode();
        const observer = new MutationObserver(checkDarkMode);
        observer.observe(document.documentElement, {
            attributes: true,
            attributeFilter: ["class"],
        });
        observer.observe(document.body, {
            attributes: true,
            attributeFilter: ["class"],
        });
        return () => observer.disconnect();
    }, []);
    return isDark;
};
/**
 * PopoverBody component displays the body/content of the popover
 */
const PopoverBody = React__default.forwardRef(({ children, className, animation = true, portal = true, scrollable = false, maxHeight, ...props }, ref) => {
    const { isOpen, onOpenChange, triggerRef, contentRef, placement, offset, triggerType, closeOnClickOutside, closeOnEsc, preventClose, hasBackdrop, theme, contentId, } = usePopoverContext();
    const shouldReduceMotion = useReducedMotion();
    const localRef = useRef(null);
    // Use the same positioning hook as Select/Tooltip (now supports all 12 placements)
    const { position, cssVariables, contentRef: portalContentRef, } = useSelectPortal({
        triggerRef,
        isOpen: isOpen || false,
        placement,
        offset: offset || 8,
        autoWidth: true,
        onClose: () => {
            if (!preventClose)
                onOpenChange(false);
        },
        stickyTracking: true,
    });
    // Click outside detection (active when no backdrop — with backdrop, Overlay handles it)
    useClickOutside(localRef, (e) => {
        var _a;
        if (hasBackdrop)
            return; // Overlay handles click-outside via backdrop
        if (e.target === triggerRef.current ||
            ((_a = triggerRef.current) === null || _a === void 0 ? void 0 : _a.contains(e.target))) {
            return;
        }
        if (closeOnClickOutside && !preventClose) {
            onOpenChange(false);
        }
    });
    // Escape key handling (active when no backdrop — with backdrop, Overlay handles it)
    useEffect(() => {
        if (hasBackdrop)
            return; // Overlay handles escape key
        const handleKeyDown = (e) => {
            if (closeOnEsc && e.key === "Escape" && !preventClose) {
                onOpenChange(false);
            }
        };
        document.addEventListener("keydown", handleKeyDown);
        return () => {
            document.removeEventListener("keydown", handleKeyDown);
        };
    }, [hasBackdrop, closeOnEsc, onOpenChange, preventClose]);
    // Combine refs
    const handleRef = useCallback((el) => {
        localRef.current = el;
        if (typeof ref === "function") {
            ref(el);
        }
        else if (ref) {
            ref.current = el;
        }
        if (contentRef) {
            contentRef.current = el;
        }
        if (portalContentRef &&
            typeof portalContentRef === "object" &&
            "current" in portalContentRef) {
            portalContentRef.current =
                el;
        }
    }, [ref, contentRef, portalContentRef]);
    const isDarkMode = useDarkMode();
    const isClient = useIsClient();
    // Extract DOM props to avoid type conflicts with Framer Motion
    const { onDrag, onDragStart, onDragEnd, onAnimationStart, onAnimationEnd, ...domProps } = props;
    const contentClasses = cn(theme.baseStyle, theme.bodyStyle, "popover-content", scrollable && "overflow-y-auto", className);
    const contentPositionStyle = {
        ...cssVariables,
        position: "fixed",
        top: `${position.top}px`,
        left: `${position.left}px`,
        ...(scrollable && {
            maxHeight: maxHeight || "var(--select-content-available-height, 400px)",
        }),
    };
    // When hasBackdrop is true, delegate backdrop + escape + click-outside to Overlay
    if (hasBackdrop) {
        return (jsx(Overlay, { ref: handleRef, isOpen: isOpen, onClose: () => {
                if (!preventClose)
                    onOpenChange(false);
            }, closeOnOverlayClick: closeOnClickOutside && !preventClose, closeOnEsc: closeOnEsc && !preventClose, enableScrollLock: false, enableFocusTrap: true, position: "none", role: "dialog", ariaModal: true, contentClassName: contentClasses, contentStyle: contentPositionStyle, animations: animation && !shouldReduceMotion
                ? {
                    overlay: overlayBackdropAnimations,
                    content: overlayContentAnimations,
                }
                : undefined, children: jsx("div", { id: contentId, "data-state": isOpen ? "open" : "closed", "data-placement": placement, "data-trigger": triggerType, ...domProps, children: children }) }));
    }
    // Without backdrop: manual portal + positioning + escape + click-outside
    const popoverContent = (jsx(AnimatePresence, { children: isOpen && (jsx(motion.div, { ref: handleRef, id: contentId, className: cn("fixed z-50", contentClasses), style: contentPositionStyle, role: "dialog", "aria-modal": "true", variants: shouldReduceMotion || !animation ? {} : popoverContentVariants, initial: shouldReduceMotion || !animation ? undefined : "hidden", animate: shouldReduceMotion || !animation ? undefined : "visible", exit: shouldReduceMotion || !animation ? undefined : "exit", transition: shouldReduceMotion || !animation
                ? { duration: 0 }
                : popoverTransitions.content, "data-state": isOpen ? "open" : "closed", "data-placement": placement, "data-trigger": triggerType, onClick: (e) => e.stopPropagation(), ...domProps, children: children })) }));
    if (portal && isClient) {
        return createPortal(jsx("div", { className: isDarkMode ? "dark" : undefined, children: popoverContent }), document.body);
    }
    return popoverContent;
});
PopoverBody.displayName = "Popover.Body";

export { PopoverBody };
