bevy_gearbox_editor 0.3.3

State machine system for the bevy game engine
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
//! Node editor UI and node management
//! 
//! This module handles:
//! - Rendering the main node editor interface
//! - Converting between node types (Leaf <-> Parent)
//! - Z-ordering and selection management
//! - Node interaction and dragging

use bevy::prelude::*;
use bevy_gearbox::active::Active;
use bevy_gearbox::{InitialState, StateMachine};
use bevy_egui::egui;
use std::collections::HashSet;

use crate::editor_state::{EditorState, StateMachinePersistentData, StateMachineTransientData, NodeDragged, NodeContextMenuRequested, TransitionContextMenuRequested, RenderItem, get_entity_name, should_get_selection_boost, TransitionCreationRequested, CreateTransition, SaveStateMachine, draw_arrow, draw_interactive_pill_label, closest_point_on_rect_edge, get_node_display_color, get_transition_color};
use crate::components::{NodeType, LeafNode, ParentNode};

/// System to update node types based on entity hierarchy
/// 
/// Converts leaf nodes to parent nodes when they gain children,
/// and parent nodes back to leaf nodes when they lose all children.
pub fn update_node_types(
    editor_state: Res<EditorState>,
    mut state_machines: Query<&mut StateMachinePersistentData, With<StateMachine>>,
    parent_query: Query<Entity, With<InitialState>>,
    leaf_query: Query<Entity, Without<InitialState>>,
    children_query: Query<&bevy_gearbox::StateChildren>,
    parallel_query: Query<Entity, With<bevy_gearbox::Parallel>>,
) {
    if let Some(selected_root) = editor_state.selected_machine {
        if let Ok(mut machine_data) = state_machines.get_mut(selected_root) {
        
        // Get all entities in the selected state machine's hierarchy
        let mut descendants: Vec<Entity> = children_query
            .iter_descendants_depth_first(selected_root)
            .collect();
        descendants.insert(0, selected_root); // Include the root
        
        // Process each entity in the hierarchy
        for &entity in &descendants {
            if parent_query.contains(entity) || parallel_query.contains(entity) {
                // Entity should be a parent node
                match machine_data.nodes.get(&entity) {
                    Some(NodeType::Parent(_)) => {
                        // Already a parent node, no change needed
                    }
                    Some(NodeType::Leaf(leaf_node)) => {
                        // Convert leaf to parent
                        let parent_node = ParentNode::new(leaf_node.entity_node.position);
                        machine_data.nodes.insert(entity, NodeType::Parent(parent_node));
                    }
                    None => {
                        // Create new parent node
                        let parent_node = ParentNode::new(egui::Pos2::new(200.0, 100.0));
                        machine_data.nodes.insert(entity, NodeType::Parent(parent_node));
                    }
                }
            } else if leaf_query.contains(entity) {
                // Entity should be a leaf node
                match machine_data.nodes.get(&entity) {
                    Some(NodeType::Leaf(_)) => {
                        // Already a leaf node, no change needed
                    }
                    Some(NodeType::Parent(parent_node)) => {
                        // Convert parent to leaf
                        let leaf_node = LeafNode::new(parent_node.entity_node.position);
                        machine_data.nodes.insert(entity, NodeType::Leaf(leaf_node));
                    }
                    None => {
                        // Create new leaf node
                        let leaf_node = LeafNode::new(egui::Pos2::new(100.0, 100.0));
                        machine_data.nodes.insert(entity, NodeType::Leaf(leaf_node));
                    }
                }
            }
        }
        
        // Remove nodes that are no longer part of the active hierarchy
        let valid_entities: HashSet<Entity> = descendants.into_iter().collect();
        machine_data.nodes.retain(|entity, _| valid_entities.contains(entity));
        }
    }
}

/// Render the node editor interface for a selected state machine
pub fn show_machine_editor(
    ctx: &egui::Context,
    editor_state: &mut EditorState,
    persistent_data: &mut StateMachinePersistentData,
    transient_data: &mut StateMachineTransientData,
    all_entities: &Query<(Entity, Option<&Name>, Option<&InitialState>)>,
    child_of_query: &Query<&bevy_gearbox::StateChildOf>,
    children_query: &Query<&bevy_gearbox::StateChildren>,
    active_query: &Query<&Active>,
    parallel_query: &Query<&bevy_gearbox::Parallel>,
    commands: &mut Commands,
) {
    egui::CentralPanel::default().show(ctx, |ui| {
        // Add back button and save button at the top
        ui.horizontal(|ui| {
            if ui.button("← Back to Machine List").clicked() {
                editor_state.selected_machine = None;
                transient_data.selected_node = None;
            }
            
            if let Some(selected_root) = editor_state.selected_machine {
                let machine_name = get_entity_name(selected_root, all_entities);
                ui.separator();
                ui.label(format!("Editing: {}", machine_name));
                
                ui.separator();
                if ui.button("💾 Save").clicked() {
                    // Trigger save event
                    commands.trigger(SaveStateMachine { entity: selected_root });
                }
            }
        });
        
        ui.separator();
        
        if let Some(selected_root) = editor_state.selected_machine {
            // Build render queue with z-order based on hierarchy depth
            let mut render_queue = Vec::new();
            
            // Get all entities in depth-first order for natural z-ordering
            let mut hierarchy_entities: Vec<Entity> = children_query
                .iter_descendants_depth_first(selected_root)
                .collect();
            hierarchy_entities.insert(0, selected_root);
            
            for (hierarchy_index, entity) in hierarchy_entities.iter().enumerate() {
                if let Some(_node) = persistent_data.nodes.get(entity) {
                    let base_z_order = hierarchy_index as i32 * 10;
                    let selection_boost = if should_get_selection_boost(*entity, transient_data.selected_node, child_of_query) { 
                        5 
                    } else { 
                        0 
                    };
                    
                    render_queue.push(RenderItem {
                        entity: *entity,
                        z_order: base_z_order + selection_boost,
                    });
                }
            }
            
            // Sort by z-order (lower values render first, higher values on top)
            render_queue.sort_by_key(|item| item.z_order);
            
            // Render all nodes in z-order
            for render_item in render_queue {
                let entity = render_item.entity;
                let entity_name = get_entity_name(entity, all_entities);
                
                if let Some(node) = persistent_data.nodes.get_mut(&entity) {
                    let is_selected = transient_data.selected_node == Some(entity);
                    let is_root = selected_root == entity;
                    let is_editing = transient_data.text_editing.is_editing(entity);
                    let should_focus = transient_data.text_editing.should_focus;
                    
                    let first_focus = transient_data.text_editing.first_focus;
                    
                    // Determine node color (active solid gold, else gold->grey pulse)
                    let node_color = Some(get_node_display_color(entity, active_query, &transient_data.node_pulses));
                    
                    let response = match node {
                        NodeType::Leaf(leaf_node) => {
                            let dotted = is_direct_child_of_parallel(entity, child_of_query, parallel_query);
                            leaf_node.show_with_border_style(
                                ui, 
                                &entity_name, 
                                Some(&format!("{:?}", entity)), 
                                is_selected, 
                                is_editing, 
                                &mut transient_data.text_editing.current_text, 
                                should_focus, 
                                first_focus, 
                                node_color, 
                                dotted,
                            )
                        }
                        NodeType::Parent(parent_node) => {
                            let dotted = is_direct_child_of_parallel(entity, child_of_query, parallel_query);
                            parent_node.show_with_border_style(
                                ui, 
                                &entity_name, 
                                Some(&format!("{:?}", entity)), 
                                is_selected, 
                                is_root, 
                                is_editing, 
                                &mut transient_data.text_editing.current_text, 
                                should_focus, 
                                first_focus, 
                                node_color, 
                                dotted,
                            )
                        }
                    };
                    
                    // Clear focus flag after first frame
                    if should_focus {
                        transient_data.text_editing.should_focus = false;
                    }
                    
                    // Clear first focus flag after it's been used
                    if first_focus {
                        transient_data.text_editing.first_focus = false;
                    }
                    
                    // Handle selection
                    if response.clicked {
                        // Check if we're in transition creation mode and waiting for target selection
                        if transient_data.transition_creation.awaiting_target_selection {
                            let pointer_pos = ui.input(|i| i.pointer.hover_pos().unwrap_or_default());
                            transient_data.transition_creation.set_target(entity, pointer_pos);
                        } else {
                            transient_data.selected_node = Some(entity);
                        }
                    }
                    
                    // Handle + button click for transition creation (leaf nodes only)
                    if response.add_transition_clicked {
                        commands.trigger(TransitionCreationRequested {
                            source_entity: entity,
                        });
                    }
                    
                    // Handle right-click context menu
                    if response.right_clicked {
                        let pointer_pos = ui.input(|i| i.pointer.hover_pos().unwrap_or_default());
                        commands.trigger(NodeContextMenuRequested {
                            entity,
                            position: pointer_pos,
                        });
                    }
                    
                    // Handle dragging
                    if response.dragged {
                        // Node was dragged - position is automatically updated in the component
                        // Emit event to handle parent-child movement
                        commands.trigger(NodeDragged {
                            entity,
                            drag_delta: response.drag_delta,
                        });
                    }
                }
            }
            
            // Update transition rectangles before rendering
            update_transition_rectangles(persistent_data, child_of_query);
            
            // Render transition arrows after all nodes
            render_transition_connections(ui, persistent_data, transient_data, child_of_query, commands);
            
            // Render initial state indicators
            render_initial_state_indicators(ui, persistent_data, &all_entities, selected_root);
            
            // Handle background clicks to cancel transition creation
            if transient_data.transition_creation.awaiting_target_selection {
                // Check for clicks on background (not handled by any node)
                if ui.input(|i| i.pointer.primary_clicked()) {
                    let pointer_pos = ui.input(|i| i.pointer.hover_pos().unwrap_or_default());
                    let clicked_on_node = persistent_data.nodes.values().any(|node| {
                        node.current_rect().contains(pointer_pos)
                    });
                    
                    if !clicked_on_node {
                        transient_data.transition_creation.cancel();
                    }
                }
            }
        } else {
            ui.label("No state machine selected");
        }
        
        // Handle text editing completion
        handle_text_editing_completion(ui, transient_data, commands);
        
        // Render transition creation UI
        render_transition_creation_ui(ui, persistent_data, transient_data, commands);
    });
}

/// Render the transition creation dropdown UI
fn render_transition_creation_ui(
    ui: &mut egui::Ui,
    persistent_data: &mut StateMachinePersistentData,
    transient_data: &mut StateMachineTransientData,
    commands: &mut Commands,
) {
    // Show visual arrow from source to mouse if we're waiting for target selection
    if transient_data.transition_creation.awaiting_target_selection {
        if let Some(source) = transient_data.transition_creation.source_entity {
            // Draw arrow from source entity to mouse cursor
            if let Some(source_node) = persistent_data.nodes.get(&source) {
                let mouse_pos = ui.input(|i| i.pointer.hover_pos().unwrap_or_default());
                let source_rect = source_node.current_rect();
                
                // Draw from the edge of the source node to the mouse cursor
                let source_edge = closest_point_on_rect_edge(source_rect, mouse_pos);
                
                // Draw a dashed line from source edge to mouse (white color)
                let painter = ui.painter();
                draw_dashed_arrow(&painter, source_edge, mouse_pos, egui::Color32::WHITE);
            }
            
            // Check for cancellation via right-click, escape key, or clicking background
            if ui.input(|i| {
                i.pointer.secondary_clicked() || // Right click
                i.key_pressed(egui::Key::Escape) // Escape key
            }) {
                transient_data.transition_creation.cancel();
            }
        }
    }
    
    // Show event type dropdown
    if transient_data.transition_creation.show_event_dropdown {
        if let (Some(source), Some(target), Some(position)) = (
            transient_data.transition_creation.source_entity,
            transient_data.transition_creation.target_entity,
            transient_data.transition_creation.dropdown_position,
        ) {
            let dropdown_id = egui::Id::new("transition_event_dropdown");
            
            egui::Area::new(dropdown_id)
                .fixed_pos(position)
                .order(egui::Order::Foreground)
                .show(ui.ctx(), |ui| {
                    egui::Frame::popup(ui.style())
                        .show(ui, |ui| {
                            ui.set_min_width(200.0);
                            ui.heading("Select Event Type");
                            ui.separator();
                            
                            if transient_data.transition_creation.available_event_types.is_empty() {
                                ui.label("No EventEdge event types found.");
                                ui.label("Make sure event types are registered with the type registry.");
                            } else {
                                for event_type in &transient_data.transition_creation.available_event_types.clone() {
                                    if ui.button(event_type).clicked() {
                                        commands.trigger(CreateTransition {
                                            source_entity: source,
                                            target_entity: target,
                                            event_type: event_type.clone(),
                                        });
                                    }
                                }
                            }
                            
                            ui.separator();
                            if ui.button("Cancel").clicked() {
                                transient_data.transition_creation.cancel();
                            }
                        });
                });
            
            // Close dropdown if clicked elsewhere
            if ui.input(|i| i.pointer.any_click()) {
                let pointer_pos = ui.input(|i| i.pointer.hover_pos().unwrap_or_default());
                let dropdown_rect = egui::Rect::from_min_size(position, egui::Vec2::new(200.0, 150.0));
                
                if !dropdown_rect.contains(pointer_pos) {
                    transient_data.transition_creation.cancel();
                }
            }
        }
    }
}

/// Render visual connections for existing transitions
fn render_transition_connections(
    ui: &mut egui::Ui,
    persistent_data: &mut StateMachinePersistentData,
    transient_data: &StateMachineTransientData,
    child_of_query: &Query<&bevy_gearbox::StateChildOf>,
    commands: &mut Commands,
) {
    // Extract data needed for rendering to avoid borrowing issues
    let transitions_data: Vec<_> = persistent_data.visual_transitions.iter().enumerate().map(|(index, transition)| {
        let transition_color = get_transition_color(
            transition.source_entity, 
            transition.target_entity, 
            &transient_data.transition_pulses
        );
        (index, 
         transition.calculate_two_segment_points(),
         transition.event_node_position,
         transition.event_type.clone(),
         transition.is_dragging_event_node,
         transition_color)
    }).collect();
    
    let painter = ui.painter();
    let mut interaction_data = Vec::new();
    
    // First pass: Draw all the arrows (using painter)
    for (index, (source_start, source_end, target_start, target_end), event_pos, _event_type, _is_dragging, _color) in &transitions_data {
        let tconn = &persistent_data.visual_transitions[*index];
        let source_rect = tconn.source_rect;
        let is_ancestor = is_ancestor_of(tconn.source_entity, tconn.target_entity, child_of_query);
        if is_ancestor {
            // Curved segment from parent to event node, straight segment from event node to target
            draw_fish_hook_to_point(&painter, source_rect, *event_pos, egui::Color32::WHITE);
            draw_arrow(&painter, *event_pos, *target_end, egui::Color32::WHITE);
        } else {
            // Default two-segment
            draw_arrow(&painter, *source_start, *source_end, egui::Color32::WHITE);
            draw_arrow(&painter, *target_start, *target_end, egui::Color32::WHITE);
        }
    }
    
    // Second pass: Draw interactive event nodes (using ui mutably)
    for (index, (_source_start, _source_end, _target_start, _target_end), event_pos, event_type, is_dragging, color) in transitions_data {
        // Draw the interactive event node (keep existing placement for now)
        let font_id = egui::FontId::new(12.0, egui::FontFamily::Proportional);
        let response = draw_interactive_pill_label(ui, event_pos, &event_type, font_id, is_dragging, color);
        
        // Store interaction data for later processing
        interaction_data.push((index, response));
    }
    
    // Process interactions after rendering
    for (index, response) in interaction_data {
        let transition = &mut persistent_data.visual_transitions[index];
        
        // Handle right-click context menu
        if response.secondary_clicked() {
            let pointer_pos = ui.input(|i| i.pointer.hover_pos().unwrap_or_default());
            commands.trigger(TransitionContextMenuRequested {
                source_entity: transition.source_entity,
                target_entity: transition.target_entity,
                event_type: transition.event_type.clone(),
                position: pointer_pos,
            });
        }
        
        // Handle event node dragging
        if response.drag_started() {
            transition.is_dragging_event_node = true;
        }
        
        if response.dragged() && transition.is_dragging_event_node {
            transition.event_node_position += response.drag_delta();
        }
        
        if response.drag_stopped() {
            transition.is_dragging_event_node = false;
            // Update the offset based on the new position
            transition.update_event_node_offset();
        }
    }
}

fn is_direct_child_of_parallel(
    entity: Entity,
    child_of_query: &Query<&bevy_gearbox::StateChildOf>,
    parallel_query: &Query<&bevy_gearbox::Parallel>,
) -> bool {
    if let Ok(child_of) = child_of_query.get(entity) {
        return parallel_query.get(child_of.0).is_ok();
    }
    false
}

/// Update the rectangles in visual transitions to match current node positions
fn update_transition_rectangles(
    persistent_data: &mut StateMachinePersistentData,
    child_of_query: &Query<&bevy_gearbox::StateChildOf>,
) {
    // Snapshot node rects first to avoid borrow conflicts
    let mut node_rects: std::collections::HashMap<Entity, egui::Rect> = std::collections::HashMap::new();
    for (entity, node) in &persistent_data.nodes {
        node_rects.insert(*entity, node.current_rect());
    }
    
    for transition in &mut persistent_data.visual_transitions {
        if let Some(r) = node_rects.get(&transition.source_entity) { transition.source_rect = *r; }
        if let Some(r) = node_rects.get(&transition.target_entity) { transition.target_rect = *r; }
        
        // Update event node position based on new source/target positions (unless being dragged)
        if !transition.is_dragging_event_node {
            transition.update_event_node_position();
            // Constrain while auto-moving due to connected state movement
            constrain_event_node_position(transition, &node_rects, child_of_query);
        }
    }
}

fn constrain_event_node_position(
    transition: &mut crate::TransitionConnection,
    node_rects: &std::collections::HashMap<Entity, egui::Rect>,
    child_of_query: &Query<&bevy_gearbox::StateChildOf>,
) {
    // Determine which end is higher in the hierarchy
    let source_depth = hierarchy_depth_from_pairs(transition.source_entity, child_of_query);
    let target_depth = hierarchy_depth_from_pairs(transition.target_entity, child_of_query);
    let higher = if source_depth <= target_depth { transition.source_entity } else { transition.target_entity };
    let other = if higher == transition.source_entity { transition.target_entity } else { transition.source_entity };
    let is_direct_child = match child_of_query.get(other) { Ok(rel) => rel.0 == higher, Err(_) => false };
    let parent_for_pill = if is_direct_child { higher } else if let Ok(rel) = child_of_query.get(higher) { rel.0 } else { higher };
    if let Some(parent_rect) = node_rects.get(&parent_for_pill) {
        // Reconstruct an approximate ParentNode content rect assumptions are required here;
        // since we only stored the whole rect, approximate content by shrinking top bar and margins
        // Use a small heuristic: treat top 30px as title bar (matches ParentNode default)
        let content_rect = egui::Rect::from_min_max(
            egui::Pos2::new(parent_rect.min.x, parent_rect.min.y + 30.0),
            parent_rect.max,
        );
        let margin = egui::Vec2::new(10.0, 10.0);
        let pill_half = egui::Vec2::new(45.0, 12.0);
        let min_allowed = content_rect.min + margin + pill_half;
        let max_allowed = content_rect.max - margin - pill_half;
        if min_allowed.x <= max_allowed.x && min_allowed.y <= max_allowed.y {
            transition.event_node_position = egui::Pos2::new(
                transition.event_node_position.x.clamp(min_allowed.x, max_allowed.x),
                transition.event_node_position.y.clamp(min_allowed.y, max_allowed.y),
            );
        }
    }
}

/// Handle text editing completion (Enter key or click outside)
fn handle_text_editing_completion(
    ui: &mut egui::Ui,
    transient_data: &mut StateMachineTransientData,
    commands: &mut Commands,
) {
    if transient_data.text_editing.editing_entity.is_some() {
        let should_complete = ui.input(|i| {
            // Complete on Enter key
            i.key_pressed(egui::Key::Enter) ||
            // Complete on Escape key (cancel)
            i.key_pressed(egui::Key::Escape) ||
            // Complete when clicking outside
            i.pointer.any_click()
        });
        
        let is_escape = ui.input(|i| i.key_pressed(egui::Key::Escape));
        
        if should_complete {
            if is_escape {
                transient_data.text_editing.cancel_editing();
            } else if let Some((entity, new_name)) = transient_data.text_editing.stop_editing() {
                // Update the entity's name if it's not empty
                let trimmed_name = new_name.trim();
                if !trimmed_name.is_empty() {
                    commands.entity(entity).insert(Name::new(trimmed_name.to_string()));
                } else {
                    info!("⚠️ Ignoring empty name for entity {:?}", entity);
                }
            }
        }
    }
}

/// Render initial state indicators (circle + arrow) for entities marked as InitialState
fn render_initial_state_indicators(
    ui: &mut egui::Ui,
    persistent_data: &StateMachinePersistentData,
    all_entities: &Query<(Entity, Option<&Name>, Option<&InitialState>)>,
    selected_root: Entity,
) {
    let painter = ui.painter();
    
    // Find all entities with InitialState component that belong to the current state machine
    for (parent_entity, _name, initial_state_opt) in all_entities.iter() {
        if let Some(initial_state) = initial_state_opt {
            let target_entity = initial_state.0;
            
            // Only render if both parent and target are in our editor nodes and belong to current state machine
            if let (Some(_parent_node), Some(target_node)) = (
                persistent_data.nodes.get(&parent_entity),
                persistent_data.nodes.get(&target_entity)
            ) {
                // Check if this belongs to the currently selected state machine
                // (We can do this by checking if the parent entity is a child of selected_root or is selected_root)
                let belongs_to_current_machine = parent_entity == selected_root || 
                    all_entities.iter().any(|(entity, _, _)| {
                        entity == selected_root && 
                        // This is a simplified check - in a real implementation you'd traverse the hierarchy
                        true // For now, assume all nodes in persistent_data.nodes belong to current machine
                    });
                
                if belongs_to_current_machine {
                    render_initial_state_indicator(
                        &painter,
                        target_node.current_rect(),
                    );
                }
            }
        }
    }
}

/// Render a single initial state indicator (circle + curved arrow)
fn render_initial_state_indicator(
    painter: &egui::Painter,
    target_rect: egui::Rect,
) {
    // Circle position: to the left and lower relative to target node (moved 6px right)
    let circle_offset = egui::Vec2::new(-13.0, 1.0);
    let circle_center = target_rect.left_top() + circle_offset;
    let circle_radius = 3.0;
    
    // Draw the circle (white)
    painter.circle_filled(
        circle_center,
        circle_radius,
        egui::Color32::WHITE,
    );
    
    // Draw circle border (slightly darker white/light gray)
    painter.circle_stroke(
        circle_center,
        circle_radius,
        egui::Stroke::new(1.5, egui::Color32::from_rgb(200, 200, 200)),
    );
    
    // Calculate curved arrow that hits the left side at 16px from top
    let arrow_start = circle_center + egui::Vec2::new(0.0, circle_radius); // Bottom of circle
    let arrow_end = egui::Pos2::new(target_rect.left(), target_rect.top() + 16.0); // 16px from top
    
    // Create a curved path using quadratic bezier
    // Control point creates the curve - positioned to make arrow go down then right
    let control_point = egui::Pos2::new(
        arrow_start.x, // Keep at same horizontal position as start
        arrow_start.y + (arrow_end.y - arrow_start.y) * 0.7, // 70% of the way vertically
    );
    
    // Draw curved arrow using multiple line segments to approximate bezier curve
    let segments = 12;
    let mut prev_point = arrow_start;
    
    for i in 1..=segments {
        let t = i as f32 / segments as f32;
        let current_point = quadratic_bezier(arrow_start, control_point, arrow_end, t);
        
        painter.line_segment(
            [prev_point, current_point],
            egui::Stroke::new(2.0, egui::Color32::WHITE),
        );
        
        prev_point = current_point;
    }
    
    // Draw arrowhead pointing horizontally (perpendicular to left side)
    let arrowhead_size = 4.0;
    let arrowhead_direction = egui::Vec2::new(1.0, 0.0); // Point right (into the node)
    let perpendicular = egui::Vec2::new(0.0, 1.0); // Vertical perpendicular
    
    let arrowhead_point1 = arrow_end - arrowhead_direction * arrowhead_size + perpendicular * (arrowhead_size * 0.5);
    let arrowhead_point2 = arrow_end - arrowhead_direction * arrowhead_size - perpendicular * (arrowhead_size * 0.5);
    
    painter.line_segment(
        [arrow_end, arrowhead_point1],
        egui::Stroke::new(2.0, egui::Color32::WHITE),
    );
    painter.line_segment(
        [arrow_end, arrowhead_point2],
        egui::Stroke::new(2.0, egui::Color32::WHITE),
    );
}

/// Calculate a point on a quadratic bezier curve
fn quadratic_bezier(start: egui::Pos2, control: egui::Pos2, end: egui::Pos2, t: f32) -> egui::Pos2 {
    let one_minus_t = 1.0 - t;
    let one_minus_t_sq = one_minus_t * one_minus_t;
    let t_sq = t * t;
    
    egui::Pos2::new(
        one_minus_t_sq * start.x + 2.0 * one_minus_t * t * control.x + t_sq * end.x,
        one_minus_t_sq * start.y + 2.0 * one_minus_t * t * control.y + t_sq * end.y,
    )
}

/// Draw a dashed arrow from start to end position
fn draw_dashed_arrow(painter: &egui::Painter, start: egui::Pos2, end: egui::Pos2, color: egui::Color32) {
    let direction = end - start;
    let distance = direction.length();
    
    if distance < 1.0 {
        return; // Too short to draw
    }
    
    let normalized_direction = direction / distance;
    let dash_length = 8.0;
    let gap_length = 4.0;
    let dash_and_gap = dash_length + gap_length;
    
    // Draw dashed line
    let mut current_distance = 0.0;
    while current_distance < distance {
        let dash_start = start + normalized_direction * current_distance;
        let dash_end_distance = (current_distance + dash_length).min(distance);
        let dash_end = start + normalized_direction * dash_end_distance;
        
        painter.line_segment(
            [dash_start, dash_end],
            egui::Stroke::new(2.0, color),
        );
        
        current_distance += dash_and_gap;
    }
    
    // Draw arrowhead at the end
    let arrowhead_size = 6.0;
    let perpendicular = egui::Vec2::new(-normalized_direction.y, normalized_direction.x);
    
    let arrowhead_point1 = end - normalized_direction * arrowhead_size + perpendicular * (arrowhead_size * 0.5);
    let arrowhead_point2 = end - normalized_direction * arrowhead_size - perpendicular * (arrowhead_size * 0.5);
    
    painter.line_segment(
        [end, arrowhead_point1],
        egui::Stroke::new(2.0, color),
    );
    painter.line_segment(
        [end, arrowhead_point2],
        egui::Stroke::new(2.0, color),
    );
}

fn is_ancestor_of(source: Entity, target: Entity, child_of_query: &Query<&bevy_gearbox::StateChildOf>) -> bool {
    let mut current = target;
    while let Ok(child_of) = child_of_query.get(current) {
        if child_of.0 == source {
            return true;
        }
        current = child_of.0;
    }
    false
}

fn draw_fish_hook_to_point(
    painter: &egui::Painter,
    parent_rect: egui::Rect,
    event_pos: egui::Pos2,
    color: egui::Color32,
) {
    // p0: closest point on parent's edge to the event position
    let p0 = closest_point_on_rect_edge(parent_rect, event_pos);

    // Direction from event toward p0
    let mut dir = p0 - event_pos;
    let len = dir.length();
    if len > 1e-3 { dir /= len; } else { dir = egui::Vec2::new(1.0, 0.0); }

    // p1: extend beyond p0 by 10px along dir
    let p1 = p0 + dir * 10.0;

    // p2: perpendicular from p1 by ~10px
    let perp = egui::Vec2::new(-dir.y, dir.x);
    let p2 = p1 + perp * 10.0;

    // p3: from p2 back towards the event by 10px (opposite dir)
    let p3 = p2 - dir * 10.0;

    // Curve to p3, then straight line to event_pos (no arrow here; arrow on final segment to target)
    draw_cubic_bezier(painter, p0, p1, p2, p3, color);
    painter.line_segment([p3, event_pos], egui::Stroke::new(2.0, color));
}

fn draw_cubic_bezier(
    painter: &egui::Painter,
    p0: egui::Pos2,
    p1: egui::Pos2,
    p2: egui::Pos2,
    p3: egui::Pos2,
    color: egui::Color32,
) {
    let segments = 24;
    let mut prev = p0;
    for i in 1..=segments {
        let t = i as f32 / segments as f32;
        let pt = cubic_bezier_point(p0, p1, p2, p3, t);
        painter.line_segment([prev, pt], egui::Stroke::new(2.0, color));
        prev = pt;
    }
}

fn cubic_bezier_point(p0: egui::Pos2, p1: egui::Pos2, p2: egui::Pos2, p3: egui::Pos2, t: f32) -> egui::Pos2 {
    let u = 1.0 - t;
    let uu = u * u;
    let uuu = uu * u;
    let tt = t * t;
    let ttt = tt * t;
    let x = uuu * p0.x + 3.0 * uu * t * p1.x + 3.0 * u * tt * p2.x + ttt * p3.x;
    let y = uuu * p0.y + 3.0 * uu * t * p1.y + 3.0 * u * tt * p2.y + ttt * p3.y;
    egui::Pos2::new(x, y)
}

fn hierarchy_depth_from_pairs(mut entity: Entity, child_of_query: &Query<&bevy_gearbox::StateChildOf>) -> usize {
    let mut depth = 0;
    while let Ok(rel) = child_of_query.get(entity) {
        depth += 1;
        entity = rel.0;
    }
    depth
}