//! Phosphor icon font registration for the primary egui context.

use bevy::prelude::*;
use bevy_egui::{EguiContext, PrimaryEguiContext};

pub struct EditorFontsPlugin;

impl Plugin for EditorFontsPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(Update, configure_editor_fonts);
    }
}

fn configure_editor_fonts(mut contexts: Query<&mut EguiContext, Added<PrimaryEguiContext>>) {
    let Some(mut ctx) = contexts.iter_mut().next() else {
        return;
    };
    let mut fonts = bevy_egui::egui::FontDefinitions::default();
    egui_phosphor_icons::add_fonts(&mut fonts);

    // Phosphor families contain icon glyphs only. Text fallbacks give egui a
    // replacement glyph for malformed/missing icons without changing icon lookup.
    let text_fallbacks = fonts
        .families
        .get(&bevy_egui::egui::FontFamily::Proportional)
        .cloned()
        .unwrap_or_default();
    for (family, font_names) in &mut fonts.families {
        let bevy_egui::egui::FontFamily::Name(name) = family else {
            continue;
        };
        if !name.starts_with("phosphor-") {
            continue;
        }
        for fallback in &text_fallbacks {
            if !font_names.contains(fallback) {
                font_names.push(fallback.clone());
            }
        }
    }
    ctx.get_mut().set_fonts(fonts);
}
