extends CharacterBody3D

var mouse_sensitivity := 0.001
var horizontal_twist := 0.0
var vertical_twist := 0.0
var current_speed := 3.0
var speed := 3.0
var normal_speed := 3.0
var sprint_speed := 6.0
var focus_speed := 1.5
var menu_open := false
var sprint_on := false
var focus_on := false


@onready var fp_camera := %FirstPerson

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _physics_process(delta: float) -> void:
	if not menu_open:
		var input_velocity := Vector3.ZERO
		var input_direction_2D := Input.get_vector(
			"move_left", "move_right", "move_forward", "move_back"
		)
		var input_direction_3D := Vector3(
			input_direction_2D.x, 0.0, input_direction_2D.y
		)
		
		input_velocity = transform.basis * input_direction_3D * speed
		
		#print("velocidades 3D: ", velocity_x, ", ", velocity_z)
		
		if Input.is_action_just_pressed("sprint"):
			sprint_on = true
			change_speed()
		elif Input.is_action_just_released("sprint"):
			sprint_on = false
			change_speed()
		elif Input.is_action_just_pressed("toggle_sprint"):
			sprint_on = not sprint_on
			change_speed()
		
#		if Input.is_action_just_pressed("focus"):
#			focus_on = true
#			%Flashlight.spot_range = 16.0
#			%Flashlight.spot_angle = 7.0
#			%Flashlight.light_energy = 8.0
#			change_speed()
#		elif Input.is_action_just_released("focus"):
#			focus_on = false
#			%Flashlight.spot_range = 8.0
#			%Flashlight.spot_angle = 28.0
#			%Flashlight.light_energy = 2.0
#			change_speed()
		
		velocity = input_velocity
		
		rotation.y -= horizontal_twist
		fp_camera.rotation.x -= vertical_twist
		fp_camera.rotation.x = clamp(fp_camera.rotation.x, -1.0, 1.0)
		
		horizontal_twist = 0.0
		vertical_twist = 0.0
		
		move_and_slide()

func _unhandled_input(event: InputEvent) -> void:
	if event is InputEventMouseMotion:
		if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
			horizontal_twist = event.relative.x * mouse_sensitivity
			vertical_twist = event.relative.y * mouse_sensitivity
			
	if Input.is_action_just_pressed("pause"):
			if menu_open:
				menu_open = false
				Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
			else:
				menu_open = true
				Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)

func change_speed() -> void:
	if focus_on:
		speed = focus_speed
	elif sprint_on:
		speed = sprint_speed
	else:
		speed = normal_speed
