// Radial layout for the BattleViewer.
//
// Places race anchors on a circle of radius `radius` around `center`
// at equal angular spacing. For three or more races the first anchor
// sits at the top (12 o'clock) and subsequent anchors march
// clockwise. For exactly two races the pair is rotated 90° so they
// face each other horizontally (3 o'clock vs 9 o'clock) — that keeps
// every race label clear of the SVG top edge when only two clusters
// remain, and reads as "the two sides facing off" naturally.
//
// When a race is eliminated mid-battle the caller filters it out of
// `activeRaceIds` and the survivors are re-spaced on the next frame
// through the same helper.

export interface RaceAnchor {
	raceId: number;
	x: number;
	y: number;
	/** Angle in radians measured from the positive Y axis clockwise. */
	angle: number;
}

export interface RadialLayoutOptions {
	center: { x: number; y: number };
	radius: number;
}

/**
 * layoutRaces returns anchor positions for each `activeRaceIds`
 * entry, placed at equal angular spacing on a circle. The input
 * order is preserved so consumers get a stable mapping across
 * frames; eliminated entries should simply be filtered out before
 * the call.
 */
export function layoutRaces(
	activeRaceIds: number[],
	options: RadialLayoutOptions,
): RaceAnchor[] {
	const count = activeRaceIds.length;
	if (count === 0) return [];
	const { center, radius } = options;
	const out: RaceAnchor[] = [];
	// For two participants we want a horizontal duel layout: race 0
	// at 9 o'clock, race 1 at 3 o'clock. For any other count the
	// first anchor lands at the top (12 o'clock) and the rest march
	// clockwise at equal spacing.
	const startAngle = count === 2 ? Math.PI : -Math.PI / 2;
	for (let i = 0; i < count; i++) {
		const step = (2 * Math.PI) / count;
		const angle = startAngle + i * step;
		out.push({
			raceId: activeRaceIds[i],
			x: center.x + radius * Math.cos(angle),
			y: center.y + radius * Math.sin(angle),
			angle,
		});
	}
	return out;
}
