import { jsx } from 'react/jsx-runtime';
import React__default, { useRef, useState, useEffect, useCallback } from 'react';
import { useReducedMotion, AnimatePresence, motion } from 'motion/react';
import { createPortal } from 'react-dom';
import { cn } from '../../../utils/cn.js';
import { useContextMenuContext, useSubMenuContext } from './ContextMenuContext.js';
import { useIsClient } from '../../../hooks/useIsClient.js';

/**
 * ContextMenuSubBody - Submenu content positioned to the right of trigger
 */
const ContextMenuSubBody = React__default.forwardRef(({ children, className, animation = true, ...props }, ref) => {
    const { theme } = useContextMenuContext();
    const { isOpen, triggerRef, onOpenChange } = useSubMenuContext();
    const shouldReduceMotion = useReducedMotion();
    const isClient = useIsClient();
    const localRef = useRef(null);
    const [position, setPosition] = useState({ x: 0, y: 0 });
    // Update position when submenu opens
    useEffect(() => {
        if (isOpen && triggerRef.current) {
            const triggerRect = triggerRef.current.getBoundingClientRect();
            // Position to the right of the trigger
            let x = triggerRect.right + 4; // 4px offset
            let y = triggerRect.top;
            // Check if submenu would overflow right edge
            const submenuWidth = 180; // min-w-[180px]
            if (x + submenuWidth > window.innerWidth) {
                // Position to the left instead
                x = triggerRect.left - submenuWidth - 4;
            }
            // Check if submenu would overflow bottom edge
            const submenuHeight = 300; // estimated max height
            if (y + submenuHeight > window.innerHeight) {
                y = window.innerHeight - submenuHeight - 10;
            }
            // Keep minimum padding from edges
            x = Math.max(10, Math.min(x, window.innerWidth - submenuWidth - 10));
            y = Math.max(10, y);
            setPosition({ x, y });
        }
    }, [isOpen, triggerRef]);
    // Close submenu on scroll
    useEffect(() => {
        if (!isOpen)
            return;
        const handleScroll = () => {
            onOpenChange(false);
        };
        // Use capture phase to catch all scroll events
        window.addEventListener("scroll", handleScroll, true);
        return () => window.removeEventListener("scroll", handleScroll, true);
    }, [isOpen, onOpenChange]);
    // Combine refs
    const handleRef = useCallback((el) => {
        localRef.current = el;
        if (typeof ref === "function") {
            ref(el);
        }
        else if (ref && typeof ref === "object" && "current" in ref) {
            ref.current = el;
        }
    }, [ref]);
    // Animation variants
    const menuVariants = {
        hidden: {
            opacity: 0,
            scale: 0.95,
            x: -10,
        },
        visible: {
            opacity: 1,
            scale: 1,
            x: 0,
        },
        exit: {
            opacity: 0,
            scale: 0.95,
            x: -10,
        },
    };
    // Extract DOM props to avoid conflicts
    const { onAnimationStart, onAnimationEnd, onDrag, onDragStart, onDragEnd, ...domProps } = props;
    // Detect dark mode from document
    const isDarkMode = typeof document !== "undefined" &&
        (document.documentElement.classList.contains("dark") ||
            document.body.classList.contains("dark") ||
            document.querySelector(".dark") !== null);
    const submenuContent = (jsx(AnimatePresence, { children: isOpen && (jsx(motion.div, { ref: handleRef, className: cn("fixed z-50", isDarkMode && "dark", theme.subContentStyle, className), style: {
                top: `${position.y}px`,
                left: `${position.x}px`,
            }, role: "menu", "aria-label": "Submenu", variants: shouldReduceMotion || !animation ? {} : menuVariants, initial: shouldReduceMotion || !animation ? undefined : "hidden", animate: shouldReduceMotion || !animation ? undefined : "visible", exit: shouldReduceMotion || !animation ? undefined : "exit", transition: shouldReduceMotion || !animation
                ? { duration: 0 }
                : {
                    type: "spring",
                    stiffness: 500,
                    damping: 30,
                }, "data-state": isOpen ? "open" : "closed", ...domProps, children: children })) }));
    // Always use portal for submenus
    return isClient
        ? createPortal(submenuContent, document.body)
        : null;
});
ContextMenuSubBody.displayName = "ContextMenu.SubBody";

export { ContextMenuSubBody };
