/**
 * Small pure helpers for TUI stdin routing (`TUI.handleInput`).
 *
 * Purpose: keep listener fan-out isolated from viewport / overlay routing so
 * `tui.ts` stays readable without changing behaviour.
 */

export type InputListenerResult =
	| { consume?: boolean; data?: string }
	| undefined;
export type InputListener = (data: string) => InputListenerResult;

/**
 * Run stdin through each listener in insertion order until one consumes or
 * rewrites `data`.
 *
 * Returns `undefined` when a listener consumes the chunk (caller should exit).
 */
export function applyInputListeners(
	listeners: Set<InputListener>,
	intake: string,
): string | undefined {
	let current = intake;
	for (const listener of listeners) {
		const result = listener(current);
		if (result?.consume) {
			return undefined;
		}
		if (result?.data !== undefined) {
			current = result.data;
		}
	}
	return current.length === 0 ? undefined : current;
}
