extends Node

var respawn_timer := 0.0
var is_dead := false

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

func _process(delta: float) -> void:
  if not is_dead:
    return
  respawn_timer -= delta
  EventBus.respawn_tick.emit(respawn_timer)
  if respawn_timer <= 0:
    _respawn()

func _on_entity_died(entity: Node) -> void:
  if entity != PlayerData:
    return
  if is_dead:
    return
  is_dead = true
  respawn_timer = PlayerData.respawn_time
  var player: Node = get_tree().get_first_node_in_group("player")
  if not player:
    return
  player.velocity = Vector3.ZERO
  player.get_node("Mesh").visible = false
  player.get_node("CollisionShape3D").disabled = true
  player.get_node("Movement").set_physics_process(false)
  player.get_node("Ability").set_process_unhandled_input(false)
  player.get_node("Targeting").set_process_unhandled_input(false)

func _respawn() -> void:
  is_dead = false
  var player: Node = get_tree().get_first_node_in_group("player")
  if not player:
    return
  player.global_position = Vector3(0, 1, -5)
  player.get_node("Mesh").visible = true
  player.get_node("CollisionShape3D").disabled = false
  player.get_node("Movement").set_physics_process(true)
  player.get_node("Ability").set_process_unhandled_input(true)
  player.get_node("Targeting").set_process_unhandled_input(true)
  PlayerData.respawn()
