class_name NPC extends CharacterBody3D

@export var target : Node3D
@export var movement_speed: float = 4.0
@onready var navigation_agent: NavigationAgent3D = $NavigationAgent3D
@onready var label : Label = $Label

func _input(event: InputEvent) -> void:
	if event.is_action_pressed('interact'):
		set_movement_target(target.position)

func _ready() -> void:
	navigation_agent.velocity_computed.connect(Callable(_on_velocity_computed))

func set_movement_target(movement_target: Vector3):
	navigation_agent.set_target_position(movement_target)

func _physics_process(_delta):
	if navigation_agent.is_navigation_finished():
		return

	var next_path_position: Vector3 = navigation_agent.get_next_path_position()
	var new_velocity: Vector3 = global_position.direction_to(next_path_position) * movement_speed
	if navigation_agent.avoidance_enabled:
		navigation_agent.velocity = new_velocity
	else:
		_on_velocity_computed(new_velocity)

func _on_velocity_computed(safe_velocity: Vector3):

	label.text = "x:%f y:%f z:%f" % [safe_velocity.x, safe_velocity.y, safe_velocity.z]
	safe_velocity.y = 0
	var direction := safe_velocity.normalized()
	if direction:
		velocity = direction * movement_speed
		look_at(global_position - direction)
	move_and_slide()
