//! UI helper utilities.

use bevy::prelude::*;
use bevy::ui::ComputedNode;

/// Returns `true` if the cursor is currently hovering any UI node.
///
/// Used to suppress scene-level mouse input (orbit camera drag, star picking)
/// when the user is interacting with overlay UI. The check is a manual rect
/// containment test against every UI node's computed layout rect — this is
/// the same approach Bevy's own `ui_focus_system` uses internally.
///
/// Coordinates: Bevy UI layout runs in **physical** pixels, while
/// [`Window::cursor_position`] returns **logical** pixels. We multiply by the
/// window's scale factor to convert.
pub fn cursor_over_ui(window: &Window, nodes: &Query<(&ComputedNode, &GlobalTransform)>) -> bool {
    let Some(cursor_logical) = window.cursor_position() else {
        return false;
    };

    let scale = window.scale_factor();
    let cursor = cursor_logical * scale;

    for (node, gt) in nodes {
        if node.is_empty() {
            continue;
        }
        let center = gt.translation().truncate();
        let half = node.size() * 0.5;
        let min = center - half;
        let max = center + half;
        if cursor.x >= min.x && cursor.x <= max.x && cursor.y >= min.y && cursor.y <= max.y {
            return true;
        }
    }
    false
}
