extends CharacterBody2D

@export var sonido: AudioStreamPlayer2D
var speed: float = randf_range(100.0, 300.0)
var direction: Vector2 = Vector2.ZERO
signal died(pos: Vector2)

func _ready() -> void:
	var element = randi_range(1, 3)
	if element == 1:
		$AnimatedSprite2D.animation = "blue"
		$AnimatedSprite2D.play("blue")
		$wind/CollisionShape2D.disabled = true
		$water/CollisionShape2D.disabled = false
		$fire/CollisionShape2D.disabled = true
	if element == 2:
		$AnimatedSprite2D.animation = "orange"
		$AnimatedSprite2D.play("orange")
		$wind/CollisionShape2D.disabled = true
		$water/CollisionShape2D.disabled = true
		$fire/CollisionShape2D.disabled = false
	if element == 3:
		$AnimatedSprite2D.animation = "white"
		$AnimatedSprite2D.play("white")
		$wind/CollisionShape2D.disabled = false
		$water/CollisionShape2D.disabled = true
		$fire/CollisionShape2D.disabled = true

func _physics_process(delta: float) -> void:
	direction = (Global.player_position - global_position).normalized()
	velocity = direction * speed
	move_and_slide()


func _on_fire_area_entered(area: Area2D) -> void:
	if area.is_in_group("fire"):
		area.remove_from_group("enemy")
		area.remove_from_group("fire")
		$AudioStreamPlayer2D.play()
		position = Vector2(-100, -100)
		hide()
		await get_tree().create_timer(1.0).timeout
		queue_free()


func _on_water_area_entered(area: Area2D) -> void:
	if area.is_in_group("water"):
		area.remove_from_group("enemy")
		area.remove_from_group("water")
		$AudioStreamPlayer2D.play()
		position = Vector2(-100, -100)
		hide()
		await get_tree().create_timer(1.0).timeout
		queue_free()


func _on_wind_area_entered(area: Area2D) -> void:
	if area.is_in_group("wind"):
		area.remove_from_group("enemy")
		area.remove_from_group("wind")
		$AudioStreamPlayer2D.play()
		position = Vector2(-100, -100)
		hide()
		await get_tree().create_timer(1.0).timeout
		queue_free()
