class_name CameraController extends Node3D

const PITCH_LIMIT := deg_to_rad(85.0)
const FOCUS_SENSITIVITY := 0.2
const FOCUS_ACCELERATION := 8

@onready var player: Player = owner

@onready var _target := Vector2(rotation.x, rotation.y)


func _unhandled_input(event: InputEvent) -> void:
	if event is InputEventMouseMotion:
		if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED:
			camera_motion((event as InputEventMouseMotion).relative)
	elif event is InputEventMouseButton:
		Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)


func camera_motion(motion: Vector2) -> void:
	var x_sensitivity: float = Game.settings.mouse_sensitivity_x
	var y_sensitivity: float = Game.settings.mouse_sensitivity_y
	var invert_pitch: bool = Game.settings.invert_pitch
	if player.firing:
		# Focus movement when firing
		# Game mechanic, should not be user-configurable.
		x_sensitivity = FOCUS_SENSITIVITY
		y_sensitivity = FOCUS_SENSITIVITY

	_target.y -= deg_to_rad(motion.x * x_sensitivity)
	_target.x = clampf(
		_target.x - deg_to_rad(motion.y * y_sensitivity) * (-1 if invert_pitch else 1),
		-PITCH_LIMIT,
		PITCH_LIMIT
	)


func _physics_process(_delta: float) -> void:
	var mouse_accel: float = Game.settings.mouse_acceleration / 60.0
	if player.firing:
		mouse_accel = FOCUS_ACCELERATION / 60.0
	rotation.y = lerp_angle(rotation.y, _target.y, mouse_accel)
	rotation.x = lerp_angle(rotation.x, _target.x, mouse_accel)
