'use client';

import * as React from 'react';
import { useFloatingTree } from '@floating-ui/react';
import { useAnchorPositioning } from '../../utils/useAnchorPositioning.js';
import { useMenuRootContext } from '../root/MenuRootContext.js';
export function useMenuPositioner(params) {
  const {
    nodeId,
    parentNodeId
  } = params;
  const {
    open,
    setOpen,
    mounted,
    setHoverEnabled
  } = useMenuRootContext();
  const positioning = useAnchorPositioning(params);
  const {
    events: menuEvents
  } = useFloatingTree();
  const positionerProps = React.useMemo(() => {
    const hiddenStyles = {};
    if (!open) {
      hiddenStyles.pointerEvents = 'none';
    }
    return {
      role: 'presentation',
      hidden: !mounted,
      style: {
        ...positioning.positionerStyles,
        ...hiddenStyles
      }
    };
  }, [open, mounted, positioning.positionerStyles]);
  React.useEffect(() => {
    function onMenuOpenChange(event) {
      if (event.open) {
        if (event.parentNodeId === nodeId) {
          setHoverEnabled(false);
        }
        if (event.nodeId !== nodeId && event.parentNodeId === parentNodeId) {
          setOpen(false, undefined);
        }
      } else if (event.parentNodeId === nodeId) {
        setHoverEnabled(true);
      }
    }
    menuEvents.on('openchange', onMenuOpenChange);
    return () => {
      menuEvents.off('openchange', onMenuOpenChange);
    };
  }, [menuEvents, nodeId, parentNodeId, setOpen, setHoverEnabled]);
  React.useEffect(() => {
    menuEvents.emit('openchange', {
      open,
      nodeId,
      parentNodeId
    });
  }, [menuEvents, open, nodeId, parentNodeId]);
  return React.useMemo(() => ({
    ...positioning,
    positionerProps
  }), [positioning, positionerProps]);
}