extends StaticBody3D

@export var stats_resource: VillageStats

@onready var mesh: MeshInstance3D = $Mesh
@onready var label: Label3D = $Label
@onready var healthbar: MeshInstance3D = $Healthbar

func _enter_tree() -> void:
  set_multiplayer_authority(1)

func _ready() -> void:
  add_to_group("village")
  if stats_resource == null:
    stats_resource = VillageStats.new()
    stats_resource.max_health = 1000.0
  Stats.register(self, stats_resource)
  EventBus.health_changed.connect(_on_health_changed)
  EventBus.entity_died.connect(_on_entity_died)
  label.text = "Village"

func _exit_tree() -> void:
  Stats.deregister(self)

func _on_health_changed(entity: Node, current: float, max: float) -> void:
  if entity != self:
    return
  EventBus.village_damaged.emit(current, max)
  var ratio: float = clamp(current / max if max > 0 else 0.0, 0.0, 1.0)
  healthbar.scale.x = max(0.01, ratio * 4.0)

func _on_entity_died(entity: Node) -> void:
  if entity != self:
    return
  EventBus.village_destroyed.emit()
  EventBus.game_over.emit()
