extends Node

@onready var spawn_system: Node = get_node("../SpawnSystem")

var active_enemies: Array = []
var active: bool = false

func _ready() -> void:
  EventBus.entity_died.connect(_on_died)

func start(wave: int) -> void:
  if not (multiplayer.is_server() or multiplayer.multiplayer_peer == null):
    return
  active = true
  active_enemies.clear()
  var count: int = 6 + wave * 2
  for i in range(count):
    var angle: float = randf() * TAU
    var pos := Vector3(cos(angle) * 50.0, 0.5, sin(angle) * 50.0)
    var e: Node = spawn_system.spawn_enemy_at(pos, true, 1.0 + wave * 0.5)
    if e:
      active_enemies.append(e)
      e.set("origin", Vector3.ZERO)
      var v: Node = get_tree().get_first_node_in_group("village")
      if v:
        e.set("invasion_target", v)

func _on_died(entity: Node) -> void:
  if not active:
    return
  if entity in active_enemies:
    active_enemies.erase(entity)
    if active_enemies.is_empty():
      active = false
      EventBus.invasion_ended.emit(true)

func damage_village(amount: float) -> void:
  var v: Node = get_tree().get_first_node_in_group("village")
  if v == null:
    return
  EventBus.damage_requested.emit(v, v, amount, Element.NONE)
