import { useRef } from 'react';

/**
 * Backdrop "click outside to close" that does NOT fire when a drag started
 * inside the modal (e.g. selecting text in an input) and was released on the
 * backdrop. A plain `onClick={onClose}` closes in that case because the browser
 * dispatches `click` on the common ancestor of mousedown+mouseup — which is the
 * backdrop — losing the user's edits.
 *
 * Spread the returned props on the backdrop element and REMOVE the old
 * `onClick={onClose}`:
 *
 *   const backdrop = useBackdropClose(onClose);
 *   <div className="fixed inset-0 ..." {...backdrop}> ... </div>
 *
 * Close only happens when BOTH the mousedown and the click target are the
 * backdrop itself, so a genuine backdrop click still closes, but a
 * press-inside / release-on-backdrop drag does not.
 */
export function useBackdropClose(onClose: () => void) {
  const downOnBackdrop = useRef(false);
  return {
    onMouseDown: (e: React.MouseEvent) => {
      downOnBackdrop.current = e.target === e.currentTarget;
    },
    onClick: (e: React.MouseEvent) => {
      if (downOnBackdrop.current && e.target === e.currentTarget) {
        onClose();
      }
      downOnBackdrop.current = false;
    },
  };
}
