class_name PlayerAiming
extends RefCounted

@export var _controller_aim_offset: float = 6
@export var _vertical_aim_aspect: float = 1.5

var aim_offset: Vector3
var aim_input: Vector2

var _floor_height: float


func controller_aiming(move_input: Vector2) -> void:
	aim_input = Input.get_vector("aim_left", "aim_right", "aim_up", "aim_down")

	if aim_input.length() == 0 and move_input.length() == 0:
		return

	var input := (aim_input if aim_input.length() > 0 else move_input).normalized()

	var aim_direction := Vector3(input.x, 0, input.y * _vertical_aim_aspect)

	aim_offset = (
		aim_direction.rotated(Vector3.UP, Referencer.main_camera.rotation.y)
		* _controller_aim_offset
	)


func mouse_aiming(
	mouse_pos: Vector2, player_position: Vector3, is_on_floor: bool
) -> void:
	var position_y := player_position.y
	if is_on_floor:
		_floor_height = player_position.y
	player_position.y = _floor_height

	var aim_position := _mouse_project(mouse_pos, _floor_height + Projectile.HEIGHT)
	aim_offset = aim_position - player_position
	aim_offset.y = 0
	aim_position.y = position_y


func _mouse_project(mouse_pos: Vector2, height: float) -> Vector3:
	var camera := Referencer.main_camera

	var from := camera.project_ray_origin(mouse_pos)
	var direction := camera.project_ray_normal(mouse_pos)
	var plane := Plane(Vector3.UP, height)

	var intersection: Variant = plane.intersects_ray(from, direction)
	if not intersection:
		return Vector3.ZERO
	return intersection as Vector3
