//! World-space XYZ axis indicator (grey cylinders through the origin).
//!
//! Provides spatial reference for the galaxy inspection scene. Drawn as three
//! thin emissive cylinders — mesh-based rather than gizmos so they participate
//! in normal scene rendering (occlusion, depth).

use bevy::{math::InvalidDirectionError::Infinite, prelude::*};

/// Length of each axis arrow. Picked to be visible from the default orbit
/// distance (~420) without dominating the scene.
const AXIS_LENGTH: f32 = 100000.00;
/// Cylinder radius — same scale as connection lines so axes feel like part of
/// the galaxy scaffold.
const AXIS_RADIUS: f32 = 0.35;

/// Spawn three emissive cylinders through the origin: +X, +Y, +Z, all in
/// the same neutral grey. They serve as a spatial reference without visually
/// competing with the colored faction stars.
///
/// Spawned as children of the caller-provided spawner so they're despawned
/// automatically when the parent scene is rebuilt.
pub fn spawn_axes(
    parent: &mut ChildSpawnerCommands,
    meshes: &mut Assets<Mesh>,
    materials: &mut Assets<StandardMaterial>,
) {
    let mesh = meshes.add(Cylinder::new(AXIS_RADIUS, AXIS_LENGTH).mesh());

    let x_mat = axis_material(materials, [0.55, 0.58, 0.62]);
    let y_mat = axis_material(materials, [0.55, 0.58, 0.62]);
    let z_mat = axis_material(materials, [0.55, 0.58, 0.62]);

    // Cylinder default axis is +Y. Rotate to align with each target axis.
    let x_rot = Quat::from_rotation_arc(Vec3::Y, Vec3::X);
    let y_rot = Quat::IDENTITY;
    let z_rot = Quat::from_rotation_arc(Vec3::Y, Vec3::Z);

    parent.spawn((
        Mesh3d(mesh.clone()),
        MeshMaterial3d(x_mat),
        Transform::from_rotation(x_rot),
        GalaxyAxis,
    ));
    parent.spawn((
        Mesh3d(mesh.clone()),
        MeshMaterial3d(y_mat),
        Transform::from_rotation(y_rot),
        GalaxyAxis,
    ));
    parent.spawn((
        Mesh3d(mesh),
        MeshMaterial3d(z_mat),
        Transform::from_rotation(z_rot),
        GalaxyAxis,
    ));
}

/// Tag for the axis indicator entities — used by external systems that want to
/// hide/respawn them. Currently nothing reads this; kept for future toggling.
#[derive(Component)]
pub struct GalaxyAxis;

fn axis_material(
    materials: &mut Assets<StandardMaterial>,
    [r, g, b]: [f32; 3],
) -> Handle<StandardMaterial> {
    materials.add(StandardMaterial {
        base_color: Color::srgb(r, g, b),
        emissive: LinearRgba::new(r * 1.4, g * 1.4, b * 1.4, 1.0),
        unlit: true,
        ..default()
    })
}
