//! Player entity bootstrap.

use avian3d::prelude::*;
use bevy::prelude::*;
use protocol::PlayerInputIntent;
use sim::tuning::*;
use sim::{
    CameraSensitivity, Crouching, Grounded, JumpState, Player, PlayerCamera, PlayerVelocity,
    PlayerYawSensitivity,
};

/// Spawns the player body (kinematic capsule) with a child first-person camera.
#[unsafe(no_mangle)]
pub fn spawn_player(mut commands: Commands, existing: Query<(), With<Player>>) {
    if !existing.is_empty() {
        return;
    }

    commands
        .spawn((
            Player,
            Name::new("Player"),
            Transform::from_xyz(0.0, 1.5, 10.0),
            Visibility::default(),
            RigidBody::Kinematic,
            CustomPositionIntegration,
            Collider::capsule(PLAYER_RADIUS, PLAYER_LENGTH),
            PlayerInputIntent::default(),
            PlayerVelocity::default(),
            PlayerYawSensitivity::default(),
            Grounded::default(),
            Crouching::default(),
            JumpState::default(),
        ))
        .with_children(|parent| {
            parent.spawn((
                PlayerCamera,
                Camera3d::default(),
                Msaa::Off,
                Camera {
                    clear_color: ClearColorConfig::Custom(Color::srgba(0.0, 0.0, 0.0, 1.0)),
                    ..default()
                },
                Transform::from_xyz(0.0, EYE_OFFSET_STAND, 0.0),
                CameraSensitivity::default(),
            ));
        });
}
