extends CharacterBody3D

@export var stats: EnemyStats

var gravity: float = ProjectSettings.get_setting("physics/3d/default_gravity")
var spawn_scale: float = 1.0
var hover_t: float = 0.0
var mesh_base_y: float = 0.0

func _ready() -> void:
  add_to_group("enemies")
  if is_in_group("boss"):
    BossData.register(self, stats, spawn_scale)
    BossData.set_stat(self, "spawn_position", global_position)
  else:
    EnemyData.register(self, stats, spawn_scale)
    EnemyData.set_stat(self, "spawn_position", global_position)
  EventBus.entity_died.connect(_on_entity_died)
  var mesh: Node3D = get_node_or_null("Mesh")
  if mesh:
    mesh_base_y = mesh.position.y
    _apply_appearance(mesh)

func _exit_tree() -> void:
  if is_in_group("boss"):
    BossData.deregister(self)
  else:
    EnemyData.deregister(self)

func _on_entity_died(entity: Node) -> void:
  if entity == self:
    queue_free()

func _process(delta: float) -> void:
  hover_t += delta
  var mesh: Node3D = get_node_or_null("Mesh")
  if mesh:
    mesh.position.y = mesh_base_y + sin(hover_t * 3.0) * 0.08

func _apply_appearance(mesh: Node3D) -> void:
  if mesh is MeshInstance3D:
    var mat := StandardMaterial3D.new()
    if is_in_group("boss"):
      mat.albedo_color = Color(0.6, 0.15, 0.7, 1)
      mat.emission_enabled = true
      mat.emission = Color(0.8, 0.2, 0.9, 1)
      mat.emission_energy_multiplier = 0.4
    else:
      mat.albedo_color = Color(0.7, 0.25, 0.25, 1)
      mat.emission_enabled = true
      mat.emission = Color(0.9, 0.3, 0.2, 1)
      mat.emission_energy_multiplier = 0.25
    (mesh as MeshInstance3D).material_override = mat

func _physics_process(delta: float) -> void:
  if not is_on_floor():
    velocity.y -= gravity * delta
  move_and_slide()
