/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

/**
 * Watches for clicks outside of specified elements and triggers a callback when they occur.
 *
 * @param config - Configuration object.
 * @param config.elements - Elements to monitor.
 * @param config.callback - Function to call when click outside occurs.
 * @returns Cleanup function to remove the listener.
 */
export function createOutsideClickWatcher( { elements, callback } ) {
	// Convert single element to array for consistent handling.
	if ( !Array.isArray( elements ) ) {
		elements = [ elements ];
	}

	// Handler function for click event.
	const handleClick = event => {
		// Check if click was outside all monitored elements.
		const isOutside = !elements.some( element =>
			element === event.target || element.contains( event.target )
		);

		if ( isOutside ) {
			callback( event );
		}
	};

	// Attach the event listener.
	document.addEventListener( 'click', handleClick );

	// Return cleanup function.
	return () => {
		document.removeEventListener( 'click', handleClick );
	};
}
