/**
 * @function useDropdownBlur
 * @description Adds the blur handler to props.
 *
 * @since 4.5.0
 *
 * @param {object}   props    The props to add handlers to.
 * @param {Function} useStore The useStore hook.
 *
 * @return {object} The modified props.
 */
const useDropdownBlur = ( props = {}, useStore ) => {
	const { resetAndClose = () => {} } = props;
	const triggerRef = useStore( ( state ) => state.triggerRef );
	const popoverRef = useStore( ( state ) => state.popoverRef );
	const open = useStore( ( state ) => state.open );

	/**
	 * @function handleBlur
	 * @description Handles the blur event.
	 *
	 * @since 4.5.0
	 *
	 * @param {Event} event The event object.
	 */
	const handleBlur = ( event ) => {
		requestAnimationFrame( () => {
			if (
				! open ||
				(
					triggerRef.current &&
					popoverRef.current &&
					(
						triggerRef.current.contains( document.activeElement ) ||
						popoverRef.current.contains( document.activeElement )
					)
				)
			) {
				return;
			}
			resetAndClose?.( event );
		} );
	};

	return {
		...props,
		handleBlur,
	};
};

export default useDropdownBlur;
