class_name BattleFighterScene extends Node3D

@export var battlePosition:BattleSingleton.BattlePosition = BattleSingleton.BattlePosition.LEFT_MIDDLE_FRONT
@export var damageLabels:Node3D
@export var damageLabelPreset:PackedScene
@export var sprite:AnimatedSprite3D

var currentFighter:BattleFighter = null

func _getFighter() -> BattleFighter:
  return BATTLE.getFighterAtPosition(self.battlePosition)

func _updateFighter() -> void:
  if currentFighter != null:
    currentFighter.healthChanged.disconnect(onDamageTaken)

  currentFighter = _getFighter()
  if currentFighter == null:
    self.visible = false
    return

  # Set up the visual representation of the fighter here
  currentFighter.healthChanged.connect(onDamageTaken)
  self.visible = true

  # Update left/right orientation
  if sprite != null:
    if BattleSingleton.isPositionRight(battlePosition):
      sprite.flip_h = true
    else:
      sprite.flip_h = false

func _enter_tree() -> void:
  BATTLE.battleFightersChanged.connect(onFightersChanged)
  self._updateFighter()

func _exit_tree() -> void:
  BATTLE.battleFightersChanged.disconnect(onFightersChanged)

func onFightersChanged() -> void:
  _updateFighter()

func onDamageTaken(amount:int, crit:bool) -> void:
  var damageLabel = damageLabelPreset.instantiate() as Label3D
  damageLabel.showDamage(damageLabels, amount, crit)
