bevy_extended_ui 1.7.0

Create simply ui's with css and html for bevy.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
use crate::services::image_service::{DEFAULT_CHOICE_BOX_KEY, get_or_load_image};
use crate::styles::components::UiStyle;
use crate::styles::paint::Colored;
use crate::styles::{CssClass, CssSource, TagName};
use crate::widgets::widget_util::{
    apply_overlay_state_for_bind, clear_active_scroll_target_for_entity,
    first_child_logical_height, set_z_index_pair, wheel_delta_y,
};
use crate::widgets::{
    ActiveScrollTarget, BindToID, ChoiceBox, ChoiceOption, IgnoreParentState, UIGenID,
    UIWidgetState, WidgetId, WidgetKind,
};
use crate::{CurrentWidgetState, ExtendedUiConfiguration, ImageCache};
use bevy::camera::visibility::RenderLayers;
use bevy::ecs::relationship::RelatedSpawnerCommands;
use bevy::input::mouse::MouseWheel;
use bevy::prelude::*;
use bevy::ui::RelativeCursorPosition;

const CHOICE_BOX_OVERLAY_ROOT_Z: i32 = 40_000;
const CHOICE_BOX_OVERLAY_CONTENT_Z: i32 = 40_001;

/// Marker component for initialized choice box widgets.
#[derive(Component)]
struct ChoiceBase;

/// Marker component for individual choice option entries.
#[derive(Component)]
struct ChoiceOptionBase;

/// Marker component for the selected option display.
#[derive(Component)]
struct SelectedOptionBase;

/// Marker component for the dropdown caret/indicator.
#[derive(Component)]
struct DropBase;

/// Marker component for the overlay label node.
#[derive(Component)]
struct OverlayLabel;

/// Marker component for the dropdown content layout box.
#[derive(Component)]
pub struct ChoiceLayoutBoxBase;

/// Plugin that registers choice box widget behavior.
pub struct ChoiceBoxWidget;

impl Plugin for ChoiceBoxWidget {
    /// Registers systems for choice box setup and interaction.
    fn build(&self, app: &mut App) {
        app.add_systems(
            Update,
            (
                update_content_box_visibility,
                internal_node_creation_system,
                handle_scroll_events,
                handle_overlay_label,
            )
                .chain(),
        );
    }
}

/// System that initializes internal UI nodes for [`ChoiceBox`] components (select/dropdown widgets).
///
/// This system constructs the full visual structure of a dropdown menu, including
/// - Main select box
/// - Overlay label
/// - Currently selected option node (icon + text)
/// - Dropdown content container with all selectable options
///
/// Each `ChoiceBox` entity that hasn't yet been initialized (i.e., is missing [`ChoiceBase`])
/// gets the following structure:
/// - main select node with label and selected option
/// - content box containing option entries
///
/// # Behavior
/// - Observers are attached to the main box and each option to respond to hover and click.
/// - Styling is inherited from [`CssSource`] and modified using classes like `choice-content-box`, `choice-option`, etc.
/// - The dropdown menu is hidden by default and must be revealed through UI interaction.
///
/// # Parameters
/// - `commands`: Used to build entities and assign components.
/// - `query`: Selects uninitialized `ChoiceBox` widgets.
/// - `config`: UI configuration including rendering layers.
/// - `asset_server`: Loads icon images if used in options.
/// - `image_cache`: Prevents redundant image loading.
/// - `images`: Asset container for Bevy `Image`s.
fn internal_node_creation_system(
    mut commands: Commands,
    query: Query<
        (Entity, &UIGenID, &ChoiceBox, Option<&CssSource>),
        (With<ChoiceBox>, Without<ChoiceBase>),
    >,
    config: Res<ExtendedUiConfiguration>,
    asset_server: Res<AssetServer>,
    mut image_cache: ResMut<ImageCache>,
    mut images: ResMut<Assets<Image>>,
) {
    let layer = config.render_layers.first().unwrap_or(&1);
    for (entity, id, choice_box, source_opt) in query.iter() {
        let mut css_source = CssSource::default();
        if let Some(source) = source_opt {
            css_source = source.clone();
        }

        commands
            .entity(entity)
            .insert((
                Name::new(format!("Choice-Box-{}", choice_box.entry)),
                Node::default(),
                WidgetId {
                    id: choice_box.entry,
                    kind: WidgetKind::ChoiceBox,
                },
                BackgroundColor::default(),
                ImageNode::default(),
                BorderColor::default(),
                BoxShadow::new(
                    Colored::TRANSPARENT,
                    Val::Px(0.),
                    Val::Px(0.),
                    Val::Px(0.),
                    Val::Px(0.),
                ),
                ZIndex::default(),
                Pickable::default(),
                css_source.clone(),
                TagName("select".to_string()),
                RenderLayers::layer(*layer),
                ChoiceBase,
            ))
            .insert(GlobalZIndex::default())
            .observe(on_internal_click)
            .observe(on_internal_cursor_entered)
            .observe(on_internal_cursor_leave)
            .with_children(|builder| {
                // Overlay label
                builder.spawn((
                    Name::new(format!("Select-Label-{}", choice_box.entry)),
                    Node::default(),
                    Text::new(choice_box.label.clone()),
                    TextColor::default(),
                    TextLayout::default(),
                    TextFont::default(),
                    ZIndex::default(),
                    UIWidgetState::default(),
                    css_source.clone(),
                    CssClass(vec!["select-label".to_string()]),
                    Pickable::IGNORE,
                    RenderLayers::layer(*layer),
                    OverlayLabel,
                    BindToID(id.0),
                ));

                generate_child_selected_option(
                    builder,
                    &css_source.clone(),
                    choice_box,
                    layer,
                    &id.0,
                    &mut *image_cache,
                    &mut images,
                    &asset_server,
                );

                builder
                    .spawn((
                        Name::new(format!("Choice-Content-{}", choice_box.entry)),
                        Node::default(),
                        BackgroundColor::default(),
                        ImageNode::default(),
                        BorderColor::default(),
                        BoxShadow::new(
                            Colored::TRANSPARENT,
                            Val::Px(0.),
                            Val::Px(0.),
                            Val::Px(0.),
                            Val::Px(0.),
                        ),
                        ZIndex::default(),
                        UIWidgetState::default(),
                        css_source.clone(),
                        CssClass(vec![String::from("choice-content-box")]),
                        RenderLayers::layer(*layer),
                        Visibility::Hidden,
                        RelativeCursorPosition::default(),
                        ChoiceLayoutBoxBase,
                        BindToID(id.0),
                    ))
                    .observe(on_layout_cursor_entered)
                    .observe(on_layout_cursor_leave)
                    .insert(GlobalZIndex::default())
                    .insert(ScrollPosition::default())
                    .with_children(|builder| {
                        let mut selected_assigned = false;

                        for option in choice_box.options.iter() {
                            let is_selected = if !selected_assigned {
                                if choice_box
                                    .value
                                    .value
                                    .as_str()
                                    .map_or(false, |s| !s.is_empty())
                                {
                                    choice_box.value.value.as_str() == option.value.as_str()
                                } else if !choice_box.value.text.is_empty() {
                                    choice_box.value.text == option.text
                                } else {
                                    false
                                }
                            } else {
                                false
                            };

                            if is_selected {
                                selected_assigned = true;
                            }

                            let state = UIWidgetState {
                                checked: is_selected,
                                ..default()
                            };

                            builder
                                .spawn((
                                    Name::new(format!("Option-{}", choice_box.entry)),
                                    Node::default(),
                                    BackgroundColor::default(),
                                    ImageNode::default(),
                                    BorderColor::default(),
                                    ZIndex::default(),
                                    state.clone(),
                                    IgnoreParentState,
                                    option.clone(),
                                    css_source.clone(),
                                    CssClass(vec![String::from("choice-option")]),
                                    RenderLayers::layer(*layer),
                                    ChoiceOptionBase,
                                    BindToID(id.0),
                                ))
                                .observe(on_internal_option_click)
                                .observe(on_internal_option_cursor_entered)
                                .observe(on_internal_option_cursor_leave)
                                .with_children(|builder| {
                                    if let Some(icon_path) = option.icon_path.as_deref() {
                                        let handle = get_or_load_image(
                                            icon_path,
                                            &mut image_cache,
                                            &mut images,
                                            &asset_server,
                                        );

                                        builder.spawn((
                                            Name::new(format!("Option-Icon-{}", choice_box.entry)),
                                            ImageNode {
                                                image: handle,
                                                ..default()
                                            },
                                            ZIndex::default(),
                                            state.clone(),
                                            IgnoreParentState,
                                            css_source.clone(),
                                            CssClass(vec![
                                                String::from("option-icon"),
                                                String::from("option-text"),
                                            ]),
                                            Pickable::IGNORE,
                                            RenderLayers::layer(*layer),
                                            BindToID(id.0),
                                        ));
                                    }

                                    let text;
                                    if option.text.trim().is_empty() {
                                        text = Text::new("Select...");
                                    } else {
                                        text = Text::new(option.text.clone());
                                    }

                                    builder.spawn((
                                        Name::new(format!("Option-Text-{}", choice_box.entry)),
                                        text,
                                        TextColor::default(),
                                        TextFont::default(),
                                        TextLayout::default(),
                                        ZIndex::default(),
                                        state.clone(),
                                        IgnoreParentState,
                                        css_source.clone(),
                                        CssClass(vec![String::from("option-text")]),
                                        Pickable::IGNORE,
                                        RenderLayers::layer(*layer),
                                        BindToID(id.0),
                                    ));
                                });
                        }
                    });
            });
    }
}

// ===============================================
//             Intern Functions
// ===============================================

/// Adjusts the position and size of the overlay label in a [`ChoiceBox`] widget.
///
/// This system runs for all `ChoiceBox` components and finds their associated
/// overlay labels (nodes marked with [`OverlayLabel`] and [`BindToID`]).
///
/// - If the `ChoiceBox` is focused or has a selected value/icon, the label moves up
///   and shrinks (floating label style).
/// - Otherwise, the label remains in its original position (centered).
///
/// This system synchronizes both the `Node::top` and the corresponding [`WidgetStyle`] values
/// for runtime CSS-based animation consistency.
///
/// # Affects:
/// - `Node::top`
/// - `TextFont::font_size`
/// - `WidgetStyle::top`
/// - `WidgetStyle::font_size`
/// Shows or hides the overlay label based on selection state.
fn handle_overlay_label(
    query: Query<(&UIWidgetState, &UIGenID, &ChoiceBox, &Children), With<ChoiceBox>>,
    mut label_query: Query<(&BindToID, &mut Node, &mut TextFont, &mut UiStyle), With<OverlayLabel>>,
) {
    for (state, gen_id, choice_box, children) in query.iter() {
        for child in children.iter() {
            if let Ok((bind_to, mut node, mut text_font, mut styles)) = label_query.get_mut(child) {
                if bind_to.0 != gen_id.0 {
                    continue;
                }

                if state.focused {
                    node.top = Val::Px(5.);
                    text_font.font_size = FontSize::Px(10.0);
                } else {
                    if choice_box.value.text.is_empty() && choice_box.value.icon_path.is_none() {
                        node.top = Val::Px(19.5);
                        text_font.font_size = FontSize::Px(14.0);
                    } else {
                        node.top = Val::Px(5.);
                        text_font.font_size = FontSize::Px(10.0);
                    }
                }

                for (_, style) in styles.styles.iter_mut() {
                    style.normal.top = Some(node.top);
                    style.normal.font_size = Some(text_font.font_size);
                }
            }
        }
    }
}

/// Controls the visibility of the dropdown menu (`ChoiceLayoutBoxBase`) for each [`ChoiceBox`].
///
/// If a `ChoiceBox` loses focus, its menu is automatically closed (`open = false`).
/// This system synchronizes the `UIWidgetState::open` field with the actual visibility
/// of the child content box.
///
/// # Behavior:
/// - Sets `Visibility::Visible` if `UIWidgetState::open` is true.
/// - Otherwise, hides the dropdown menu.
///
/// # Affects:
/// - `UIWidgetState::open`
/// - `Visibility`
/// Toggles dropdown visibility based on widget state.
fn update_content_box_visibility(
    mut query: Query<(&mut UIWidgetState, &UIGenID), (With<ChoiceBox>, Changed<UIWidgetState>)>,
    mut root_query: Query<
        (&mut ZIndex, &mut GlobalZIndex, &UIGenID),
        (With<ChoiceBox>, Without<ChoiceLayoutBoxBase>),
    >,
    mut content_query: Query<
        (&mut Visibility, &mut ZIndex, &mut GlobalZIndex, &BindToID),
        (With<ChoiceLayoutBoxBase>, Without<ChoiceBox>),
    >,
) {
    for (mut state, gen_id) in query.iter_mut() {
        if !state.disabled {
            if !state.focused {
                state.open = false;
            }
        } else {
            state.open = false;
        }

        for (mut root_z, mut root_global_z, root_id) in root_query.iter_mut() {
            if root_id.0 != gen_id.0 {
                continue;
            }
            set_z_index_pair(
                &mut root_z,
                &mut root_global_z,
                state.open,
                CHOICE_BOX_OVERLAY_ROOT_Z,
            );
        }

        apply_overlay_state_for_bind(
            gen_id.0,
            state.open,
            CHOICE_BOX_OVERLAY_CONTENT_Z,
            &mut content_query,
        );
    }
}

/// Enables mouse wheel scrolling for the options inside a [`ChoiceBox`] dropdown.
///
/// This system reads [`MouseWheel`] input and scrolls the child options inside
/// the visible [`ChoiceLayoutBoxBase`]. It applies clamped and smoothed scrolling
/// to maintain a fluid UI experience.
///
/// # Logic:
/// - Only applies scrolling to dropdowns that are currently visible.
/// - Computes scroll offset per frame using an exponential smoothing function.
/// - Applies the offset to each `Node::top` and updates the matching [`WidgetStyle`] styles.
///
/// # Assumptions:
/// - A visible dropdown has at least 3 items; otherwise, scrolling isn't necessary.
/// - Each option is placed vertically with a fixed height (e.g., 50px).
///
/// # Affects:
/// - `Node::top` on [`ChoiceOptionBase`] children
/// - `WidgetStyle::top`
/// Handles mouse wheel scrolling within the dropdown content.
fn handle_scroll_events(
    mut scroll_events: MessageReader<MouseWheel>,
    active_scroll_target: Res<ActiveScrollTarget>,
    mut layout_query: Query<
        (
            Entity,
            &Visibility,
            &Children,
            &mut ScrollPosition,
            &ComputedNode,
            &RelativeCursorPosition,
        ),
        With<ChoiceLayoutBoxBase>,
    >,
    option_query: Query<(&ComputedNode, &ChildOf), With<ChoiceOptionBase>>,
    time: Res<Time>,
) {
    let smooth_factor = 30.0;

    for event in scroll_events.read() {
        for (layout_entity, visibility, children, mut scroll, layout_computed, cursor_pos) in
            layout_query.iter_mut()
        {
            let is_visible = matches!(*visibility, Visibility::Visible | Visibility::Inherited);
            if !is_visible || cursor_pos.normalized.is_none() {
                continue;
            }

            if active_scroll_target.entity != Some(layout_entity) {
                continue;
            }

            let inv_sf = layout_computed.inverse_scale_factor.max(f32::EPSILON);
            // Wheel down -> scroll down -> increase scroll.y
            let delta = -wheel_delta_y(event, inv_sf);

            if children.len() <= 3 {
                scroll.y = 0.0;
                continue;
            }

            // Determine the actual option height from the first option under this layout.
            let option_height = first_child_logical_height(layout_entity, &option_query, 1.0);

            // Fallback if we couldn't find an option size (shouldn't happen).
            let option_h = option_height.unwrap_or(50.0);

            // Visible viewport height (what is clipped). If this comes out too big because
            // the container grows with content, max_scroll becomes too small.
            // If your CSS sets a fixed height, this is fine. Otherwise, we clamp it to "3 options".
            let measured_viewport = (layout_computed.size().y * inv_sf).max(1.0);
            let viewport_h = measured_viewport.min(option_h * 3.0);

            let content_h = children.len() as f32 * option_h;
            let max_scroll = (content_h - viewport_h).max(0.0);

            let target = (scroll.y + delta).clamp(0.0, max_scroll);

            // Smooth interpolation
            let smoothed = scroll.y + (target - scroll.y) * smooth_factor * time.delta_secs();
            scroll.y = smoothed.clamp(0.0, max_scroll);
        }
    }
}

// ===============================================
//                   Intern Events
// ===============================================

// Main Component

/// Handles click events on the [`ChoiceBox`] base widget.
///
/// When the user clicks the widget:
/// - It toggles the open/closed state of the dropdown.
/// - Sets the widget as focused.
/// - Updates [`CurrentWidgetState`] to reflect the focused widget's ID.
///
/// # Triggered By:
/// - `Trigger<Pointer<Click>>`
///
/// # Affects:
/// - `UIWidgetState::focused`
/// - `UIWidgetState::open`
/// - `CurrentWidgetState::widget_id`
/// Handles clicks on the choice box to open or close the dropdown.
fn on_internal_click(
    mut trigger: On<Pointer<Click>>,
    mut query: Query<(&mut UIWidgetState, &UIGenID), With<ChoiceBox>>,
    mut current_widget_state: ResMut<CurrentWidgetState>,
) {
    if let Ok((mut state, gen_id)) = query.get_mut(trigger.entity) {
        state.focused = true;
        state.open = !state.open;
        current_widget_state.widget_id = gen_id.0;
    }

    trigger.propagate(false);
}

/// Sets `hovered = true` on a [`ChoiceBox`] when the cursor enters its area.
///
/// This system is used to update visual states or styles that react to hovering.
///
/// # Triggered By:
/// - `Trigger<Pointer<Over>>`
///
/// # Affects:
/// - `UIWidgetState::hovered`
/// Sets hovered state when the cursor enters the choice box.
fn on_internal_cursor_entered(
    mut trigger: On<Pointer<Over>>,
    mut query: Query<&mut UIWidgetState, With<ChoiceBox>>,
) {
    if let Ok(mut state) = query.get_mut(trigger.entity) {
        state.hovered = true;
    }

    trigger.propagate(false);
}

/// Sets `hovered = false` on a [`ChoiceBox`] when the cursor exits its area.
///
/// # Triggered By:
/// - `Trigger<Pointer<Out>>`
///
/// # Affects:
/// - `UIWidgetState::hovered`
/// Clears hovered state when the cursor leaves the choice box.
fn on_internal_cursor_leave(
    mut trigger: On<Pointer<Out>>,
    mut query: Query<&mut UIWidgetState, With<ChoiceBox>>,
) {
    if let Ok(mut state) = query.get_mut(trigger.entity) {
        state.hovered = false;
    }

    trigger.propagate(false);
}

/// Tracks hover state directly on the dropdown overlay.
fn on_layout_cursor_entered(
    trigger: On<Pointer<Over>>,
    mut query: Query<&mut UIWidgetState, With<ChoiceLayoutBoxBase>>,
    mut active_scroll_target: ResMut<ActiveScrollTarget>,
) {
    if let Ok(mut state) = query.get_mut(trigger.entity) {
        state.hovered = true;
        active_scroll_target.entity = Some(trigger.entity);
    }
}

/// Clears hover state when the cursor leaves the dropdown overlay.
fn on_layout_cursor_leave(
    trigger: On<Pointer<Out>>,
    mut query: Query<&mut UIWidgetState, With<ChoiceLayoutBoxBase>>,
    mut active_scroll_target: ResMut<ActiveScrollTarget>,
) {
    if let Ok(mut state) = query.get_mut(trigger.entity) {
        state.hovered = false;
        clear_active_scroll_target_for_entity(&mut active_scroll_target, trigger.entity);
    }
}

/// Sets hovered state on an option and its immediate visual children.
fn set_option_hover_state(
    entity: Entity,
    hovered: bool,
    query: &mut Query<(&mut UIWidgetState, &Children), With<ChoiceOptionBase>>,
    inner_query: &mut Query<&mut UIWidgetState, Without<ChoiceOptionBase>>,
) {
    if let Ok((mut state, children)) = query.get_mut(entity) {
        state.hovered = hovered;

        for child in children.iter() {
            if let Ok(mut inner_state) = inner_query.get_mut(child) {
                inner_state.hovered = hovered;
            }
        }
    }
}

// Option Component

/// Handles selection logic when a [`ChoiceOptionBase`] is clicked.
///
/// This system:
/// - Updates the selected state across all sibling options (only one is `checked = true`).
/// - Updates the parent [`ChoiceBox`] value with the full clicked option, including typed value.
/// - Closes the dropdown (`open = false`).
/// - Updates any [`SelectedOptionBase`] display widgets with the new value.
/// - Optionally removes focus from the clicked option if no value was selected.
///
/// # Triggered By:
/// - `Trigger<Pointer<Click>>` on a `ChoiceOptionBase`
///
/// # Affects:
/// - `UIWidgetState::checked` on options
/// - `ChoiceBox::value`
/// - `UIWidgetState::open`
/// - `Text` in `SelectedOptionBase`
/// - Optional: `UIWidgetState::focused`
/// Handles clicks on choice box options to update selection.
fn on_internal_option_click(
    mut trigger: On<Pointer<Click>>,
    mut option_query: Query<
        (
            Entity,
            &mut UIWidgetState,
            &ChoiceOption,
            &BindToID,
            &Children,
        ),
        (With<ChoiceOptionBase>, Without<ChoiceBox>),
    >,
    mut parent_query: Query<
        (Entity, &mut UIWidgetState, &UIGenID, &mut ChoiceBox),
        (With<ChoiceBox>, Without<ChoiceOptionBase>),
    >,
    mut selected_query: Query<(&BindToID, &Children), With<SelectedOptionBase>>,
    mut text_query: Query<&mut Text>,
    mut inner_query: Query<&mut UIWidgetState, (Without<ChoiceOptionBase>, Without<ChoiceBox>)>,
    mut active_scroll_target: ResMut<ActiveScrollTarget>,
) {
    let clicked_entity = trigger.entity;

    let (clicked_parent_id, clicked_option) =
        if let Ok((_, _, option, bind_id, _)) = option_query.get(clicked_entity) {
            (bind_id.0, option.clone())
        } else {
            return;
        };

    let clicked_option_text = clicked_option.text.clone();
    let clicked_option_icon = clicked_option.icon_path.clone();

    for (entity, mut state, _, bind_id, children) in option_query.iter_mut() {
        if bind_id.0 == clicked_parent_id {
            state.checked = entity == clicked_entity;

            for child in children.iter() {
                if let Ok(mut inner_state) = inner_query.get_mut(child) {
                    inner_state.checked = state.checked;
                }
            }
        }
    }

    for (_, mut parent_state, id, mut choice_box) in parent_query.iter_mut() {
        if id.0 == clicked_parent_id {
            choice_box.value = clicked_option.clone();
            parent_state.open = false;
            active_scroll_target.entity = None;

            if clicked_option_text.is_empty() && clicked_option_icon.is_none() {
                if let Ok((_, mut state, _, _, _)) = option_query.get_mut(clicked_entity) {
                    state.focused = false;
                }
            }

            for (bind_id, selected_children) in selected_query.iter_mut() {
                if bind_id.0 == clicked_parent_id {
                    for child in selected_children.iter() {
                        if let Ok(mut text) = text_query.get_mut(child) {
                            text.0 = clicked_option_text.clone();
                        }
                    }
                }
            }
        }
    }

    trigger.propagate(false);
}

/// Sets `hovered = true` on a [`ChoiceOptionBase`] and its visual children when hovered.
///
/// Used for hover effects like highlighting or animations.
///
/// # Triggered By:
/// - `Trigger<Pointer<Over>>`
///
/// # Affects:
/// - `UIWidgetState::hovered` on option and visual children
/// Sets hovered state when the cursor enters an option.
fn on_internal_option_cursor_entered(
    trigger: On<Pointer<Over>>,
    mut query: Query<(&mut UIWidgetState, &Children), With<ChoiceOptionBase>>,
    mut inner_query: Query<&mut UIWidgetState, Without<ChoiceOptionBase>>,
) {
    set_option_hover_state(trigger.entity, true, &mut query, &mut inner_query);
}

/// Sets `hovered = false` on a [`ChoiceOptionBase`] and its visual children when unhovered.
///
/// # Triggered By:
/// - `Trigger<Pointer<Out>>`
///
/// # Affects:
/// - `UIWidgetState::hovered` on option and visual children
/// Clears hovered state when the cursor leaves an option.
fn on_internal_option_cursor_leave(
    trigger: On<Pointer<Out>>,
    mut query: Query<(&mut UIWidgetState, &Children), With<ChoiceOptionBase>>,
    mut inner_query: Query<&mut UIWidgetState, Without<ChoiceOptionBase>>,
) {
    set_option_hover_state(trigger.entity, false, &mut query, &mut inner_query);
}

// ===============================================
//                   Child Builder
// ===============================================

/// Spawns the visible child UI elements that represent the currently selected option
/// inside a [`ChoiceBox`] widget.
///
/// This function creates two primary child nodes:
/// 1. **SelectedOptionBase**: A container displaying the selected text.
/// 2. **DropBase**: A container holding the dropdown arrow icon.
///
/// These nodes are styled via CSS classes (`"option-selected"`, `"option-sel-text"`, and `"option-drop-box"`)
/// and tied to the owning widget via [`BindToID`]. They are rendered on the same [`RenderLayers`] level
/// as the parent `ChoiceBox` and ignore pointer interaction via [`Pickable::IGNORE`].
///
/// # Parameters
/// - `builder`: The [`RelatedSpawnerCommands`] to create children in the current entity hierarchy.
/// - `css_source`: A [`CssSource`] reference for applying consistent widget styling.
/// - `choice_box`: The [`ChoiceBox`] from which to derive current selected value and icon.
/// - `layer`: The render layer index for correct UI layering.
/// - `id`: The widget ID used to bind the children to their parent.
/// - `image_cache`: A local image cache to avoid redundant asset loading.
/// - `images`: The global Bevy [`Assets<Image>`] map for dynamically managed textures.
/// - `asset_server`: The [`AssetServer`] for loading icon assets as needed.
///
/// # Spawns:
/// - `SelectedOptionBase`:
///   - Text displaying the selected value (`choice_box.value.text`)
///
/// - `DropBase`:
///   - Icon image from `choice_box.icon_path` or a default fallback
///
/// # Components Added:
/// - [`Name`], [`Node`], [`BackgroundColor`], [`ImageNode`], [`BorderColor`], [`BorderRadius`]
/// - [`UIWidgetState`], [`CssSource`], [`CssClass`], [`RenderLayers`], [`Pickable`], [`BindToID`]
/// - Marker: [`SelectedOptionBase`], [`DropBase`]
/// Spawns the selected option display node.
fn generate_child_selected_option(
    builder: &mut RelatedSpawnerCommands<ChildOf>,
    css_source: &CssSource,
    choice_box: &ChoiceBox,
    layer: &usize,
    id: &usize,
    image_cache: &mut ImageCache,
    images: &mut ResMut<Assets<Image>>,
    asset_server: &Res<AssetServer>,
) {
    // Selected Container
    builder
        .spawn((
            Name::new(format!("Option-Selected-{}", choice_box.entry)),
            Node::default(),
            BackgroundColor::default(),
            ImageNode::default(),
            BorderColor::default(),
            UIWidgetState::default(),
            css_source.clone(),
            CssClass(vec![String::from("option-selected")]),
            RenderLayers::layer(*layer),
            Pickable::IGNORE,
            BindToID(*id),
            SelectedOptionBase,
        ))
        .with_children(|builder| {
            // Selected Text
            builder.spawn((
                Name::new(format!("Option-Sel-Text-{}", choice_box.entry)),
                Text::new(choice_box.value.text.clone()),
                TextColor::default(),
                TextFont::default(),
                TextLayout::default(),
                ZIndex::default(),
                UIWidgetState::default(),
                IgnoreParentState,
                css_source.clone(),
                CssClass(vec![String::from("option-sel-text")]),
                Pickable::IGNORE,
                RenderLayers::layer(*layer),
                BindToID(*id),
            ));
        });

    builder
        .spawn((
            Name::new(format!("Arrow-Box-{}", choice_box.entry)),
            Node::default(),
            BackgroundColor::default(),
            ImageNode::default(),
            BorderColor::default(),
            UIWidgetState::default(),
            css_source.clone(),
            CssClass(vec![String::from("option-drop-box")]),
            RenderLayers::layer(*layer),
            Pickable::IGNORE,
            BindToID(*id),
            DropBase,
        ))
        .with_children(|builder| {
            let handle = get_or_load_image(
                choice_box
                    .icon_path
                    .as_deref()
                    .unwrap_or(DEFAULT_CHOICE_BOX_KEY),
                image_cache,
                images,
                &asset_server,
            );

            builder.spawn((
                Name::new(format!("Drop-Icon-{}", choice_box.entry)),
                ImageNode {
                    image: handle,
                    ..default()
                },
                ZIndex::default(),
                UIWidgetState::default(),
                css_source.clone(),
                CssClass(vec![String::from("option-drop-icon")]),
                Pickable::IGNORE,
                RenderLayers::layer(*layer),
                BindToID(*id),
            ));
        });
}