extends CharacterBody2D
signal hurt

@onready var player: CharacterBody2D = $"../../Player"
@onready var timer: Timer = $Deathcounter

const SPEED = 150
var inarea = false
var alive = true

func _physics_process(delta: float) -> void:
	velocity.y += get_gravity().y * delta
	if inarea and alive:
		if player.global_position.x < self.global_position.x:
			get_node("AnimatedSprite2D").flip_h = true
			velocity.x -= SPEED * delta
		elif  player.global_position.x > self.global_position.x:
			get_node("AnimatedSprite2D").flip_h = false
			velocity.x += SPEED * delta
	else:
		velocity.x = 0
	move_and_slide()
	


func _on_player_detection_body_entered(body: Node2D) -> void:
	if body.name == "Player":
		inarea = true


func _on_player_detection_body_exited(body: Node2D) -> void:
	if body.name == "Player":
		inarea = false

	
func _on_killingzone_body_entered(body: Node2D) -> void:
	if body.name == "Player":
		if player.global_position.y < self.global_position.y - 10 :
			get_node("AnimatedSprite2D").play("death")
			alive = false
			timer.start()
		elif alive:
			print("HURT")
			hurt.emit()


func _on_timer_timeout() -> void:
	queue_free()
