## TurnManager.gd
# Autoload singleton for managing turn order in a turn-based game.
# Handles registration, sequencing, and signaling for all turn-taking entities.
extends Node

# List of entities that participate in the turn order (e.g., Player, Enemies).
var turn_entities: Array[Node] = []
# Index of the entity whose turn is currently active.
var current_index: int = 0
# Whether the turn system is currently running.
var active: bool = false

# Registers an entity to participate in the turn order.
# Ensures no duplicates.
func register_entity(entity: Node) -> void:
	if entity not in turn_entities:
		turn_entities.append(entity)

# Unregisters an entity (e.g., when it is removed or defeated).
func unregister_entity(entity: Node) -> void:
	if entity in turn_entities:
		turn_entities.erase(entity)

# Starts the turn sequence for all registered entities.
# Resets the index and begins the first turn.
func start_turns() -> void:
	if turn_entities.size() == 0:
		return
	active = true
	current_index = 0
	_next_turn()

# Advances to the next entity's turn.
# Connects to the entity's turn_finished signal and calls its take_turn() method.
func _next_turn() -> void:
	if not active or turn_entities.size() == 0:
		return
	if current_index >= turn_entities.size():
		current_index = 0 # New round
	# Get the next entity in the list.
	var entity: Node = turn_entities[current_index]
	# Connect to the entity's turn_finished signal if not already connected.
	if not entity.is_connected("turn_finished", Callable(self, "_on_entity_turn_finished")):
		entity.connect("turn_finished", Callable(self, "_on_entity_turn_finished"))
	# Notify the entity to take its turn.
	entity.take_turn()

# Called when an entity finishes its turn (emits turn_finished).
# Disconnects the signal and advances to the next entity.
func _on_entity_turn_finished() -> void:
	# Disconnect to avoid duplicate connections.
	var entity: Node = turn_entities[current_index]
	if entity.is_connected("turn_finished", Callable(self, "_on_entity_turn_finished")):
		entity.disconnect("turn_finished", Callable(self, "_on_entity_turn_finished"))
	current_index += 1
	_next_turn()

# Optionally, stops the turn sequence and resets state.
func stop_turns() -> void:
	active = false
	current_index = 0
