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

/**
 * Creates a throttled version of a function that only executes at most once
 * every specified delay period.
 *
 * @param {Function} callback - The function to throttle.
 * @param {number} delay - The delay in milliseconds.
 * @returns {Function} - The throttled function.
 */
export function throttle( callback, delay ) {
	if ( typeof callback !== 'function' ) {
		throw new Error( 'Callback must be a function' );
	}

	let isThrottled = false;
	let savedArgs = null;
	let savedThis = null;

	function wrapper( ...args ) {
		if ( isThrottled ) {
			savedArgs = args;
			// eslint-disable-next-line consistent-this
			savedThis = this;
			return;
		}

		callback.apply( this, args );
		isThrottled = true;

		setTimeout( () => {
			isThrottled = false;

			if ( savedArgs ) {
				wrapper.apply( savedThis, savedArgs );
				savedArgs = null;
				savedThis = null;
			}
		}, delay );
	}

	return wrapper;
}
