import { type FormEvent, useState } from "react";
import { useEncounter } from "./hooks/use-encounter";

function formatEvent(e: ReturnType<typeof useEncounter>["events"][number]) {
	switch (e.type) {
		case "TurnAdvanced":
			return `Turn: ${e.previousCombatantId} → ${e.newCombatantId} (round ${e.roundNumber})`;
		case "RoundAdvanced":
			return `Round advanced to ${e.newRoundNumber}`;
		case "CombatantAdded":
			return `Added combatant: ${e.name}`;
	}
}

export function App() {
	const { encounter, events, advanceTurn, addCombatant } = useEncounter();
	const activeCombatant = encounter.combatants[encounter.activeIndex];
	const [nameInput, setNameInput] = useState("");

	const handleAdd = (e: FormEvent) => {
		e.preventDefault();
		if (nameInput.trim() === "") return;
		addCombatant(nameInput);
		setNameInput("");
	};

	return (
		<div>
			<h1>Initiative Tracker</h1>

			{activeCombatant && (
				<p>
					Round {encounter.roundNumber} — Current: {activeCombatant.name}
				</p>
			)}

			<ul>
				{encounter.combatants.map((c, i) => (
					<li key={c.id}>
						{i === encounter.activeIndex ? `▶ ${c.name}` : c.name}
					</li>
				))}
			</ul>

			<form onSubmit={handleAdd}>
				<input
					type="text"
					value={nameInput}
					onChange={(e) => setNameInput(e.target.value)}
					placeholder="Combatant name"
				/>
				<button type="submit">Add Combatant</button>
			</form>

			<button type="button" onClick={advanceTurn}>
				Next Turn
			</button>

			{events.length > 0 && (
				<div>
					<h2>Events</h2>
					<ul>
						{events.map((e, i) => (
							<li key={`${e.type}-${i}`}>{formatEvent(e)}</li>
						))}
					</ul>
				</div>
			)}
		</div>
	);
}
