extends Node3D

@onready var spring_arm: SpringArm3D = $SpringArm3D
var _desired_length: float = 7.0


func _ready() -> void:
	Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
	_desired_length = DP.f("cam_spring_length")
	spring_arm.spring_length = _desired_length


func _unhandled_input(event: InputEvent) -> void:
	var sensitivity: float = DP.f("cam_sensitivity")
	var min_vert: float = deg_to_rad(DP.f("cam_min_vert_angle"))
	var max_vert: float = deg_to_rad(DP.f("cam_max_vert_angle"))
	var min_zoom: float = DP.f("cam_min_zoom")
	var max_zoom: float = DP.f("cam_max_zoom")

	if event is InputEventMouseMotion:
		rotation.y -= event.relative.x * sensitivity
		rotation.y = wrapf(rotation.y, 0.0, TAU)
		rotation.x -= event.relative.y * sensitivity
		rotation.x = clamp(rotation.x, min_vert, max_vert)

	if event.is_action_pressed("zoom_in"):
		_desired_length = clamp(_desired_length / 1.2, min_zoom, max_zoom)
	if event.is_action_pressed("zoom_out"):
		_desired_length = clamp(_desired_length * 1.2, min_zoom, max_zoom)

	if event.is_action_pressed("toggle_mouse_capture"):
		if Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
			Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
		else:
			Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)


func _process(_delta: float) -> void:
	spring_arm.spring_length = _desired_length
