extends CharacterBody3D

const TARGET_FPS: float = 60.0
const BASE_SPEED: float = 5.0
const JUMP_FORCE: float = 4.5
const FRICTION: float = 0.3
const AIR_DRAG: float = 0.03
const INPUT_SENSITIVITY: float = 0.7
const TURN_SENSITIVITY: float = 0.04

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

@onready var camera_root: Node3D = $CameraRoot
@onready var mesh: Node3D = $Mesh
@onready var animation_tree: AnimationTree = $Mesh/Mech/AnimationTree


func _physics_process(delta: float) -> void:
	var delta_factor: float = delta * TARGET_FPS

	# Add the gravity.
	if not is_on_floor():
		velocity.y -= gravity * delta
	elif animation_tree["parameters/anim_state/current_state"] == "air":
		animation_tree["parameters/jump_state/transition_request"] = "end"

	# Handle jump.
	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = JUMP_FORCE
		animation_tree["parameters/jump_state/transition_request"] = "in_air"
		animation_tree["parameters/anim_state/transition_request"] = "air"

	# Get the input direction and handle the movement/deceleration.
	var input_dir: Vector2 = Input.get_vector("left", "right", "forward", "backward")
	if input_dir:
		var movement: Vector3 = (
			(camera_root.global_transform.basis * Vector3(input_dir.x, 0, input_dir.y) * -1)
			. normalized()
		)
		velocity.x = lerpf(velocity.x, movement.x * BASE_SPEED, delta_factor * INPUT_SENSITIVITY)
		velocity.z = lerpf(velocity.z, movement.z * BASE_SPEED, delta_factor * INPUT_SENSITIVITY)

		if is_on_floor():
			mesh.rotation.y = lerp_angle(
				mesh.rotation.y, camera_root.rotation.y, delta_factor * TURN_SENSITIVITY
			)
		animation_tree["parameters/move_state/transition_request"] = "walk"
		animation_tree["parameters/walk_space/blend_position"] = input_dir
	else:
		animation_tree["parameters/move_state/transition_request"] = "idle"

	var drag: float = FRICTION if is_on_floor() else AIR_DRAG
	velocity.x = lerpf(velocity.x, 0.0, delta_factor * drag)
	velocity.z = lerpf(velocity.z, 0.0, delta_factor * drag)

	move_and_slide()
