using Godot;
using static GameData;

public partial class Camera3d : Camera3D
{
	[Export] public float Speed = 7.5f;
	[Export] public float MouseSensitivity = 0.2f;
	[Export] public float ScrollStrength = 5.0f;

	private Vector2 _mouseDelta;

	public override void _Process(double delta)
	{
		if(!canMove) return;
		float d = (float)delta;

		var rotation = RotationDegrees;
		rotation.X = Mathf.Clamp(rotation.X, -90f, 90f);
		RotationDegrees = rotation;

		_mouseDelta = Vector2.Zero;

		Vector3 direction = Vector3.Zero;
		if (Input.IsActionPressed("move_forward") && Position.Z > 0) direction += Transform.Basis.Z;
		if (Input.IsActionPressed("move_backward") && Position.Z < layerSize * 6) direction -= Transform.Basis.Z;
		if (Input.IsActionPressed("move_left") && Position.X > 0) direction -= Transform.Basis.X;
		if (Input.IsActionPressed("move_right") && Position.X < layerSize * 6) direction += Transform.Basis.X;

		if (direction != Vector3.Zero)
		{
			direction = direction.Normalized() * Speed * (Input.IsActionPressed("sprint") ? 2.5f : 1) * d;
			Translate(direction);
		}

		if (Position.Y != 10 - visibleLayer * 4)
		{
			Position = new Vector3(Position.X, 10 - visibleLayer * 4, Position.Z);
		}
	}

	public override void _Input(InputEvent @event)
	{
		if (@event is InputEventMouseButton mouse &&
			mouse.ButtonIndex == MouseButton.Left &&
			mouse.Pressed)
		{
			var camera = GetViewport().GetCamera3D();

			Vector2 mousePos = mouse.Position;

			Vector3 from = camera.ProjectRayOrigin(mousePos);
			Vector3 to = from + camera.ProjectRayNormal(mousePos) * 1000f;

			var spaceState = GetWorld3D().DirectSpaceState;

			var query = PhysicsRayQueryParameters3D.Create(from, to);

			query.CollisionMask = 1 << 1;

			var result = spaceState.IntersectRay(query);

			if (result.Count > 0)
			{
				Variant colliderVariant = result["collider"];

				Node hit = colliderVariant.As<Node>();

				GD.Print($"Clicked robot: {hit.Name}");

				// Optional: call method on robot
				if (hit is Node robot)
				{
					robot.Call("OnClicked");
				}
			}
		}
	}
}
