use crate::{GameState, physics_layers::GameLayer};
use avian3d::prelude::*;
use bevy::prelude::*;
use bevy_trenchbroom::physics::SceneCollidersReady;

pub fn plugin(app: &mut App) {
    app.add_systems(OnEnter(GameState::MapLoading), setup_scene);
}

fn setup_scene(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands
        .spawn((
            CollisionLayers::new(LayerMask(GameLayer::Level.to_bits()), LayerMask::ALL),
            SceneRoot(asset_server.load("maps/map1.map#Scene")),
        ))
        .observe(
            |_t: Trigger<SceneCollidersReady>,
             mut next_game_state: ResMut<NextState<GameState>>| {
                info!("map loaded");

                next_game_state.set(GameState::Playing);
            },
        );

    commands.spawn((
        DirectionalLight {
            illuminance: light_consts::lux::OVERCAST_DAY,
            shadows_enabled: true,
            ..default()
        },
        Transform {
            translation: Vec3::new(0.0, 2.0, 0.0),
            rotation: Quat::from_rotation_x(-1.7),
            ..default()
        },
    ));
}
