extends Node

func _ready() -> void:
  EventBus.target_requested.connect(_on_target_requested)
  EventBus.entity_died.connect(_on_entity_died)
  EventBus.enemy_engaged.connect(_on_enemy_engaged)
  EventBus.damage_dealt.connect(_on_damage_dealt)

func _process(delta: float) -> void:
  if PlayerData.in_combat:
    PlayerData.combat_timer -= delta
    if PlayerData.combat_timer <= 0:
      PlayerData.in_combat = false

func _on_target_requested(_player: Node, target: Node3D) -> void:
  PlayerData.set_target(target)
  if target and (target.is_in_group("enemies") or target.is_in_group("portals")):
    PlayerData.in_combat = true
    PlayerData.combat_timer = PlayerData.combat_timeout

func _on_entity_died(entity: Node) -> void:
  if entity == PlayerData.target:
    PlayerData.set_target(null)
    if PlayerData.in_combat:
      _auto_target(entity)

func _on_enemy_engaged(_enemy: Node, target: Node) -> void:
  var player: Node = get_tree().get_first_node_in_group("player")
  if target == player:
    PlayerData.combat_timer = PlayerData.combat_timeout
    PlayerData.in_combat = true
    if PlayerData.target == null:
      _auto_target()

func _on_damage_dealt(attacker: Node, target: Node, _amount: float) -> void:
  var player: Node = get_tree().get_first_node_in_group("player")
  if target == player:
    PlayerData.combat_timer = PlayerData.combat_timeout
    if not PlayerData.in_combat:
      PlayerData.in_combat = true
      if PlayerData.target == null:
        _auto_target()
  elif attacker == player:
    PlayerData.in_combat = true
    PlayerData.combat_timer = PlayerData.combat_timeout

func _auto_target(exclude: Node = null) -> void:
  var player: Node = get_tree().get_first_node_in_group("player")
  if not player:
    return
  var nearest: Node3D = null
  var nearest_dist: float = INF
  for enemy in get_tree().get_nodes_in_group("enemies"):
    if is_instance_valid(enemy) and enemy != exclude:
      var dist: float = player.global_position.distance_to(enemy.global_position)
      if dist < nearest_dist:
        nearest_dist = dist
        nearest = enemy
  if nearest:
    PlayerData.set_target(nearest)
    return
  for p in get_tree().get_nodes_in_group("portals"):
    if is_instance_valid(p) and p != exclude:
      var dist: float = player.global_position.distance_to(p.global_position)
      if dist < nearest_dist:
        nearest_dist = dist
        nearest = p
  if nearest:
    PlayerData.set_target(nearest)
