/**
 * Region navigation for the transcribe keyboard shortcuts (j/k) — issue #327.
 *
 * Pure and side-effect free so the wrap-around / fresh-entry branches are
 * unit-testable without mounting the page.
 */

/**
 * Pick the annotation id one step from the active region, wrapping around the
 * ends. Entering fresh (no active region, or an unknown id) lands on the first
 * region going forward and the last going backward.
 *
 * @param orderedAnnotationIds region annotation ids in display order
 * @param activeId the currently active region, or null
 * @param delta +1 for next (j), -1 for previous (k)
 * @returns the next annotation id, or null when there are no regions
 */
export function stepRegion(
	orderedAnnotationIds: string[],
	activeId: string | null,
	delta: 1 | -1
): string | null {
	const count = orderedAnnotationIds.length;
	if (count === 0) return null;

	const current = activeId === null ? -1 : orderedAnnotationIds.indexOf(activeId);
	if (current === -1) {
		return delta > 0 ? orderedAnnotationIds[0] : orderedAnnotationIds[count - 1];
	}

	const next = (current + delta + count) % count;
	return orderedAnnotationIds[next];
}
