use bevy::prelude::*;

pub struct MousePlugin;

impl Plugin for MousePlugin {
	fn build(&self, app: &mut App) {
		app.insert_resource(Mouse::default());
		app.add_systems(PreUpdate, mouse_position);
	}
}

#[derive(Resource, Default, Deref, DerefMut)]
pub struct Mouse(pub Vec2);

fn mouse_position(
	mut mouse: ResMut<Mouse>,
	window: Query<&Window>,
	camera: Query<(&Camera, &GlobalTransform)>,
) {
	let Ok(window) = window.get_single()
	else {
		return;
	};

	if let Some(position) = window.cursor_position() {
		let Ok((camera, camera_transform)) = camera.get_single()
		else {
			return;
		};

		let window_size = Vec2::new(window.width(), window.height());
		let ndc = ((position / window_size) * 2.0 - Vec2::ONE) * Vec2::new(1., -1.);
		let world_pos = camera
			.ndc_to_world(camera_transform, ndc.extend(-1.0))
			.unwrap_or_default();
		let world_pos: Vec2 = world_pos.truncate();
		mouse.0 = world_pos;
	}
}
