/**
 * Shared list-table row-click guard.
 *
 * List tables open a drawer (or navigate to an edit screen) when a row is
 * clicked. That must NOT fire when the user was selecting text in any column —
 * dragging to highlight a name, an amount, an ID. A single pointer tracker,
 * loaded before every row-click handler, answers one question for all of them:
 * "was the click that's firing really the release of a drag / a text
 * selection?" One implementation, every list table.
 *
 * getSelection() alone is unreliable (the selection can be collapsed by the
 * time the click fires, and a short drag may leave none), so the primary
 * signal is pointer travel since mousedown, measured on the capture phase so
 * it's settled before any handler runs.
 */
( function () {

	let moved = false;
	let downX = 0;
	let downY = 0;

	document.addEventListener( 'mousedown', function ( event ) {
		moved = false;
		downX = event.clientX;
		downY = event.clientY;
	}, true );

	document.addEventListener( 'mousemove', function ( event ) {
		if ( ! moved && ( Math.abs( event.clientX - downX ) > 4 || Math.abs( event.clientY - downY ) > 4 ) ) {
			moved = true;
		}
	}, true );

	/**
	 * Whether the click currently firing should be treated as a text selection
	 * rather than a row-open click.
	 *
	 * @return {boolean} True if the pointer moved during the press, or a
	 *                   non-collapsed text selection exists.
	 */
	window.affwpRowClickWasSelection = function () {
		if ( moved ) {
			return true;
		}
		const selection = window.getSelection && window.getSelection();
		return !! ( selection && ! selection.isCollapsed && String( selection ).length );
	};

} )();
