class_name RoomSpawn extends Area2D

@export var waves_container: Node2D

var waves: Array[Node] = []
var current_wave_index: int = 0
var active_enemies: int = 0
var has_triggered: bool = false

func _ready() -> void:
	body_entered.connect(_on_body_entered)
	
	if not waves_container:
		push_error("Waves container not assigned in RoomSpawn!")
		return
		
	waves = waves_container.get_children()
	for wave in waves:
		wave.hide()
		wave.process_mode = Node.PROCESS_MODE_DISABLED

func _on_body_entered(body: Node2D) -> void:
	if has_triggered:
		return
		
	if body.is_in_group("player"):
		has_triggered = true
		start_next_wave()

func start_next_wave() -> void:
	if current_wave_index >= waves.size():
		return
		
	var current_wave = waves[current_wave_index]
	current_wave.show()
	current_wave.process_mode = Node.PROCESS_MODE_INHERIT
	
	var enemies = current_wave.get_children()
	active_enemies = enemies.size()
	
	if active_enemies == 0:
		current_wave_index += 1
		start_next_wave()
		return
		
	for enemy in enemies:
		enemy.tree_exited.connect(_on_enemy_died)

func _on_enemy_died() -> void:
	active_enemies -= 1
	
	if active_enemies <= 0:
		current_wave_index += 1
		start_next_wave()
