extends CharacterBody3D

const SPEED:= 150.0
const CHASE_RANGE:= 4.5
const ATTACK_RANGE:= 1.0

var dead:= false
var EXECUTED:= false 
@export var DAMAGE_ATTACK:= 1
@onready var action = $beetle_bot_Skin/AnimationPlayer
@export var target : CharacterBody3D
@export var attack_cooldown = 2.5
@onready var nav_agent = $nav_agent
@onready var animation_tree = $beetle_bot_Skin/AnimationTree
@onready var state_machine = animation_tree.get("parameters/playback")
@onready var attack_time := $SecondaryActionTimer
@export var LIFE:= 5


func verfy_life():
	if LIFE == 0:
		dead = true
		
func _process(delta: float):
	
	velocity = Vector3.ZERO
	
	match state_machine.get_current_node():
		
			"idle":
				look_at(Vector3(target.global_position.x, global_position.y, target.global_position.z), Vector3.UP)
			"walk":
				if global_position.distance_to(target.global_position) < CHASE_RANGE:
					nav_agent.target_position = target.global_transform.origin
					var next_nav_point = nav_agent.get_next_path_position()
					velocity = (next_nav_point - global_transform.origin).normalized() * SPEED * delta
					look_at(Vector3(target.global_position.x, global_position.y, target.global_position.z), Vector3.UP)
			"attack":
				if not EXECUTED:
					look_at(Vector3(target.global_position.x, global_position.y, target.global_position.z), Vector3.UP)
				
					
	animation_tree.set("parameters/conditions/walk", chase_player())
	animation_tree.set("parameters/conditions/idle", not chase_player())
	animation_tree.set("parameters/conditions/attack", attack_player())
	

	move_and_slide()

func chase_player(): 
	return global_position.distance_to(target.global_position) < CHASE_RANGE

func attack_player():
	return global_position.distance_to(target.global_position) < ATTACK_RANGE

	
func _on_area_3d_body_entered(body: Node3D) -> void: #head
	if body.name == "player":
		body.damage_player(DAMAGE_ATTACK)
		EXECUTED = true
		await get_tree().create_timer(2.0).timeout
		EXECUTED = false
	# Replace with function body.

func damage(amount):
	LIFE -= amount
	verfy_life()
	

func _on_secondary_action_timer_timeout() -> void:
	pass

#func _on_body_area_entered(area: Area3D) -> void:
	#if area.name == "Foot":
		#pass
		
		
