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

import { getAllScrollableParents } from './get-all-scrollable-parents';

/**
 * Sets up positioning event listeners for an element.
 *
 * @param config - Configuration object
 * @param config.element - The element to watch for positioning
 * @param config.handler - The handler function to call when positioning events occur
 * @returns A function that cleans up all event listeners when called
 */
export function createAnchorPositioningWatcher( { element, handler } ) {
	const cleanupCallbacks = [];

	// Get all scrollable parents of the element
	const scrollableParents = getAllScrollableParents( element, true );

	// Add event listeners to window for resize
	window.addEventListener( 'resize', handler, { passive: true } );
	cleanupCallbacks.push( () => {
		window.removeEventListener( 'resize', handler );
	} );

	// Add wheel and scroll event listeners to all scrollable parents
	for ( const parent of scrollableParents ) {
		parent.addEventListener( 'wheel', handler, { passive: true } );
		parent.addEventListener( 'scroll', handler, { passive: true } );

		// Store cleanup callbacks
		cleanupCallbacks.push( () => {
			parent.removeEventListener( 'wheel', handler );
			parent.removeEventListener( 'scroll', handler );
		} );
	}

	// Return a single function that cleans up all event listeners
	return () => {
		for ( const cleanup of cleanupCallbacks ) {
			cleanup();
		}
	};
}
