use bevy::prelude::*;
use bevy_sprite3d::Sprite3dPlugin;

#[derive(Component, Reflect)]
#[reflect(Component)]
pub struct Billboard;

pub fn plugin(app: &mut App) {
    if !app.is_plugin_added::<Sprite3dPlugin>() {
        app.add_plugins(Sprite3dPlugin);
    }

    app.register_type::<Billboard>();
    app.add_systems(Update, face_camera);
}

fn face_camera(
    cam_query: Query<&GlobalTransform, With<Camera>>,
    mut query: Query<
        (&mut Transform, &Parent, &InheritedVisibility),
        (With<Billboard>, Without<Camera>),
    >,
    parent_transform: Query<&GlobalTransform>,
) {
    let cam_transform = cam_query.single();
    for (mut transform, parent, visible) in query.iter_mut() {
        if !matches!(*visible, InheritedVisibility::VISIBLE) {
            continue;
        }

        let Ok(parent_global) = parent_transform.get(parent.get()) else {
            continue;
        };

        let target = cam_transform.reparented_to(parent_global);
        transform.look_at(target.translation, Vec3::Y);
    }
}
