extends Node

const WAVE_DURATION := 60.0

var tick_accumulator := 0.0

func _ready() -> void:
  EventBus.portal_defeated.connect(_on_portal_defeated)
  EventBus.invasion_ended.connect(_on_invasion_ended)
  call_deferred("_start_run")

func _start_run() -> void:
  if not GameState.run_initialized:
    GameState.current_wave = 1
    GameState.wave_timer_remaining = WAVE_DURATION
    GameState.run_initialized = true
    EventBus.run_started.emit(GameState.current_wave)
  EventBus.wave_started.emit(GameState.current_wave)

func _process(delta: float) -> void:
  if GameState.wave_timer_remaining <= 0:
    return
  GameState.wave_timer_remaining -= delta
  tick_accumulator += delta
  if tick_accumulator >= 1.0:
    tick_accumulator -= 1.0
    EventBus.wave_timer_tick.emit(max(0.0, GameState.wave_timer_remaining))
  if GameState.wave_timer_remaining <= 0:
    GameState.wave_timer_remaining = 0.0
    EventBus.wave_timer_tick.emit(0.0)

func _on_portal_defeated(portal: Node) -> void:
  if not portal.is_in_group("red_portal"):
    return
  _advance_wave()

func _on_invasion_ended(success: bool) -> void:
  if not success:
    return
  _advance_wave()

func _advance_wave() -> void:
  EventBus.wave_ended.emit(GameState.current_wave, true)
  GameState.current_wave += 1
  GameState.wave_timer_remaining = WAVE_DURATION
  tick_accumulator = 0.0
  EventBus.wave_started.emit(GameState.current_wave)
