export function radioGroupNav(
	node: HTMLElement,
	onChange?: (value: string) => void
): { destroy: () => void; update: (onChange?: (value: string) => void) => void } {
	let onChangeFn = onChange;

	function getRadios(): HTMLElement[] {
		return Array.from(node.querySelectorAll<HTMLElement>('[role="radio"]'));
	}

	function handleKeydown(event: KeyboardEvent) {
		if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return;

		const radios = getRadios();
		const current = radios.indexOf(document.activeElement as HTMLElement);
		if (current === -1) return;

		const delta = event.key === 'ArrowRight' ? 1 : -1;
		const next = (current + delta + radios.length) % radios.length;

		radios[next].focus();
		radios.forEach((r, i) => r.setAttribute('aria-checked', i === next ? 'true' : 'false'));
		onChangeFn?.(radios[next].getAttribute('value') ?? '');
	}

	node.addEventListener('keydown', handleKeydown);

	return {
		update(newOnChange) {
			onChangeFn = newOnChange;
		},
		destroy() {
			node.removeEventListener('keydown', handleKeydown);
		}
	};
}
