'use client';

import * as React from 'react';
import { ownerDocument } from '@base-ui/utils/owner';
import { EMPTY_OBJECT } from "./constants.js";

/**
 * Returns `click` and `mousedown` handlers that fix the behavior of triggers of popups that are toggled by different events.
 * For example, a button that opens a popup on mousedown and closes it on click.
 * This hook prevents the popup from closing immediately after the mouse button is released.
 */
export function useMixedToggleClickHandler(params) {
  const {
    enabled = true,
    mouseDownAction,
    open
  } = params;
  const ignoreClickRef = React.useRef(false);
  return React.useMemo(() => {
    if (!enabled) {
      return EMPTY_OBJECT;
    }
    return {
      onMouseDown: event => {
        if (mouseDownAction === 'open' && !open || mouseDownAction === 'close' && open) {
          ignoreClickRef.current = true;
          ownerDocument(event.currentTarget).addEventListener('click', () => {
            ignoreClickRef.current = false;
          }, {
            once: true
          });
        }
      },
      onClick: event => {
        if (ignoreClickRef.current) {
          ignoreClickRef.current = false;
          event.preventBaseUIHandler();
        }
      }
    };
  }, [enabled, mouseDownAction, open]);
}