extends CharacterBody3D
class_name Enemy

@export var speed: float = 5.0
@export var max_speed: float = 2 * speed
@export var attack_distace: float = 1.3
@export var drop_chance: float = 0.5
@export var max_health: float = 5.0;

var despawn_threshold = -10

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")

var player: Player

@export var anim: AnimationPlayer

@export var drop: PackedScene

@export var attack_anim: String = "Attack"
@export var running_anim: String = "running"
@export var idle_anim: String = "idle"

@onready var nav_agent: NavigationAgent3D = $NavigationAgent3D


var spawned_objects;
var world;

@onready var health = $Health 

func _ready():
	player = get_tree().get_nodes_in_group("Player").back();
	world = find_parent("MainScene");
	spawned_objects = world.find_child("SpawnedObjects");


func _physics_process(delta):
	# Add the gravity.
	if not is_on_floor():
		velocity.y -= gravity * delta
	elif player:
		look_at(player.position, Vector3.UP)
		rotation.x = 0.0
		rotation.z = 0.0
		
		var player_distance: float = position.distance_to(player.position)
		if player_distance <= attack_distace:
			if anim.current_animation != attack_anim:
				anim.speed_scale = 2.0
				anim.play(attack_anim)
		
		if position.y <= 2.5 and player_distance > 2.5 * attack_distace:
			nav_agent.set_target_position(player.position)
			var next_location: Vector3 = nav_agent.get_next_path_position()
			var new_velocity = (next_location - global_position).normalized() * speed
			velocity = velocity.move_toward(new_velocity, 0.99)
		else:
			var angle: float = rotation.y
			var direction: Vector3 = Vector3.FORWARD
			direction = direction.rotated(Vector3.UP, angle).normalized()
			if direction:
				velocity.x = direction.x * speed
				velocity.z = direction.z * speed
			else:
				velocity.x = move_toward(velocity.x, 0, speed)
				velocity.z = move_toward(velocity.z, 0, speed)
	
		if anim.current_animation != attack_anim:
			if velocity.length() > 0.01:
				anim.speed_scale = 1.0
				anim.play(running_anim)
			else:
				anim.speed_scale = 1.0
				anim.play(idle_anim)
	
	if position.y < despawn_threshold:
		# Remove the node from the scene
		queue_free()
	move_and_slide()


func _on_health_death():
	if drop != null and randf() < drop_chance:
		var new_item = drop.instantiate()
		new_item.position = position
		
		spawned_objects.add_child(new_item) 
	queue_free()
	
	world.update_kill_score(1)
	

func update_stats(dif):
	speed += (max_speed - speed) * dif
	drop_chance += drop_chance * dif
	var add_health = (max_health - health.max_health) * dif
	if add_health < 0.25:
		add_health = 0.0
	health.set_maxhealth(health.max_health + add_health)
	
	
