extends Node3D

@onready var camera: Camera3D = $YawPivot/PitchPivot/Camera3D
@onready var pitchPivot: Marker3D = $YawPivot/PitchPivot
@onready var yawPivot: Marker3D = $YawPivot

@export var sensitivity: float = 0.01
@export var zoom_speed: float = 0.5
@export var min_zoom: float = 5.0
@export var max_zoom: float = 50.0
@export var min_pitch: float = -65.0
@export var max_pitch: float = 20.0

# Speed of pivot movement
@export var movement_speed: float = 10

# For boundaries of pivot movement
# Currently the boundaries are fixed to a certain position
@export var min_movement_x: float = -2
@export var max_movement_x: float = 8
@export var min_movement_z: float = -2
@export var max_movement_z: float = 12

var dragging = false

func _unhandled_input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
		# Left Mouse Button
		if event.button_index == MOUSE_BUTTON_LEFT:
			dragging = event.pressed
		
		# Zoom In/Out
		elif event.button_index == MOUSE_BUTTON_WHEEL_UP:
			_zoom_camera(-zoom_speed)
		elif event.button_index == MOUSE_BUTTON_WHEEL_DOWN:
			_zoom_camera(zoom_speed)
			
	elif dragging and event is InputEventMouseMotion:
		yawPivot.rotate_y(-event.relative.x * sensitivity)
		pitchPivot.rotate_x(-event.relative.y * sensitivity)
		# Makes sure the pitch is within the boundaries
		pitchPivot.rotation.x = clamp(pitchPivot.rotation.x, deg_to_rad(min_pitch), deg_to_rad(max_pitch))

func _process(delta: float):
	var direction := Vector3.ZERO
	
	if Input.is_action_pressed("move_forward"):
		direction -= yawPivot.transform.basis.z
	if Input.is_action_pressed("move_backward"):
		direction += yawPivot.transform.basis.z
	if Input.is_action_pressed("move_left"):
		direction -= yawPivot.transform.basis.x
	if Input.is_action_pressed("move_right"):
		direction += yawPivot.transform.basis.x
		
	direction.y = 0
	direction = direction.normalized()
	
	position.x += direction.x * movement_speed * delta
	position.z += direction.z * movement_speed * delta
	# Clamp positions such that the pivot position does not go beyond the boundaries
	position.x = clamp(position.x, min_movement_x, max_movement_x)
	position.z = clamp(position.z, min_movement_z, max_movement_z)

func _zoom_camera(amount: float):
	var camera_global_pos = camera.global_transform.origin
	var pivot_pos = global_transform.origin
	
	var direction = (camera_global_pos - pivot_pos).normalized()
	var distance = camera_global_pos.distance_to(pivot_pos)
	
	distance = clamp(distance + amount, min_zoom, max_zoom)
	camera.global_transform.origin = pivot_pos + direction * distance
