import { jsx } from 'react/jsx-runtime';
import { useId, useState, useRef, useCallback } from 'react';
import { cn } from '../../../utils/cn.js';
import { PopoverContext } from './PopoverContext.js';
import { PopoverTrigger } from './PopoverTrigger.js';
import { PopoverBody } from './PopoverBody.js';
import { popoverTheme } from './Popover.theme.js';

/**
 * Popover component using compound component pattern
 *
 * @component
 * @example
 * ```tsx
 * <Popover>
 *   <Popover.Trigger>
 *     <Button>Open Popover</Button>
 *   </Popover.Trigger>
 *   <Popover.Body>
 *     <div>Popover content</div>
 *   </Popover.Body>
 * </Popover>
 * ```
 */
const PopoverRoot = ({ children, className, isOpen: controlledIsOpen, defaultIsOpen = false, onOpenChange, placement = "bottom", offset = 8, triggerType = "click", closeOnClickOutside = true, closeOnEsc = true, preventClose = false, hasBackdrop = false, theme: themeOverrides, darkMode = false, ...props }) => {
    // Generate unique ID for content linkage
    const contentId = `${useId()}-popover-content`;
    // State for uncontrolled mode
    const [uncontrolledIsOpen, setUncontrolledIsOpen] = useState(defaultIsOpen);
    // Determine if controlled or uncontrolled
    const isControlled = controlledIsOpen !== undefined;
    const isOpen = isControlled ? controlledIsOpen : uncontrolledIsOpen;
    // Refs for positioning
    const triggerRef = useRef(null);
    const contentRef = useRef(null);
    // Handle open state changes
    const handleOpenChange = useCallback((value) => {
        if (!isControlled) {
            setUncontrolledIsOpen(value);
        }
        onOpenChange === null || onOpenChange === void 0 ? void 0 : onOpenChange(value);
    }, [isControlled, onOpenChange]);
    // Merge theme with overrides
    const theme = {
        ...popoverTheme,
        ...(themeOverrides || {}),
    };
    // Context value
    const contextValue = {
        isOpen,
        onOpenChange: handleOpenChange,
        triggerRef,
        contentRef,
        placement,
        offset,
        triggerType,
        closeOnClickOutside,
        closeOnEsc,
        preventClose,
        hasBackdrop,
        theme,
        contentId,
    };
    return (jsx(PopoverContext.Provider, { value: contextValue, children: jsx("div", { className: cn("popover", darkMode && "dark", className), "data-state": isOpen ? "open" : "closed", "data-backdrop": hasBackdrop ? "true" : "false", ...props, children: children }) }));
};
// Export as a unified component
const Popover = Object.assign(PopoverRoot, {
    Trigger: PopoverTrigger,
    Body: PopoverBody,
});

export { Popover };
