/**
 * Throttles a function to execute at most once per specified delay period.
 * The first call executes immediately, then subsequent calls are throttled.
 *
 * @param func - The function to throttle
 * @param delay - Minimum time in milliseconds between function executions
 * @returns Throttled version of the function
 */
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let lastCall = 0;
  let timeout: NodeJS.Timeout | null = null;

  return function (...args: Parameters<T>) {
    const now = Date.now();
    const timeSinceLastCall = now - lastCall;

    const execute = () => {
      lastCall = Date.now();
      func(...args);
    };

    if (timeSinceLastCall >= delay) {
      // Enough time has passed, execute immediately
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      execute();
    } else if (!timeout) {
      // Schedule execution after remaining delay
      timeout = setTimeout(() => {
        timeout = null;
        execute();
      }, delay - timeSinceLastCall);
    }
  };
}
