turbo-vision 2.3.1

A Rust implementation of the classic Borland Turbo Vision text-mode UI framework
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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
// (C) 2025 - Enzo Lombardi

//! Group view - container for managing multiple child views with focus handling.

use super::view::{View, ViewId, write_line_to_terminal};
use crate::core::draw::DrawBuffer;
use crate::core::event::{Event, EventType, KB_SHIFT_TAB, KB_TAB};
use crate::core::geometry::Rect;
use crate::core::palette::Attr;
use crate::terminal::Terminal;

/// Group - a container for child views
/// Matches Borland: TGroup (tgroup.h/tgroup.cc)
pub struct Group {
    bounds: Rect,
    children: Vec<Box<dyn View>>,
    view_ids: Vec<ViewId>, // Parallel vec storing ID for each child
    focused: usize,
    background: Option<Attr>,
    end_state: crate::core::command::CommandId, // For execute() event loop (Borland: endState)
    palette_chain: Option<crate::core::palette_chain::PaletteChainNode>,
    /// Grow mode of this Group itself when nested inside another Group
    /// (Borland: TView::growMode)
    grow_mode: crate::core::state::GrowFlags,
}

impl Group {
    pub fn new(bounds: Rect) -> Self {
        Self {
            bounds,
            children: Vec::new(),
            view_ids: Vec::new(),
            focused: 0,
            background: None,
            end_state: 0,
            palette_chain: None,
            grow_mode: 0,
        }
    }

    pub fn with_background(bounds: Rect, background: Attr) -> Self {
        Self {
            bounds,
            children: Vec::new(),
            view_ids: Vec::new(),
            focused: 0,
            background: Some(background),
            end_state: 0,
            palette_chain: None,
            grow_mode: 0,
        }
    }

    /// Set the grow mode of a child by index (Borland: child->growMode = ...).
    ///
    /// Convenience for callers that add children whose concrete type does not
    /// override `set_grow_mode()` — the call is then a no-op, matching the
    /// trait default.
    pub fn set_child_grow_mode(&mut self, index: usize, grow_mode: crate::core::state::GrowFlags) {
        if index < self.children.len() {
            self.children[index].set_grow_mode(grow_mode);
        }
    }

    pub fn add(&mut self, mut view: Box<dyn View>) -> ViewId {
        // Convert child's bounds from relative to absolute coordinates
        // Child bounds are specified relative to this Group's interior
        let child_bounds = view.bounds();
        let absolute_bounds = Rect::new(
            self.bounds.a.x + child_bounds.a.x,
            self.bounds.a.y + child_bounds.a.y,
            self.bounds.a.x + child_bounds.b.x,
            self.bounds.a.y + child_bounds.b.y,
        );
        view.set_bounds(absolute_bounds);

        let view_id = ViewId::new();
        self.children.push(view);
        self.view_ids.push(view_id);
        view_id
    }

    pub fn set_initial_focus(&mut self) {
        if self.children.is_empty() {
            return;
        }

        // Find first focusable child and set focus
        for i in 0..self.children.len() {
            if self.children[i].can_focus() {
                self.focused = i;
                self.children[i].set_focus(true);
                break;
            }
        }
    }

    pub fn clear_all_focus(&mut self) {
        for child in &mut self.children {
            child.set_focus(false);
        }
    }

    pub fn len(&self) -> usize {
        self.children.len()
    }

    pub fn is_empty(&self) -> bool {
        self.children.is_empty()
    }

    pub fn child_at(&self, index: usize) -> &dyn View {
        &*self.children[index]
    }

    pub fn child_at_mut(&mut self, index: usize) -> &mut dyn View {
        &mut *self.children[index]
    }

    pub fn set_focus_to(&mut self, index: usize) {
        if index < self.children.len() && self.children[index].can_focus() {
            self.clear_all_focus();
            self.focused = index;
            self.children[index].set_focus(true);
        }
    }

    /// Focus a child view by its ViewId
    /// Returns true if the view was found and focused, false otherwise
    pub fn focus_by_view_id(&mut self, view_id: ViewId) -> bool {
        if let Some(index) = self.view_ids.iter().position(|&id| id == view_id) {
            if self.children[index].can_focus() {
                self.clear_all_focus();
                self.focused = index;
                self.children[index].set_focus(true);
                return true;
            }
        }
        false
    }

    /// Bring a child view to the front (top of z-order)
    /// Matches Borland: TGroup::selectView() which reorders views
    /// Returns the new index of the moved child
    pub fn bring_to_front(&mut self, index: usize) -> usize {
        if index >= self.children.len() || index == self.children.len() - 1 {
            // Already at front or invalid index
            return index;
        }

        // Remove the view and its corresponding ID from their current position
        let view = self.children.remove(index);
        let view_id = self.view_ids.remove(index);

        // Add them to the end (front of z-order)
        self.children.push(view);
        self.view_ids.push(view_id);

        // Update focused index if necessary
        let new_index = self.children.len() - 1;
        if self.focused == index {
            self.focused = new_index;
        } else if self.focused > index {
            // Focused view shifted down by one
            self.focused -= 1;
        }

        new_index
    }

    /// Send a child view to the back (bottom of z-order, but after index 0)
    /// Matches Borland: current->putInFrontOf(background) for window cycling
    /// Returns the new index of the moved child (always 1 for desktop windows)
    pub fn send_to_back(&mut self, index: usize) -> usize {
        if index >= self.children.len() || index == 1 {
            // Already at back (position 1) or invalid index
            return index;
        }

        // Remove the view and its corresponding ID from their current position
        let view = self.children.remove(index);
        let view_id = self.view_ids.remove(index);

        // Insert them at position 1 (right after element 0, which is typically background)
        self.children.insert(1, view);
        self.view_ids.insert(1, view_id);

        // Update focused index if necessary
        if self.focused == index {
            self.focused = 1;
        } else if self.focused >= 1 && self.focused < index {
            // Views between positions 1 and index shifted up by one
            self.focused += 1;
        }

        1 // Always returns 1 (the back position after index 0)
    }

    /// Get the ViewId of a child at the given index.
    /// Returns None if the index is out of bounds.
    pub fn view_id_at(&self, index: usize) -> Option<ViewId> {
        self.view_ids.get(index).copied()
    }

    /// Remove a child at the specified index
    /// Matches Borland: TGroup::remove(TView *p) or TGroup::shutDown()
    pub fn remove(&mut self, index: usize) {
        if index < self.children.len() {
            let removed_focused = self.focused == index;
            self.children.remove(index);
            // `view_ids` is a parallel vec — must stay in lock-step with
            // `children`. Forgetting it leaves stale ids that point past the
            // end of `children`, so `child_by_id` indexes out of bounds.
            if index < self.view_ids.len() {
                self.view_ids.remove(index);
            }

            // Update focused index if needed
            if self.focused >= index && self.focused > 0 {
                self.focused -= 1;
            }

            // If we removed the last child, clear focus
            if self.children.is_empty() {
                self.focused = 0;
            } else if removed_focused {
                // The focused child was removed: re-establish focus on the
                // nearest focusable child so focus isn't silently lost.
                // Matches Borland: TGroup::remove() → resetCurrent()/focusNext.
                let len = self.children.len();
                let start = self.focused.min(len - 1);
                for k in 0..len {
                    let idx = (start + k) % len;
                    if self.children[idx].can_focus() {
                        self.focused = idx;
                        self.children[idx].set_focus(true);
                        break;
                    }
                }
            }
        }
    }

    /// Get an immutable reference to a child by its ViewId
    /// Returns None if the ViewId is not found
    pub fn child_by_id(&self, view_id: ViewId) -> Option<&dyn View> {
        self.view_ids
            .iter()
            .position(|&id| id == view_id)
            .map(|index| &*self.children[index])
    }

    /// Get a mutable reference to a child by its ViewId
    /// Returns None if the ViewId is not found
    pub fn child_by_id_mut(&mut self, view_id: ViewId) -> Option<&mut (dyn View + '_)> {
        if let Some(index) = self.view_ids.iter().position(|&id| id == view_id) {
            Some(&mut *self.children[index])
        } else {
            None
        }
    }

    /// Remove a child by its ViewId
    /// Returns true if a child was found and removed, false otherwise
    pub fn remove_by_id(&mut self, view_id: ViewId) -> bool {
        if let Some(index) = self.view_ids.iter().position(|&id| id == view_id) {
            // `remove()` already keeps `children` and `view_ids` in lock-step,
            // so we must NOT remove from `view_ids` again here — doing so drops
            // the wrong (now-shifted) id and can index out of bounds.
            self.remove(index);
            true
        } else {
            false
        }
    }

    /// Execute a modal event loop
    /// Matches Borland: TGroup::execute() (tgroup.cc:182-195)
    ///
    /// This is the KEY method that makes modal views work.
    /// In Borland, TGroup has an execute() method with an event loop that calls
    /// getEvent() and handleEvent() until endState is set by endModal().
    ///
    /// The event loop:
    /// 1. Calls app.get_event() which handles drawing and returns events
    /// 2. Calls self.handle_event() to process the event
    /// 3. Continues until end_state is set (by endModal)
    ///
    /// This is used by Dialog, Window, and any other container that needs
    /// modal execution.
    pub fn execute(
        &mut self,
        app: &mut crate::app::Application,
    ) -> crate::core::command::CommandId {
        self.end_state = 0;

        loop {
            // Get event from Application (which handles drawing)
            // Matches Borland: TGroup::execute() calls getEvent(e)
            if let Some(mut event) = app.get_event() {
                // Handle the event
                // Matches Borland: TGroup::execute() calls handleEvent(e)
                self.handle_event(&mut event);
            }

            // Check if we should end the modal loop
            // Matches Borland: while( endState == 0 )
            // IMPORTANT: This must be OUTSIDE the event check, so we check
            // end_state even when there are no events (timeout)
            if self.end_state != 0 {
                // Matches Borland: do { ... } while( !valid(endState) ) —
                // a failing validator vetoes the close and re-enters the loop
                let end_state = self.end_state;
                if self.valid(end_state) {
                    break;
                }
                self.end_state = 0;
            }
        }

        self.end_state
    }

    /// End the modal event loop with a result code
    /// Matches Borland: TView::endModal(ushort command) (tview.cc:391-395)
    ///
    /// In Borland, views call endModal() to set endState and break out of
    /// the execute() event loop. This is typically called in response to
    /// button clicks (CM_OK, CM_CANCEL, etc.)
    pub fn end_modal(&mut self, command: crate::core::command::CommandId) {
        self.end_state = command;
    }

    /// Get the current end_state
    /// Used by containers that implement their own execute() loop
    /// to check if they should end the modal loop
    pub fn get_end_state(&self) -> crate::core::command::CommandId {
        self.end_state
    }

    /// Set the current end_state
    /// Used by modal views to signal they want to close
    pub fn set_end_state(&mut self, command: crate::core::command::CommandId) {
        self.end_state = command;
    }

    /// Broadcast an event to all children except the owner
    /// Matches Borland: TGroup::forEach with message() that takes receiver parameter
    ///
    /// The owner parameter prevents the broadcast from echoing back to the originator.
    /// This is essential for focus-list navigation commands and other broadcast patterns
    /// where the sender shouldn't receive its own message.
    ///
    /// # Arguments
    /// * `event` - The event to broadcast (typically EventType::Broadcast)
    /// * `owner_index` - Optional index of the child that originated the broadcast (will be skipped)
    ///
    /// # Reference
    /// Borland's message() function: `local-only/borland-tvision/include/tv/tvutil.h`
    /// TGroup::forEach pattern: `local-only/borland-tvision/classes/tgroup.cc:675-689`
    pub fn broadcast(&mut self, event: &mut Event, owner_index: Option<usize>) {
        for (i, child) in self.children.iter_mut().enumerate() {
            // Skip the owner if specified
            if let Some(owner) = owner_index {
                if i == owner {
                    continue;
                }
            }

            // Send event to this child
            // Note: Child handle_event may clear or transform the event
            // So we need to check if it's still active before continuing
            child.handle_event(event);

            // If event was cleared, stop broadcasting
            if event.what == EventType::Nothing {
                break;
            }
        }
    }

    /// Draw views starting from a specific index
    /// Used for Borland's drawUnderRect pattern where we only redraw views
    /// that come after (on top of) a moved view
    /// Matches Borland: TGroup::drawSubViews(TView *p, TView *bottom)
    pub fn draw_sub_views(&mut self, terminal: &mut Terminal, start_index: usize, clip: Rect) {
        // Set clip region to the affected area
        terminal.push_clip(clip);

        // Draw all children from start_index onwards that intersect the clip region
        for i in start_index..self.children.len() {
            let child_bounds = self.children[i].bounds();
            if clip.intersects(&child_bounds) {
                self.children[i].draw(terminal);
            }
        }

        terminal.pop_clip();
    }

    /// Get a reference to the currently focused child view, if any
    pub fn focused_child(&self) -> Option<&dyn View> {
        if self.focused < self.children.len() {
            Some(&*self.children[self.focused])
        } else {
            None
        }
    }

    /// True if the child at `index` can take focus.
    ///
    /// Matches Borland TGroup::findNext: the view must be selectable and not
    /// disabled. (SF_VISIBLE is not checked because this port never sets it;
    /// hidden views are simply not added to the group.)
    fn child_focusable(&self, index: usize) -> bool {
        use crate::core::state::SF_DISABLED;
        let child = &self.children[index];
        child.can_focus() && (child.state() & SF_DISABLED) == 0
    }

    pub fn select_next(&mut self) {
        if self.children.is_empty() {
            return;
        }

        // Find the next focusable child WITHOUT dropping current focus:
        // if no other child qualifies, focus stays where it is (Borland's
        // focusNext is a no-op in that case)
        let start_index = self.focused;
        let mut candidate = self.focused;
        loop {
            candidate = (candidate + 1) % self.children.len();
            if candidate == start_index {
                return; // wrapped without finding another focusable child
            }
            if self.child_focusable(candidate) {
                break;
            }
        }

        if self.focused < self.children.len() {
            self.children[self.focused].set_focus(false);
        }
        self.focused = candidate;
        self.children[self.focused].set_focus(true);
    }

    pub fn select_previous(&mut self) {
        if self.children.is_empty() {
            return;
        }

        // Mirror image of select_next: scan backwards, keep focus if no
        // other focusable child exists
        let start_index = self.focused;
        let mut candidate = self.focused;
        loop {
            candidate = if candidate == 0 {
                self.children.len() - 1
            } else {
                candidate - 1
            };
            if candidate == start_index {
                return;
            }
            if self.child_focusable(candidate) {
                break;
            }
        }

        if self.focused < self.children.len() {
            self.children[self.focused].set_focus(false);
        }
        self.focused = candidate;
        self.children[self.focused].set_focus(true);
    }
}

impl View for Group {
    fn bounds(&self) -> Rect {
        self.bounds
    }

    fn set_bounds(&mut self, bounds: Rect) {
        // Calculate the offset (how much the group moved)
        let dx = bounds.a.x - self.bounds.a.x;
        let dy = bounds.a.y - self.bounds.a.y;

        // Calculate the size change (how much the group was resized)
        let dw = bounds.width() - self.bounds.width();
        let dh = bounds.height() - self.bounds.height();

        // Update our bounds
        self.bounds = bounds;

        // Update all children's bounds. Every child shifts by the group's
        // offset (children store absolute coordinates); each edge additionally
        // follows the size delta only if the matching grow bit is set.
        // Matches Borland: TView::calcBounds() driven by growMode.
        use crate::core::state::{GF_GROW_HI_X, GF_GROW_HI_Y, GF_GROW_LO_X, GF_GROW_LO_Y};
        for child in &mut self.children {
            let grow = child.grow_mode();
            let child_bounds = child.bounds();
            let new_bounds = Rect::new(
                child_bounds.a.x + dx + if grow & GF_GROW_LO_X != 0 { dw } else { 0 },
                child_bounds.a.y + dy + if grow & GF_GROW_LO_Y != 0 { dh } else { 0 },
                child_bounds.b.x + dx + if grow & GF_GROW_HI_X != 0 { dw } else { 0 },
                child_bounds.b.y + dy + if grow & GF_GROW_HI_Y != 0 { dh } else { 0 },
            );
            child.set_bounds(new_bounds);
        }
    }

    fn draw(&mut self, terminal: &mut Terminal) {
        // Draw background if specified
        if let Some(bg_attr) = self.background {
            let width = self.bounds.width_clamped() as usize;
            let height = self.bounds.height_clamped() as usize;

            for y in 0..height {
                let mut buf = DrawBuffer::new(width);
                buf.move_char(0, ' ', bg_attr, width);
                write_line_to_terminal(terminal, self.bounds.a.x, self.bounds.a.y + y as i16, &buf);
            }
        }

        // Push clipping region for this group's bounds
        // Expand by 1 on all sides to allow children (like scrollbars) to overlap with parent's frame
        let mut clip_bounds = self.bounds;
        clip_bounds.grow(1, 1);
        terminal.push_clip(clip_bounds);

        // Build this Group's palette chain node for safe palette traversal.
        // Group is typically transparent (no palette), but carries the parent link.
        let my_chain_node = crate::core::palette_chain::PaletteChainNode::new(
            self.get_palette(),
            self.palette_chain.clone(),
        );

        // Only draw children that intersect with this group's bounds
        // The clipping region ensures children can't render outside parent boundaries
        for child in &mut self.children {
            child.set_palette_chain(Some(my_chain_node.clone()));
            let child_bounds = child.bounds();
            if self.bounds.intersects(&child_bounds) {
                child.draw(terminal);
            }
        }

        // Pop clipping region
        terminal.pop_clip();
    }

    fn handle_event(&mut self, event: &mut Event) {
        use crate::core::state::{OF_POST_PROCESS, OF_PRE_PROCESS};

        // Mouse events: positional events (no three-phase processing)
        // Search in REVERSE order (top-most child first) - matches Borland's z-order
        // Matches Borland: TGroup::handleEvent() processes mouse events from front to back
        if event.what == EventType::MouseDown
            || event.what == EventType::MouseMove
            || event.what == EventType::MouseUp
        {
            let mouse_pos = event.mouse.pos;

            // For MouseMove and MouseUp, check if the focused child is dragging or resizing
            // If so, send the event to it even if mouse is outside its bounds
            // This allows dragging and resizing beyond window boundaries (matches Borland behavior)
            if (event.what == EventType::MouseMove || event.what == EventType::MouseUp)
                && self.focused < self.children.len()
            {
                // Check if focused child is in dragging or resizing state
                let child_state = self.children[self.focused].state();
                if (child_state
                    & (crate::core::state::SF_DRAGGING | crate::core::state::SF_RESIZING))
                    != 0
                {
                    self.children[self.focused].handle_event(event);
                    return;
                }
            }

            // First pass: find which child contains the mouse (search in reverse z-order)
            let mut clicked_child_index: Option<usize> = None;
            for i in (0..self.children.len()).rev() {
                let child_bounds = self.children[i].bounds();
                if child_bounds.contains(mouse_pos) {
                    clicked_child_index = Some(i);
                    break;
                }
            }

            // If a child was clicked, handle focus and events
            if let Some(i) = clicked_child_index {
                if event.what == EventType::MouseDown {
                    // Check if this is a label with a link (Borland: TLabel::focusLink)
                    // If so, focus the linked control instead of the label
                    if let Some(link_id) = self.children[i].label_link() {
                        // Find the child with the matching ViewId
                        if let Some(link_index) = self.view_ids.iter().position(|&id| id == link_id)
                        {
                            if self.children[link_index].can_focus() {
                                self.clear_all_focus();
                                self.focused = link_index;
                                self.children[link_index].set_focus(true);
                                event.clear(); // Event consumed by focus transfer
                                return;
                            }
                        }
                    } else if self.children[i].can_focus() {
                        // Regular focusable view - give it focus
                        self.clear_all_focus();
                        self.focused = i;
                        self.children[i].set_focus(true);
                    }
                }

                // Second pass: handle the event
                self.children[i].handle_event(event);

                // IMPORTANT: If the child converted the event to Broadcast (e.g., calculator buttons),
                // we need to handle that broadcast now (matches Borland's putEvent behavior)
                if event.what == EventType::Broadcast {
                    // Recursively call handle_event to process the broadcast
                    self.handle_event(event);
                    return;
                }

                // CRITICAL FIX: If the child converted MouseDown to Command (e.g., ListBox double-click),
                // DON'T return immediately. Instead, fall through to the command processing phase below
                // so the Command can be handled by the three-phase processing.
                // Matches Borland: Commands generated by mouse events flow through the event loop
                if event.what == EventType::Command {
                    // Fall through to command processing (don't return here)
                } else {
                    // For other event types, return after handling
                    return;
                }
            } else {
                // No child under the mouse: positional events must NOT be
                // forwarded to the focused child. Matches Borland:
                // TGroup::handleEvent() routes positional events only to
                // firstThat(hasMouse); if no subview contains the mouse the
                // event goes nowhere.
                return;
            }
        }

        // Keyboard and Command events: use three-phase processing (matches Borland)
        // Phase 1: PreProcess - views with OF_PRE_PROCESS flag (e.g., buttons for Space/Enter)
        // Phase 2: Focused - currently focused view gets first chance
        // Phase 3: PostProcess - views with OF_POST_PROCESS flag (e.g., status line for help keys)

        if event.what == EventType::Keyboard || event.what == EventType::Command {
            // Phase 1: PreProcess
            // Views with OF_PRE_PROCESS get first chance at the event
            for child in &mut self.children {
                if event.what == EventType::Nothing {
                    break; // Event was handled
                }
                if (child.options() & OF_PRE_PROCESS) != 0 {
                    child.handle_event(event);
                }
            }

            // Phase 2: Focused
            // Give focused view a chance if event wasn't handled
            if event.what != EventType::Nothing && self.focused < self.children.len() {
                self.children[self.focused].handle_event(event);
            }

            // Phase 3: PostProcess
            // Views with OF_POST_PROCESS get last chance (e.g., status line, buttons)
            if event.what != EventType::Nothing {
                for child in &mut self.children {
                    if event.what == EventType::Nothing {
                        break; // Event was handled
                    }
                    if (child.options() & OF_POST_PROCESS) != 0 {
                        child.handle_event(event);
                    }
                }

                // IMPORTANT: If a PostProcess view converted the event to Broadcast,
                // we need to handle that broadcast now (matches Borland's putEvent behavior)
                // For example, calculator buttons convert MouseDown to Broadcast
                if event.what == EventType::Broadcast {
                    // Recursively call handle_event to process the broadcast
                    self.handle_event(event);
                }
            }

            // Handle Tab key for focus navigation (after three-phase processing)
            // Only handle if event wasn't consumed by any child
            if event.what == EventType::Keyboard {
                if event.key_code == KB_TAB {
                    self.select_next();
                    event.clear();
                    return;
                } else if event.key_code == KB_SHIFT_TAB {
                    self.select_previous();
                    event.clear();
                    return;
                }
            }
        } else {
            // Broadcast events: send to ALL children
            // Other event types: send to focused child only
            if event.what == EventType::Broadcast {
                // Handle CM_FOCUS_LINK: Label hotkey requests focus on linked control
                if event.command == crate::core::command::CM_FOCUS_LINK {
                    let view_id = super::view::ViewId::from_u16(event.key_code);
                    if self.focus_by_view_id(view_id) {
                        event.clear();
                    }
                    return;
                }
                // Matches Borland: TGroup::handleEvent() broadcasts to ALL
                // children via forEach(doHandleEvent) — delivery does not stop
                // when one child clears the event, so every child sees the
                // broadcast.
                for child in &mut self.children {
                    child.handle_event(event);
                }
            } else {
                // Other event types: send to focused child only
                if self.focused < self.children.len() {
                    self.children[self.focused].handle_event(event);
                }
            }
        }
    }

    fn update_cursor(&self, terminal: &mut Terminal) {
        // Hide cursor by default
        let _ = terminal.hide_cursor();

        // Update cursor for the focused child (it can show it if needed)
        if self.focused < self.children.len() {
            self.children[self.focused].update_cursor(terminal);
        }
    }

    fn get_end_state(&self) -> crate::core::command::CommandId {
        self.end_state
    }

    fn set_end_state(&mut self, command: crate::core::command::CommandId) {
        self.end_state = command;
    }

    /// Validate group before performing command
    /// Matches Borland: TGroup::valid(ushort command)
    /// - If command is CM_RELEASED_FOCUS, validate current focused child if it has OF_VALIDATE
    /// - Otherwise, validate all children (return false if any child is invalid)
    fn valid(&mut self, command: crate::core::command::CommandId) -> bool {
        use crate::core::command::CM_RELEASED_FOCUS;
        use crate::core::state::OF_VALIDATE;

        if command == CM_RELEASED_FOCUS {
            // Validate only the currently focused child if it has OF_VALIDATE flag
            if self.focused < self.children.len() {
                let child = &mut self.children[self.focused];
                if (child.options() & OF_VALIDATE) != 0 {
                    return child.valid(command);
                }
            }
            true
        } else {
            // Validate all children - return false if any child is invalid
            // Matches Borland: firstThat(isInvalid, &command) == nullptr
            for child in &mut self.children {
                if !child.valid(command) {
                    return false;
                }
            }
            true
        }
    }

    fn grow_mode(&self) -> crate::core::state::GrowFlags {
        self.grow_mode
    }

    fn set_grow_mode(&mut self, grow_mode: crate::core::state::GrowFlags) {
        self.grow_mode = grow_mode;
    }

    fn set_palette_chain(&mut self, node: Option<crate::core::palette_chain::PaletteChainNode>) {
        self.palette_chain = node;
    }

    fn get_palette_chain(&self) -> Option<&crate::core::palette_chain::PaletteChainNode> {
        self.palette_chain.as_ref()
    }

    fn get_palette(&self) -> Option<crate::core::palette::Palette> {
        // TGroup has no palette (returns empty palette in Borland)
        // Returning None achieves the same effect - skip to parent's palette
        None
    }
}

/// Builder for creating groups with a fluent API.
pub struct GroupBuilder {
    bounds: Option<Rect>,
    background: Option<Attr>,
}

impl GroupBuilder {
    pub fn new() -> Self {
        Self {
            bounds: None,
            background: None,
        }
    }

    #[must_use]
    pub fn bounds(mut self, bounds: Rect) -> Self {
        self.bounds = Some(bounds);
        self
    }

    #[must_use]
    pub fn background(mut self, background: Attr) -> Self {
        self.background = Some(background);
        self
    }

    pub fn build(self) -> Group {
        let bounds = self.bounds.expect("Group bounds must be set");
        if let Some(bg) = self.background {
            Group::with_background(bounds, bg)
        } else {
            Group::new(bounds)
        }
    }

    pub fn build_boxed(self) -> Box<Group> {
        Box::new(self.build())
    }
}

impl Default for GroupBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Helper to count how many times draw is called on views
    struct DrawCountView {
        bounds: Rect,
        draw_count: std::cell::RefCell<usize>,
    }

    impl DrawCountView {
        fn new(bounds: Rect) -> Self {
            Self {
                bounds,
                draw_count: std::cell::RefCell::new(0),
            }
        }
    }

    impl View for DrawCountView {
        fn bounds(&self) -> Rect {
            self.bounds
        }

        fn set_bounds(&mut self, bounds: Rect) {
            self.bounds = bounds;
        }

        fn draw(&mut self, _terminal: &mut Terminal) {
            *self.draw_count.borrow_mut() += 1;
        }

        fn handle_event(&mut self, _event: &mut Event) {}

        fn get_palette(&self) -> Option<crate::core::palette::Palette> {
            None
        }
    }

    // Test view that records events, can take focus, and stores a grow mode
    struct RecorderView {
        bounds: Rect,
        state: crate::core::state::StateFlags,
        grow_mode: crate::core::state::GrowFlags,
        events: std::rc::Rc<std::cell::RefCell<Vec<EventType>>>,
    }

    impl RecorderView {
        fn new(bounds: Rect) -> Self {
            Self {
                bounds,
                state: 0,
                grow_mode: 0,
                events: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
            }
        }
    }

    impl View for RecorderView {
        fn bounds(&self) -> Rect {
            self.bounds
        }

        fn set_bounds(&mut self, bounds: Rect) {
            self.bounds = bounds;
        }

        fn draw(&mut self, _terminal: &mut Terminal) {}

        fn handle_event(&mut self, event: &mut Event) {
            self.events.borrow_mut().push(event.what);
        }

        fn can_focus(&self) -> bool {
            true
        }

        fn state(&self) -> crate::core::state::StateFlags {
            self.state
        }

        fn set_state(&mut self, state: crate::core::state::StateFlags) {
            self.state = state;
        }

        fn grow_mode(&self) -> crate::core::state::GrowFlags {
            self.grow_mode
        }

        fn set_grow_mode(&mut self, grow_mode: crate::core::state::GrowFlags) {
            self.grow_mode = grow_mode;
        }

        fn get_palette(&self) -> Option<crate::core::palette::Palette> {
            None
        }
    }

    #[test]
    fn test_mouse_down_outside_children_not_sent_to_focused() {
        use crate::core::geometry::Point;

        let mut group = Group::new(Rect::new(0, 0, 80, 25));
        let child = RecorderView::new(Rect::new(0, 0, 10, 5));
        let events = child.events.clone();
        group.add(Box::new(child));
        group.set_initial_focus();

        // MouseDown on empty group area (outside the child at 0,0-10,5)
        let mut event = Event::mouse(EventType::MouseDown, Point::new(50, 20), 1, false);
        group.handle_event(&mut event);

        // The focused child must NOT have received the positional event
        assert!(events.borrow().is_empty());

        // But a click ON the child is still delivered (focus-on-click intact)
        let mut event = Event::mouse(EventType::MouseDown, Point::new(5, 2), 1, false);
        group.handle_event(&mut event);
        assert_eq!(events.borrow().as_slice(), &[EventType::MouseDown]);
    }

    #[test]
    fn test_grow_modes_on_resize() {
        use crate::core::state::{GF_GROW_ALL, GF_GROW_HI_X, GF_GROW_HI_Y};

        let mut group = Group::new(Rect::new(0, 0, 40, 20));

        // Fixed child (grow_mode = 0, Borland default)
        group.add(Box::new(RecorderView::new(Rect::new(1, 1, 11, 3))));

        // Right/bottom-growing child (gfGrowHiX | gfGrowHiY)
        let mut growing = RecorderView::new(Rect::new(1, 5, 11, 7));
        growing.set_grow_mode(GF_GROW_HI_X | GF_GROW_HI_Y);
        group.add(Box::new(growing));

        // Fully growing child (gfGrowAll — moves with the far edge)
        let mut all = RecorderView::new(Rect::new(30, 15, 39, 19));
        all.set_grow_mode(GF_GROW_ALL);
        group.add(Box::new(all));

        // Resize the group: +10 wide, +5 tall (no move)
        group.set_bounds(Rect::new(0, 0, 50, 25));

        // Fixed child: unchanged
        assert_eq!(group.child_at(0).bounds(), Rect::new(1, 1, 11, 3));
        // HiX|HiY child: only b edge moved
        assert_eq!(group.child_at(1).bounds(), Rect::new(1, 5, 21, 12));
        // GrowAll child: both edges moved
        assert_eq!(group.child_at(2).bounds(), Rect::new(40, 20, 49, 24));

        // Moving the group (no size change) shifts all children equally
        group.set_bounds(Rect::new(5, 2, 55, 27));
        assert_eq!(group.child_at(0).bounds(), Rect::new(6, 3, 16, 5));
        assert_eq!(group.child_at(1).bounds(), Rect::new(6, 7, 26, 14));
        assert_eq!(group.child_at(2).bounds(), Rect::new(45, 22, 54, 26));
    }

    #[test]
    fn test_focus_restored_after_removing_focused_child() {
        use crate::core::state::SF_FOCUSED;

        let mut group = Group::new(Rect::new(0, 0, 80, 25));
        group.add(Box::new(RecorderView::new(Rect::new(0, 0, 10, 2))));
        group.add(Box::new(RecorderView::new(Rect::new(0, 3, 10, 5))));
        group.add(Box::new(RecorderView::new(Rect::new(0, 6, 10, 8))));

        group.set_focus_to(1);
        assert!(group.child_at(1).is_focused());

        // Remove the focused child — focus must land on a remaining child
        group.remove(1);
        assert_eq!(group.len(), 2);
        let focused_count = (0..group.len())
            .filter(|&i| (group.child_at(i).state() & SF_FOCUSED) != 0)
            .count();
        assert_eq!(focused_count, 1);
        assert!(group.focused_child().unwrap().is_focused());
    }

    #[test]
    fn test_broadcast_delivered_to_all_children() {
        // A child that clears broadcast events (simulates a "consumer")
        struct Consumer {
            bounds: Rect,
        }
        impl View for Consumer {
            fn bounds(&self) -> Rect {
                self.bounds
            }
            fn set_bounds(&mut self, bounds: Rect) {
                self.bounds = bounds;
            }
            fn draw(&mut self, _terminal: &mut Terminal) {}
            fn handle_event(&mut self, event: &mut Event) {
                if event.what == EventType::Broadcast {
                    event.clear();
                }
            }
            fn get_palette(&self) -> Option<crate::core::palette::Palette> {
                None
            }
        }

        let mut group = Group::new(Rect::new(0, 0, 80, 25));
        // First child consumes broadcasts
        group.add(Box::new(Consumer {
            bounds: Rect::new(0, 0, 5, 1),
        }));
        // Second child records what it receives
        let recorder = RecorderView::new(Rect::new(0, 2, 5, 3));
        let events = recorder.events.clone();
        group.add(Box::new(recorder));

        let mut event = Event::broadcast(9999);
        group.handle_event(&mut event);

        // The second child was still visited even though the first cleared
        // the event (Borland delivers broadcasts to every child)
        assert_eq!(events.borrow().len(), 1);
    }

    #[test]
    fn test_child_completely_outside_parent_not_drawn() {
        // Create a group at (10, 10) with size 20x20
        let group = Group::new(Rect::new(10, 10, 30, 30));

        // Add a child completely outside the parent bounds (to the right)
        let child_bounds = Rect::new(100, 15, 110, 20);

        // Verify the child is outside parent bounds
        assert!(!group.bounds.intersects(&child_bounds));
    }

    #[test]
    fn test_child_inside_parent_is_drawn() {
        // Create a group at (10, 10) with size 20x20
        let mut group = Group::new(Rect::new(10, 10, 30, 30));

        // Add a child at relative position (5, 5) which becomes absolute (15, 15)
        // This is inside the parent bounds (10, 10, 30, 30)
        let child = Box::new(DrawCountView::new(Rect::new(5, 5, 15, 15)));
        group.add(child);

        // Verify the child was converted to absolute coordinates
        assert_eq!(group.children.len(), 1);
        assert_eq!(group.children[0].bounds(), Rect::new(15, 15, 25, 25));

        // Verify child intersects with parent (so it would be drawn)
        assert!(group.bounds.intersects(&group.children[0].bounds()));
    }

    #[test]
    fn test_child_partially_outside_parent() {
        // Create a group at (10, 10) with size 20x20 (bounds: 10-30, 10-30)
        let mut group = Group::new(Rect::new(10, 10, 30, 30));

        // Add a child at relative position (15, 15) with size 10x10
        // Absolute bounds: (25, 25, 35, 35)
        // This extends beyond parent (30, 30), so partially outside
        let child = Box::new(DrawCountView::new(Rect::new(15, 15, 25, 25)));
        group.add(child);

        // Verify conversion to absolute
        assert_eq!(group.children[0].bounds(), Rect::new(25, 25, 35, 35));

        // Verify child still intersects with parent (partially visible)
        assert!(group.bounds.intersects(&group.children[0].bounds()));

        // Note: The child will be drawn, but the Terminal's write methods
        // will clip at the terminal boundaries. For proper parent clipping,
        // we would need to implement a clipping region in Terminal.
        // For now, we just verify that intersecting children would be drawn.
    }

    #[test]
    fn test_coordinate_conversion_on_add() {
        // Create a group at (20, 30) with size 40x50
        let mut group = Group::new(Rect::new(20, 30, 60, 80));

        // Add a child with relative coordinates (5, 10)
        let child = Box::new(DrawCountView::new(Rect::new(5, 10, 15, 20)));
        group.add(child);

        // Verify the child's bounds were converted to absolute
        // Relative (5, 10, 15, 20) + Group origin (20, 30) = Absolute (25, 40, 35, 50)
        assert_eq!(group.children[0].bounds(), Rect::new(25, 40, 35, 50));
    }

    #[test]
    fn test_multiple_children_clipping() {
        // Create a group at (0, 0) with size 50x50
        let mut group = Group::new(Rect::new(0, 0, 50, 50));

        // Child 1: Inside (10, 10, 20, 20) -> absolute (10, 10, 20, 20)
        group.add(Box::new(DrawCountView::new(Rect::new(10, 10, 20, 20))));

        // Child 2: Completely outside (100, 100, 110, 110) -> absolute (100, 100, 110, 110)
        group.add(Box::new(DrawCountView::new(Rect::new(100, 100, 110, 110))));

        // Child 3: Partially outside (40, 40, 60, 60) -> absolute (40, 40, 60, 60)
        group.add(Box::new(DrawCountView::new(Rect::new(40, 40, 60, 60))));

        assert_eq!(group.children.len(), 3);

        // Verify intersections
        // Child 1: completely inside, should intersect
        assert!(group.bounds.intersects(&group.children[0].bounds()));

        // Child 2: completely outside, should NOT intersect
        assert!(!group.bounds.intersects(&group.children[1].bounds()));

        // Child 3: partially outside, should intersect
        assert!(group.bounds.intersects(&group.children[2].bounds()));
    }

    #[test]
    fn test_child_by_id() {
        // Create a group and add children
        let mut group = Group::new(Rect::new(0, 0, 50, 50));

        let child1 = Box::new(DrawCountView::new(Rect::new(0, 0, 10, 10)));
        let id1 = group.add(child1);

        let child2 = Box::new(DrawCountView::new(Rect::new(20, 0, 30, 10)));
        let id2 = group.add(child2);

        let child3 = Box::new(DrawCountView::new(Rect::new(40, 0, 50, 10)));
        let id3 = group.add(child3);

        // Test accessing children by ID (immutable)
        assert!(group.child_by_id(id1).is_some());
        assert!(group.child_by_id(id2).is_some());
        assert!(group.child_by_id(id3).is_some());

        // Test that invalid ID returns None
        let invalid_id = ViewId::new();
        assert!(group.child_by_id(invalid_id).is_none());
    }

    #[test]
    fn test_child_by_id_mut() {
        // Create a group and add a child
        let mut group = Group::new(Rect::new(0, 0, 50, 50));

        let child = Box::new(DrawCountView::new(Rect::new(0, 0, 10, 10)));
        let child_id = group.add(child);

        // Test accessing child by ID (mutable)
        let child_ref = group.child_by_id_mut(child_id);
        assert!(child_ref.is_some());

        // Test that invalid ID returns None
        let invalid_id = ViewId::new();
        assert!(group.child_by_id_mut(invalid_id).is_none());
    }

    #[test]
    fn test_remove_by_id() {
        // Create a group and add multiple children
        let mut group = Group::new(Rect::new(0, 0, 50, 50));

        let child1 = Box::new(DrawCountView::new(Rect::new(0, 0, 10, 10)));
        let id1 = group.add(child1);

        let child2 = Box::new(DrawCountView::new(Rect::new(20, 0, 30, 10)));
        let id2 = group.add(child2);

        let child3 = Box::new(DrawCountView::new(Rect::new(40, 0, 50, 10)));
        let id3 = group.add(child3);

        // Verify all children are present
        assert_eq!(group.len(), 3);
        assert!(group.child_by_id(id1).is_some());
        assert!(group.child_by_id(id2).is_some());
        assert!(group.child_by_id(id3).is_some());

        // Remove middle child by ID
        let removed = group.remove_by_id(id2);
        assert!(removed);
        assert_eq!(group.len(), 2);

        // Verify id2 is gone but id1 and id3 are still there
        assert!(group.child_by_id(id1).is_some());
        assert!(group.child_by_id(id2).is_none());
        assert!(group.child_by_id(id3).is_some());

        // Try to remove invalid ID
        let invalid_id = ViewId::new();
        let not_removed = group.remove_by_id(invalid_id);
        assert!(!not_removed);
        assert_eq!(group.len(), 2);
    }

    #[test]
    fn test_bring_to_front_syncs_view_ids() {
        use crate::core::geometry::Rect;

        let mut group = Group::new(Rect::new(0, 0, 80, 25));
        let id1 = group.add(Box::new(crate::views::background::Background::new(
            Rect::new(0, 0, 10, 5),
            ' ',
            crate::core::palette::Attr::new(
                crate::core::palette::TvColor::White,
                crate::core::palette::TvColor::Blue,
            ),
        )));
        let id2 = group.add(Box::new(crate::views::background::Background::new(
            Rect::new(0, 0, 10, 5),
            ' ',
            crate::core::palette::Attr::new(
                crate::core::palette::TvColor::White,
                crate::core::palette::TvColor::Blue,
            ),
        )));
        let id3 = group.add(Box::new(crate::views::background::Background::new(
            Rect::new(0, 0, 10, 5),
            ' ',
            crate::core::palette::Attr::new(
                crate::core::palette::TvColor::White,
                crate::core::palette::TvColor::Blue,
            ),
        )));

        // Bring first child to front
        group.bring_to_front(0);

        // After bring_to_front(0): order should be [id2, id3, id1]
        // Verify child_by_id still works correctly
        assert!(group.child_by_id(id1).is_some());
        assert!(group.child_by_id(id2).is_some());
        assert!(group.child_by_id(id3).is_some());

        // The brought-to-front child (id1) should now be at the last index
        // Verify by checking that view_ids[2] == id1
        // We can test this indirectly: remove_by_id should still find the right child
        assert!(group.remove_by_id(id1));
        assert_eq!(group.len(), 2);
        // id2 and id3 should still be findable
        assert!(group.child_by_id(id2).is_some());
        assert!(group.child_by_id(id3).is_some());
    }

    #[test]
    fn test_send_to_back_syncs_view_ids() {
        use crate::core::geometry::Rect;

        let mut group = Group::new(Rect::new(0, 0, 80, 25));
        let id1 = group.add(Box::new(crate::views::background::Background::new(
            Rect::new(0, 0, 10, 5),
            ' ',
            crate::core::palette::Attr::new(
                crate::core::palette::TvColor::White,
                crate::core::palette::TvColor::Blue,
            ),
        )));
        let id2 = group.add(Box::new(crate::views::background::Background::new(
            Rect::new(0, 0, 10, 5),
            ' ',
            crate::core::palette::Attr::new(
                crate::core::palette::TvColor::White,
                crate::core::palette::TvColor::Blue,
            ),
        )));
        let id3 = group.add(Box::new(crate::views::background::Background::new(
            Rect::new(0, 0, 10, 5),
            ' ',
            crate::core::palette::Attr::new(
                crate::core::palette::TvColor::White,
                crate::core::palette::TvColor::Blue,
            ),
        )));

        // Send last child to back (position 1, after index 0)
        group.send_to_back(2);

        // After send_to_back(2): order should be [id1, id3, id2]
        // All IDs should still be findable
        assert!(group.child_by_id(id1).is_some());
        assert!(group.child_by_id(id2).is_some());
        assert!(group.child_by_id(id3).is_some());

        // Remove id3 (should be at index 1 now) to verify sync
        assert!(group.remove_by_id(id3));
        assert_eq!(group.len(), 2);
        assert!(group.child_by_id(id1).is_some());
        assert!(group.child_by_id(id2).is_some());
    }

    #[test]
    fn test_child_by_id_fragility_fix() {
        // This test demonstrates the fragility fix that child_by_id() solves
        let mut group = Group::new(Rect::new(0, 0, 50, 50));

        let child1 = Box::new(DrawCountView::new(Rect::new(0, 0, 10, 10)));
        let id1 = group.add(child1);

        let child2 = Box::new(DrawCountView::new(Rect::new(20, 0, 30, 10)));
        let id2 = group.add(child2);

        let child3 = Box::new(DrawCountView::new(Rect::new(40, 0, 50, 10)));
        let id3 = group.add(child3);

        // With indices, we would have: index 0 = id1, index 1 = id2, index 2 = id3
        // If we stored index 1 for "the button" and then inserted a new child before it,
        // our stored index 1 would now point to the new child, not the button!

        // But with ViewIds, the IDs are stable regardless of insertion order
        assert!(group.child_by_id(id1).is_some());
        assert!(group.child_by_id(id2).is_some());
        assert!(group.child_by_id(id3).is_some());

        // If we insert a new child at the beginning (simulating reordering)
        let new_child = Box::new(DrawCountView::new(Rect::new(0, 20, 10, 30)));
        let new_id = group.add(new_child);

        // The old IDs still work correctly because they're not affected by reordering
        assert!(group.child_by_id(id1).is_some());
        assert!(group.child_by_id(id2).is_some());
        assert!(group.child_by_id(id3).is_some());
        assert!(group.child_by_id(new_id).is_some());
    }
}