pub(super) fn create_secondary_egui_state(
    renderer: &mut Option<Box<dyn crate::ecs::world::Render>>,
    index: usize,
    window_handle: &std::sync::Arc<winit::window::Window>,
) -> Option<egui_winit::State> {
    if let Some(renderer) = renderer {
        renderer.initialize_secondary_egui(index);
    }
    let gui_context = egui::Context::default();
    let viewport_id = gui_context.viewport_id();
    let gui_state = egui_winit::State::new(
        gui_context,
        viewport_id,
        window_handle,
        Some(window_handle.scale_factor() as _),
        Some(winit::window::Theme::Dark),
        None,
    );
    egui_extras::install_image_loaders(gui_state.egui_ctx());
    Some(gui_state)
}

impl super::MultiWindowContext {
    pub(super) fn process_secondary_egui(&mut self) {
        let window_ids: Vec<winit::window::WindowId> =
            self.secondary_windows.keys().copied().collect();

        for window_id in window_ids {
            let Some(info) = self.secondary_windows.get_mut(&window_id) else {
                continue;
            };

            let Some(mut egui_state) = info.egui_state.take() else {
                continue;
            };

            let window_handle = info.handle.clone();
            let index = info.index;

            let scale_factor = window_handle.scale_factor() as f32;
            egui_state.egui_ctx().set_pixels_per_point(scale_factor);
            let gui_input = egui_state.take_egui_input(&window_handle);
            egui_state.egui_ctx().begin_pass(gui_input);
            let ctx = egui_state.egui_ctx().clone();

            self.state.secondary_ui(&mut self.world, index, &ctx);

            let output = ctx.end_pass();
            egui_state.handle_platform_output(&window_handle, output.platform_output.clone());
            let paint_jobs = ctx.tessellate(output.shapes.clone(), output.pixels_per_point);

            if let Some(renderer) = &mut self.renderer
                && let Err(error) =
                    renderer.render_egui_to_secondary_surface(index, Some(output), Some(paint_jobs))
            {
                tracing::error!("Failed to render egui to secondary surface {index}: {error}");
            }

            if let Some(info) = self.secondary_windows.get_mut(&window_id) {
                info.egui_state = Some(egui_state);
            }
        }
    }
}
