use crate::prelude::*;

pub(crate) struct CreditsPlugin;

impl Plugin for CreditsPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(Startup, init_credits_ui)
            .add_systems(
                Update,
                (menu::exit_to_menu.run_if(in_state(GameState::Credits)),),
            )
            .add_systems(
                OnEnter(GameState::Credits),
                (update_credits, activate::<Credits>.after(update_credits)),
            )
            .add_systems(OnExit(GameState::Credits), deactivate::<Credits>);
    }
}

#[derive(Debug, Component)]
struct Credits;

fn init_credits_ui(mut commands: Commands) {
    commands
        .spawn((
            Credits,
            NodeBundle {
                style: Style {
                    width: Val::Percent(100.0),
                    height: Val::Percent(100.0),
                    justify_content: JustifyContent::Center,
                    align_items: AlignItems::Center,
                    position_type: PositionType::Absolute,
                    ..default()
                },
                visibility: Visibility::Hidden,
                ..default()
            },
        ))
        .with_children(|parent| {
            parent.spawn((
                Credits,
                TextBundle {
                    text: Text {
                        alignment: TextAlignment::Center,
                        sections: vec![],
                        ..default()
                    },
                    background_color: Color::BLACK.with_a(0.5).into(),
                    ..default()
                },
            ));
        });
}

fn update_credits(
    mut query: Query<&mut Text, With<Credits>>,
    tweaks: Res<Assets<tweak::Tweaks>>,
    tweaks_file: Res<tweak::GameTweaks>,
) {
    let tweak = tweaks
        .get(tweaks_file.handle.clone())
        .expect("Load tweakfile");

    query.iter_mut().for_each(|mut text| {
        let credits_text = tweak.get::<String>("credits_text").unwrap();
        text.sections = {
            credits_text
                .split('\n')
                .map(|l| TextSection {
                    value: format!("{}\n", l),
                    style: TextStyle { ..default() },
                })
                .collect()
        };
        debug!("Text sections: {:?}", text.sections);
    });
}
