textual 1.0.0-dev

A reactive TUI framework inspired by the Python Textual library
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
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
use crate::debug::debug_message;
use crate::event::{Action, AnimationRequest, BindingHint, Event, EventCtx};
use crate::keys::{KeyEventData, format_key_display};
use crate::message::{MessageEnvelope, MessageEvent};
use crate::node_id::NodeId;
use crate::widget_tree::WidgetTree;
use crate::widgets::Widget;

use super::dispatch_ctx::set_dispatch_recipient;
use super::types::DispatchOutcome;

#[cfg(test)]
pub(crate) fn dispatch_event(root: &mut dyn Widget, event: Event) -> DispatchOutcome {
    let event_debug = format!("{event:?}");
    let mut ctx = EventCtx::default();
    let always_bubble = matches!(&event, Event::MouseUp(..));
    root.on_event_capture(&event, &mut ctx);
    if always_bubble || !ctx.handled() {
        root.on_event(&event, &mut ctx);
    }
    let outcome = DispatchOutcome {
        handled: ctx.handled(),
        repaint_requested: ctx.repaint_requested(),
        invalidation: ctx.invalidation(),
        stop_requested: ctx.stop_requested(),
        messages: ctx.take_messages(),
        animation_requests: ctx.take_animation_requests(),
        worker_requests: ctx.take_worker_requests(),
        recompose_nodes: ctx.take_recompose_nodes(),
        default_prevented: false,
    };
    debug_message(&format!(
        "[dispatch_event] event={event_debug} handled={} repaint={} messages={}",
        outcome.handled,
        outcome.repaint_requested,
        outcome.messages.len()
    ));
    outcome
}

pub(crate) fn is_scroll_action(action: Action) -> bool {
    matches!(
        action,
        Action::ScrollHome
            | Action::ScrollEnd
            | Action::ScrollUp
            | Action::ScrollDown
            | Action::ScrollPageUp
            | Action::ScrollPageDown
            | Action::ScrollLeft
            | Action::ScrollRight
            | Action::ScrollPageLeft
            | Action::ScrollPageRight
    )
}

pub(crate) fn is_priority_action(action: Action) -> bool {
    matches!(action, Action::CommandPalette)
}

pub(crate) fn dispatch_mouse_scroll(
    root: &mut dyn Widget,
    delta_x: i32,
    delta_y: i32,
) -> DispatchOutcome {
    let mut ctx = EventCtx::default();
    root.on_mouse_scroll(delta_x, delta_y, &mut ctx);
    DispatchOutcome {
        handled: ctx.handled(),
        repaint_requested: ctx.repaint_requested(),
        invalidation: ctx.invalidation(),
        stop_requested: ctx.stop_requested(),
        messages: ctx.take_messages(),
        animation_requests: ctx.take_animation_requests(),
        worker_requests: ctx.take_worker_requests(),
        recompose_nodes: ctx.take_recompose_nodes(),
        default_prevented: false,
    }
}

// ---------------------------------------------------------------------------
// Arena-tree-based event routing
// ---------------------------------------------------------------------------

/// Build the path from root to `target` (inclusive): `[root, …, parent, target]`.
///
/// Returns an empty vec if `target` is not in the tree or the tree has no root.
fn build_path_to_node(tree: &WidgetTree, target: NodeId) -> Vec<NodeId> {
    if !tree.contains(target) {
        return Vec::new();
    }
    let mut path = vec![target];
    let ancestors = tree.ancestors(target); // [parent, grandparent, …, root]
    path.extend(ancestors);
    path.reverse(); // [root, …, parent, target]
    path
}

/// Find the currently focused node by walking the entire tree depth-first.
///
/// Returns the first node whose widget reports `has_focus() == true`.
pub fn focused_node_id_tree(tree: &WidgetTree) -> Option<NodeId> {
    let root = tree.root()?;
    for node_id in tree.walk_depth_first(root) {
        if let Some(node) = tree.get(node_id) {
            if node.display
                && node.visibility == crate::style::Visibility::Visible
                && node.widget.has_focus()
            {
                return Some(node_id);
            }
        }
    }
    None
}

/// Dispatch an event through the arena tree using capture + bubble phases.
///
/// 1. Build the path from root to `focused` node.
/// 2. **Capture phase**: walk root→focused, calling `on_event_capture()`.
/// 3. **Bubble phase**: walk focused→root, calling `on_event()`.
///
/// If `focused` is `None`, dispatches to the root node only.
pub fn dispatch_event_tree(
    tree: &mut WidgetTree,
    focused: Option<NodeId>,
    event: &Event,
) -> DispatchOutcome {
    let event_debug = format!("{event:?}");
    let mut ctx = EventCtx::default();
    let always_bubble = matches!(event, Event::MouseUp(..));

    let path = match focused {
        Some(focus_id) => build_path_to_node(tree, focus_id),
        None => match tree.root() {
            Some(root) => vec![root],
            None => return DispatchOutcome::default(),
        },
    };

    // Capture phase: root → focused
    for &node_id in &path {
        if ctx.handled() {
            break;
        }
        if let Some(node) = tree.get_mut(node_id) {
            let _dispatch_guard = set_dispatch_recipient(node_id);
            ctx.set_node_id(node_id);
            node.widget.on_event_capture(event, &mut ctx);
        }
    }

    // Bubble phase: focused → root
    if always_bubble || !ctx.handled() {
        for &node_id in path.iter().rev() {
            if let Some(node) = tree.get_mut(node_id) {
                let _dispatch_guard = set_dispatch_recipient(node_id);
                ctx.set_node_id(node_id);
                node.widget.on_event(event, &mut ctx);
            }
            if ctx.handled() {
                break;
            }
        }
    }

    let outcome = DispatchOutcome {
        handled: ctx.handled(),
        repaint_requested: ctx.repaint_requested(),
        invalidation: ctx.invalidation(),
        stop_requested: ctx.stop_requested(),
        messages: ctx.take_messages(),
        animation_requests: ctx.take_animation_requests(),
        worker_requests: ctx.take_worker_requests(),
        recompose_nodes: ctx.take_recompose_nodes(),
        default_prevented: false,
    };
    debug_message(&format!(
        "[dispatch_event_tree] event={event_debug} handled={} repaint={} messages={}",
        outcome.handled,
        outcome.repaint_requested,
        outcome.messages.len()
    ));
    outcome
}

/// Dispatch an event to a specific `target` node using the arena tree.
///
/// Capture phase runs root→target, then bubble phase runs target→root.
pub fn dispatch_event_to_target_tree(
    tree: &mut WidgetTree,
    target: NodeId,
    event: &Event,
) -> DispatchOutcome {
    let mut ctx = EventCtx::default();
    let path = build_path_to_node(tree, target);

    // Capture phase: root → target
    for &node_id in &path {
        if ctx.handled() {
            break;
        }
        if let Some(node) = tree.get_mut(node_id) {
            let _dispatch_guard = set_dispatch_recipient(node_id);
            ctx.set_node_id(node_id);
            node.widget.on_event_capture(event, &mut ctx);
        }
    }

    // Bubble phase: target → root
    if !ctx.handled() {
        for &node_id in path.iter().rev() {
            if let Some(node) = tree.get_mut(node_id) {
                let _dispatch_guard = set_dispatch_recipient(node_id);
                ctx.set_node_id(node_id);
                node.widget.on_event(event, &mut ctx);
            }
            if ctx.handled() {
                break;
            }
        }
    }

    DispatchOutcome {
        handled: ctx.handled(),
        repaint_requested: ctx.repaint_requested(),
        invalidation: ctx.invalidation(),
        stop_requested: ctx.stop_requested(),
        messages: ctx.take_messages(),
        animation_requests: ctx.take_animation_requests(),
        worker_requests: ctx.take_worker_requests(),
        recompose_nodes: ctx.take_recompose_nodes(),
        default_prevented: false,
    }
}

/// Dispatch a global event to every node in the tree.
///
/// This is used for runtime-global state updates (e.g. binding-hint payload
/// changes) where non-focused widgets such as `Footer` still need notification.
pub fn dispatch_event_broadcast_tree(tree: &mut WidgetTree, event: &Event) -> DispatchOutcome {
    let Some(root) = tree.root() else {
        return DispatchOutcome::default();
    };

    let mut aggregate = EventCtx::default();
    for node_id in tree.walk_depth_first(root) {
        let mut ctx = EventCtx::default();
        ctx.set_node_id(node_id);
        if let Some(node) = tree.get_mut(node_id) {
            let _dispatch_guard = set_dispatch_recipient(node_id);
            node.widget.on_event(event, &mut ctx);
        }
        aggregate.merge_from(ctx);
    }

    DispatchOutcome {
        handled: aggregate.handled(),
        repaint_requested: aggregate.repaint_requested(),
        invalidation: aggregate.invalidation(),
        stop_requested: aggregate.stop_requested(),
        messages: aggregate.take_messages(),
        animation_requests: aggregate.take_animation_requests(),
        worker_requests: aggregate.take_worker_requests(),
        recompose_nodes: aggregate.take_recompose_nodes(),
        default_prevented: false,
    }
}

/// Dispatch a scroll action through the tree, preferring focused → hovered → root.
pub(crate) fn dispatch_scroll_action_tree(
    tree: &mut WidgetTree,
    action: Action,
    hovered: Option<NodeId>,
) -> DispatchOutcome {
    let event = Event::Action(action);
    let focused = focused_node_id_tree(tree);

    if let Some(target) = focused {
        let outcome = dispatch_event_to_target_tree(tree, target, &event);
        if outcome.handled || outcome.repaint_requested || !outcome.messages.is_empty() {
            return outcome;
        }
    }

    if let Some(target) = hovered.filter(|id| Some(*id) != focused) {
        let outcome = dispatch_event_to_target_tree(tree, target, &event);
        if outcome.handled || outcome.repaint_requested || !outcome.messages.is_empty() {
            return outcome;
        }
    }

    // In tree mode, the arena root is often an app adapter wrapper while the
    // actual screen/content root is the first visible child. Route scroll
    // actions there before trying root-only fallback so PageUp/PageDown remain
    // deterministic regardless of focus/hover state.
    if let Some(root_id) = tree.root()
        && let Some(target) = tree.children(root_id).iter().copied().find(|child_id| {
            tree.get(*child_id).is_some_and(|node| {
                node.display && node.visibility == crate::style::Visibility::Visible
            })
        })
    {
        let outcome = dispatch_event_to_target_tree(tree, target, &event);
        if outcome.handled || outcome.repaint_requested || !outcome.messages.is_empty() {
            return outcome;
        }
    }

    dispatch_event_tree(tree, None, &event)
}

/// Dispatch mouse scroll to a target node, bubbling up the ancestor path.
pub(crate) fn dispatch_mouse_scroll_to_target_tree(
    tree: &mut WidgetTree,
    target: NodeId,
    delta_x: i32,
    delta_y: i32,
) -> DispatchOutcome {
    let mut ctx = EventCtx::default();
    let path = build_path_to_node(tree, target);

    // Bubble phase only: target → root (mouse scroll doesn't have a capture phase)
    for &node_id in path.iter().rev() {
        if let Some(node) = tree.get_mut(node_id) {
            let _dispatch_guard = set_dispatch_recipient(node_id);
            ctx.set_node_id(node_id);
            node.widget.on_mouse_scroll(delta_x, delta_y, &mut ctx);
        }
        if ctx.handled() {
            break;
        }
    }

    DispatchOutcome {
        handled: ctx.handled(),
        repaint_requested: ctx.repaint_requested(),
        invalidation: ctx.invalidation(),
        stop_requested: ctx.stop_requested(),
        messages: ctx.take_messages(),
        animation_requests: ctx.take_animation_requests(),
        worker_requests: ctx.take_worker_requests(),
        recompose_nodes: ctx.take_recompose_nodes(),
        default_prevented: false,
    }
}

/// Coalesce replaceable messages in the queue.
///
/// For each older/newer envelope pair with the same sender:
/// - if the newer envelope has `set_replaceable(true)`, it replaces older
///   envelopes of the same message variant;
/// - otherwise replacement is delegated to `Message::can_replace(pending)`.
///
/// This keeps envelope-level override support while making replacement
/// semantics message-driven (Python parity).
pub(crate) fn coalesce_message_queue(queue: &mut std::collections::VecDeque<MessageEnvelope>) {
    if queue.len() < 2 {
        return;
    }

    fn envelope_replaces_pending(newer: &MessageEnvelope, older: &MessageEnvelope) -> bool {
        if newer.can_replace() {
            return std::mem::discriminant(newer.message())
                == std::mem::discriminant(older.message());
        }
        newer.message().can_replace(older.message())
    }

    let mut keep = vec![true; queue.len()];

    // Walk backwards so later messages survive.
    for i in (0..queue.len()).rev() {
        for j in ((i + 1)..queue.len()).rev() {
            let older = &queue[i];
            let newer = &queue[j];
            if older.sender() != newer.sender() {
                continue;
            }
            if envelope_replaces_pending(newer, older) {
                keep[i] = false;
                break;
            }
        }
    }

    // Remove dropped envelopes (drain back-to-front to preserve indices).
    let mut idx = queue.len();
    while idx > 0 {
        idx -= 1;
        if !keep[idx] {
            queue.remove(idx);
        }
    }
}

/// Drain and dispatch a queue of messages through the arena tree.
///
/// Each `MessageEvent` is wrapped in a [`MessageEnvelope`] that controls
/// propagation.  Messages bubble from the sender node up to the root; a
/// handler can stop propagation via `ctx.set_handled()` (maps to
/// `envelope.stop()`).  Before dispatching each batch the queue is
/// coalesced according to message-level replacement semantics.
pub(crate) fn dispatch_message_queue_tree(
    tree: &mut WidgetTree,
    initial: Vec<MessageEvent>,
) -> DispatchOutcome {
    use std::collections::VecDeque;

    let mut handled = false;
    let mut repaint_requested = false;
    let mut invalidation = crate::event::InvalidationFlags::default();
    let mut stop_requested = false;
    let mut default_prevented = false;
    let mut emitted: Vec<MessageEvent> = Vec::new();
    let mut animation_requests: Vec<AnimationRequest> = Vec::new();
    let mut worker_requests: Vec<crate::worker::WorkerRequest> = Vec::new();
    let mut recompose_nodes: Vec<NodeId> = Vec::new();

    let mut queue: VecDeque<MessageEnvelope> =
        initial.into_iter().map(MessageEnvelope::new).collect();

    coalesce_message_queue(&mut queue);

    const LIMIT: usize = 1024;
    let mut processed = 0usize;

    while let Some(mut envelope) = queue.pop_front() {
        processed += 1;
        if processed > LIMIT {
            debug_message("[dispatch_message_queue_tree] limit reached, dropping remaining");
            break;
        }

        let mut ctx = EventCtx::default();
        dispatch_message_bubble(tree, &mut envelope, &mut ctx);
        handled |= ctx.handled();
        repaint_requested |= ctx.repaint_requested();
        invalidation.merge(ctx.invalidation());
        stop_requested |= ctx.stop_requested();
        default_prevented |= envelope.is_default_prevented();
        let next = ctx.take_messages();
        let mut next_anims = ctx.take_animation_requests();
        let mut next_workers = ctx.take_worker_requests();
        let mut next_recompose = ctx.take_recompose_nodes();
        if !next.is_empty() {
            let next_envelopes: VecDeque<MessageEnvelope> = next
                .iter()
                .map(|evt| MessageEnvelope::new(evt.clone()))
                .collect();
            queue.extend(next_envelopes);
            // Re-coalesce the full pending queue so that newly emitted
            // replaceable messages can deduplicate against older entries.
            coalesce_message_queue(&mut queue);
            emitted.extend(next);
        }
        if !next_anims.is_empty() {
            animation_requests.append(&mut next_anims);
        }
        if !next_workers.is_empty() {
            worker_requests.append(&mut next_workers);
        }
        if !next_recompose.is_empty() {
            recompose_nodes.append(&mut next_recompose);
        }
    }

    DispatchOutcome {
        handled,
        repaint_requested,
        invalidation,
        stop_requested,
        messages: emitted,
        animation_requests,
        worker_requests,
        recompose_nodes,
        default_prevented,
    }
}

/// Bubble a single message from its sender up to the tree root.
///
/// The walk order is `[sender, parent, …, root]`.  At each node,
/// `widget.on_message()` is called.  If the handler sets `ctx.handled()`,
/// propagation stops (`envelope.stop()` is called).  When the sender is not
/// present in the tree, the message falls back to a depth-first broadcast
/// so that globally-targeted messages (e.g. overlay commands) still reach
/// their recipient.
fn dispatch_message_bubble(
    tree: &mut WidgetTree,
    envelope: &mut MessageEnvelope,
    ctx: &mut EventCtx,
) {
    // Sync the envelope's promoted/overridden control into the event so that
    // widget `on_message(&MessageEvent, …)` handlers see the correct value.
    envelope.event.control = envelope.control();

    let sender = envelope.sender();
    let bubble_path = build_path_to_node(tree, sender); // [root, …, parent, sender]

    if bubble_path.is_empty() {
        // Sender not in tree — fall back to depth-first broadcast so
        // globally-addressed messages (overlay commands, etc.) still work.
        let root = match tree.root() {
            Some(r) => r,
            None => return,
        };
        let node_ids = tree.walk_depth_first(root);
        for node_id in node_ids {
            if envelope.is_stopped() || ctx.handled() {
                return;
            }
            if let Some(node) = tree.get_mut(node_id) {
                let _dispatch_guard = set_dispatch_recipient(node_id);
                ctx.set_node_id(node_id);
                node.widget.on_message(&envelope.event, ctx);
                if ctx.handled() {
                    envelope.stop();
                }
            }
        }
        return;
    }

    // Bubble: sender → parent → … → root (reverse of build_path_to_node).
    for &node_id in bubble_path.iter().rev() {
        if envelope.is_stopped() {
            break;
        }
        if let Some(node) = tree.get_mut(node_id) {
            let _dispatch_guard = set_dispatch_recipient(node_id);
            ctx.set_node_id(node_id);
            node.widget.on_message(&envelope.event, ctx);
            if ctx.handled() {
                envelope.stop();
            }
        }
    }
}

/// Return the focused widget's help markup, if any.
pub(crate) fn focused_help_metadata_tree(tree: &WidgetTree) -> Option<(NodeId, String)> {
    let root = tree.root()?;
    for node_id in tree.walk_depth_first(root) {
        let node = tree.get(node_id)?;
        if node.widget.has_focus() {
            let help = node.widget.help_markup().map(str::trim).unwrap_or_default();
            if !help.is_empty() {
                return Some((node_id, help.to_string()));
            }
            return None;
        }
    }
    None
}

/// Check whether a `KeyEventData` matches a binding key specification.
///
/// The binding key may contain comma-separated alternatives (e.g. `"j,down"`).
/// Matching is performed against the key's `aliases()` which include the
/// canonical name plus any alias variants.
fn key_matches_binding(key: &KeyEventData, binding_key: &str) -> bool {
    let aliases = key.aliases();
    binding_key
        .split(',')
        .map(str::trim)
        .any(|alt| aliases.iter().any(|a| *a == alt))
}

fn format_binding_key_display(binding_key: &str) -> String {
    binding_key
        .split(',')
        .map(str::trim)
        .filter(|part| !part.is_empty())
        .map(|part| {
            if matches!(part, "tab" | "shift+tab") {
                part.to_string()
            } else {
                format_key_display(part)
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

/// Walk the focused widget chain and find the first matching `BindingDecl`.
///
/// Phase 1: priority bindings (focused→root).
/// Phase 2: normal bindings (focused→root).
///
/// Returns `(node_id, action_string)` of the first match, or `None`.
pub(crate) fn match_binding_tree(
    tree: &WidgetTree,
    key: &KeyEventData,
) -> Option<(NodeId, String)> {
    let path = if let Some(focus_id) = focused_node_id_tree(tree) {
        build_path_to_node(tree, focus_id)
    } else {
        // No focused widget: fall back to root + single-child chain so
        // app-level/root declarative bindings still work.
        let Some(root) = tree.root() else {
            return None;
        };
        let mut path = vec![root];
        let mut current = root;
        loop {
            let children = tree.children(current);
            if children.len() != 1 {
                break;
            }
            current = children[0];
            path.push(current);
        }
        path
    };

    // Phase 1: priority bindings (focused → root)
    for &node_id in path.iter().rev() {
        if let Some(node) = tree.get(node_id) {
            for binding in node.widget.bindings() {
                if binding.priority && key_matches_binding(key, &binding.key) {
                    return Some((node_id, binding.action.clone()));
                }
            }
        }
    }

    // Phase 2: normal bindings (focused → root)
    for &node_id in path.iter().rev() {
        if let Some(node) = tree.get(node_id) {
            for binding in node.widget.bindings() {
                if !binding.priority && key_matches_binding(key, &binding.key) {
                    return Some((node_id, binding.action.clone()));
                }
            }
        }
    }

    None
}

/// Collect binding hints along the focused path (focused→root).
///
/// If no widget has focus, falls back to root + single-child chain.
pub(crate) fn active_binding_hints_tree(tree: &WidgetTree) -> (Vec<BindingHint>, Vec<NodeId>) {
    if let Some(focus_id) = focused_node_id_tree(tree) {
        let path = build_path_to_node(tree, focus_id);
        let mut hints = Vec::new();
        let mut sources = Vec::new();
        for &node_id in path.iter().rev() {
            if let Some(node) = tree.get(node_id) {
                sources.push(node_id);
                let namespace = node.widget.action_namespace();
                hints.extend(node.widget.binding_hints().into_iter().map(
                    |hint| match hint.namespace {
                        Some(_) => hint,
                        None => hint.with_namespace(namespace),
                    },
                ));
                // Also include hints derived from declarative bindings.
                for decl in node.widget.bindings() {
                    let mut hint = BindingHint::new(&decl.key, &decl.description)
                        .hidden(!decl.show)
                        .with_key_display(format_binding_key_display(&decl.key))
                        .with_priority(decl.priority)
                        .with_action(&decl.action)
                        .with_namespace(
                            decl.namespace
                                .clone()
                                .unwrap_or_else(|| namespace.to_string()),
                        );
                    if let Some(tooltip) = &decl.tooltip {
                        hint = hint.with_tooltip(tooltip.clone());
                    }
                    hints.push(hint);
                }
            }
        }
        return (hints, sources);
    }

    // No focus — walk root + single-child chain (matches old `collect_no_focus_scope`).
    collect_root_scope_hints(tree)
}

/// Walk from root along single-child chains collecting hints (no-focus fallback).
fn collect_root_scope_hints(tree: &WidgetTree) -> (Vec<BindingHint>, Vec<NodeId>) {
    let mut hints = Vec::new();
    let mut sources = Vec::new();
    let Some(root) = tree.root() else {
        return (hints, sources);
    };

    let mut current = root;
    loop {
        if let Some(node) = tree.get(current) {
            sources.push(current);
            let namespace = node.widget.action_namespace();
            hints.extend(node.widget.binding_hints().into_iter().map(
                |hint| match hint.namespace {
                    Some(_) => hint,
                    None => hint.with_namespace(namespace),
                },
            ));
            for decl in node.widget.bindings() {
                let mut hint = BindingHint::new(&decl.key, &decl.description)
                    .hidden(!decl.show)
                    .with_key_display(format_binding_key_display(&decl.key))
                    .with_priority(decl.priority)
                    .with_action(&decl.action)
                    .with_namespace(
                        decl.namespace
                            .clone()
                            .unwrap_or_else(|| namespace.to_string()),
                    );
                if let Some(tooltip) = &decl.tooltip {
                    hint = hint.with_tooltip(tooltip.clone());
                }
                hints.push(hint);
            }
            let children = tree.children(current);
            if children.len() == 1 {
                current = children[0];
            } else {
                break;
            }
        } else {
            break;
        }
    }

    (hints, sources)
}

#[cfg(test)]
mod message_tests {
    use super::*;
    use crate::event::{MouseDownEvent, MouseUpEvent};
    use crate::keys::KeyEventData;
    use crate::message::Message;
    use crate::runtime::render::{apply_layout_info_tree_from_layout_rects, run_layout_pass};
    use crate::widget_tree::WidgetTree;
    use crate::widgets::{AppRoot, Button, Label, ScrollView};
    use crossterm::event::{KeyCode, KeyModifiers};
    use rich_rs::{Console, ConsoleOptions, Segments};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    struct HintNode {
        focused: bool,
        hints: Vec<BindingHint>,
        help_markup: Option<String>,
    }

    impl HintNode {
        fn new(focused: bool, hints: Vec<BindingHint>) -> Self {
            Self {
                focused,
                hints,
                help_markup: None,
            }
        }

        fn with_help(mut self, help_markup: impl Into<String>) -> Self {
            self.help_markup = Some(help_markup.into());
            self
        }
    }

    impl Widget for HintNode {
        fn render(&self, _console: &Console, _options: &ConsoleOptions) -> Segments {
            Segments::new()
        }

        fn binding_hints(&self) -> Vec<BindingHint> {
            self.hints.clone()
        }

        fn help_markup(&self) -> Option<&str> {
            self.help_markup.as_deref()
        }

        fn has_focus(&self) -> bool {
            self.focused
        }

        fn set_focus(&mut self, focused: bool) {
            self.focused = focused;
        }
    }

    struct Child;

    impl Child {
        fn new() -> Self {
            Self
        }
    }

    impl Widget for Child {
        fn render(&self, _console: &Console, _options: &ConsoleOptions) -> rich_rs::Segments {
            rich_rs::Segments::new()
        }

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

        fn on_event(&mut self, event: &Event, ctx: &mut EventCtx) {
            if let Event::Key(key) = event {
                if matches!(key.code, KeyCode::Char('x')) {
                    ctx.post_message(Message::InputChanged(crate::message::InputChanged {
                        value: "ok".into(),
                        validation: crate::validation::ValidationResult::success(),
                    }));
                    ctx.set_handled();
                }
            }
        }
    }

    struct Parent {
        child: Box<dyn Widget>,
        seen: usize,
    }

    impl Parent {
        fn new(child: impl Widget + 'static) -> Self {
            Self {
                child: Box::new(child),
                seen: 0,
            }
        }
    }

    impl Widget for Parent {
        fn render(&self, _console: &Console, _options: &ConsoleOptions) -> rich_rs::Segments {
            rich_rs::Segments::new()
        }

        fn on_event_capture(&mut self, event: &Event, ctx: &mut EventCtx) {
            self.child.on_event_capture(event, ctx);
        }

        fn on_event(&mut self, event: &Event, ctx: &mut EventCtx) {
            self.child.on_event(event, ctx);
        }

        fn on_message(&mut self, message: &crate::message::MessageEvent, ctx: &mut EventCtx) {
            if matches!(message.message, Message::InputChanged(..)) {
                self.seen += 1;
                ctx.set_handled();
            }
        }
    }

    #[test]
    fn messages_bubble_to_ancestor_handlers() {
        let mut root = Parent::new(Child::new());
        let key = KeyEventData::from_crossterm(crossterm::event::KeyEvent::new(
            KeyCode::Char('x'),
            KeyModifiers::empty(),
        ));
        let outcome = dispatch_event(&mut root, Event::Key(key));
        assert_eq!(outcome.messages.len(), 1);

        // Deliver message directly to root for this unit test.
        let mut ctx = EventCtx::default();
        root.on_message(&outcome.messages[0], &mut ctx);
        assert!(ctx.handled());
        assert_eq!(root.seen, 1);
    }

    struct Receiver {
        child: Box<dyn Widget>,
        seen: usize,
    }

    impl Receiver {
        fn new_leaf() -> Self {
            Self {
                child: Box::new(Label::new("")),
                seen: 0,
            }
        }
    }

    impl Widget for Receiver {
        fn render(&self, _console: &Console, _options: &ConsoleOptions) -> rich_rs::Segments {
            rich_rs::Segments::new()
        }
        fn on_event_capture(&mut self, event: &Event, ctx: &mut EventCtx) {
            self.child.on_event_capture(event, ctx);
        }
        fn on_event(&mut self, event: &Event, ctx: &mut EventCtx) {
            self.child.on_event(event, ctx);
        }
        fn on_message(&mut self, message: &crate::message::MessageEvent, ctx: &mut EventCtx) {
            if matches!(message.message, Message::ButtonPressed(..)) {
                self.seen += 1;
                ctx.set_handled();
            }
        }
    }

    #[test]
    fn button_pressed_message_reaches_ancestor() {
        // Build tree: root(AppRoot) → recv(Receiver) → button(Button)
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(AppRoot::new()));
        let recv_id = tree.mount(root_id, Box::new(Receiver::new_leaf()));
        let button_id = tree.mount(recv_id, Box::new(Button::new("x")));

        // Button checks target == self.node_id(). Tree dispatch sets dispatch
        // context to button_id, so events must carry button_id as target.
        let down = dispatch_event_to_target_tree(
            &mut tree,
            button_id,
            &Event::MouseDown(MouseDownEvent {
                target: button_id,
                screen_x: 0,
                screen_y: 0,
                x: 0,
                y: 0,
            }),
        );
        let _ = dispatch_message_queue_tree(&mut tree, down.messages);

        let up = dispatch_event_to_target_tree(
            &mut tree,
            button_id,
            &Event::MouseUp(MouseUpEvent {
                target: Some(button_id),
                screen_x: 0,
                screen_y: 0,
                x: 0,
                y: 0,
            }),
        );
        assert!(!up.messages.is_empty());
        let routed = dispatch_message_queue_tree(&mut tree, up.messages);
        assert!(routed.handled);
    }

    #[test]
    fn button_pressed_message_survives_scrollview_forwarding() {
        // Build tree: root(AppRoot) → recv(Receiver) → scroll(ScrollView) → button(Button)
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(AppRoot::new()));
        let recv_id = tree.mount(root_id, Box::new(Receiver::new_leaf()));
        let scroll_id = tree.mount(recv_id, Box::new(ScrollView::new(Label::new(""))));
        let button_id = tree.mount(scroll_id, Box::new(Button::new("x")));

        // Button checks target == self.node_id(). Tree dispatch sets dispatch
        // context to button_id, so events must carry button_id as target.
        let down = dispatch_event_to_target_tree(
            &mut tree,
            button_id,
            &Event::MouseDown(MouseDownEvent {
                target: button_id,
                screen_x: 0,
                screen_y: 0,
                x: 0,
                y: 0,
            }),
        );
        let _ = dispatch_message_queue_tree(&mut tree, down.messages);

        let up = dispatch_event_to_target_tree(
            &mut tree,
            button_id,
            &Event::MouseUp(MouseUpEvent {
                target: Some(button_id),
                screen_x: 0,
                screen_y: 0,
                x: 0,
                y: 0,
            }),
        );
        assert_eq!(up.messages.len(), 1);
        let routed = dispatch_message_queue_tree(&mut tree, up.messages);
        assert!(routed.handled);
    }

    struct ScrollReceiver {
        seen: usize,
    }

    impl Widget for ScrollReceiver {
        fn render(&self, _console: &Console, _options: &ConsoleOptions) -> rich_rs::Segments {
            rich_rs::Segments::new()
        }
        fn on_mouse_scroll(&mut self, _delta_x: i32, _delta_y: i32, ctx: &mut EventCtx) {
            self.seen += 1;
            ctx.set_handled();
        }
    }

    #[test]
    fn mouse_scroll_bubbles_to_ancestor_handlers() {
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(ScrollReceiver { seen: 0 }));
        let button_id = tree.mount(root_id, Box::new(Button::new("x")));

        // Button doesn't handle scroll, so it bubbles to ScrollReceiver.
        let outcome = dispatch_mouse_scroll_to_target_tree(&mut tree, button_id, 0, 1);
        assert!(outcome.handled);
    }

    #[test]
    fn dedicated_scrollbar_click_updates_scrollview_offset() {
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(AppRoot::new()));
        let scroll_id = tree.mount(
            root_id,
            Box::new(ScrollView::new(Label::new("line\n".repeat(120)))),
        );

        // Enter tree mode and mount ScrollView dedicated scrollbar children.
        let extracted = {
            let node = tree.get_mut(scroll_id).expect("scrollview node");
            node.widget.take_composed_children()
        };
        for child in extracted {
            tree.mount(scroll_id, child);
        }

        run_layout_pass(&mut tree, (40, 10));
        apply_layout_info_tree_from_layout_rects(&mut tree);

        let vbar_id = tree
            .children(scroll_id)
            .iter()
            .copied()
            .find(|child_id| {
                tree.get(*child_id).and_then(|node| node.widget.style_id())
                    == Some("__scrollview_vscrollbar")
            })
            .expect("vertical scrollbar child must exist");

        // Click below the thumb to trigger page-down behavior.
        let down = dispatch_event_to_target_tree(
            &mut tree,
            vbar_id,
            &Event::MouseDown(MouseDownEvent {
                target: vbar_id,
                screen_x: 39,
                screen_y: 8,
                x: 0,
                y: 8,
            }),
        );
        let _ = dispatch_message_queue_tree(&mut tree, down.messages);

        let offset_y = tree
            .get(scroll_id)
            .expect("scrollview node")
            .widget
            .scroll_offset()
            .1;
        assert!(
            offset_y > 0,
            "clicking the dedicated vertical scrollbar should advance offset, got {offset_y}"
        );
    }

    struct ScrollSink {
        focused: bool,
        hits: Arc<AtomicUsize>,
    }

    impl ScrollSink {
        fn new(focused: bool, hits: Arc<AtomicUsize>) -> Self {
            Self { focused, hits }
        }
    }

    impl Widget for ScrollSink {
        fn render(&self, _console: &Console, _options: &ConsoleOptions) -> rich_rs::Segments {
            rich_rs::Segments::new()
        }

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

        fn set_focus(&mut self, focused: bool) {
            self.focused = focused;
        }

        fn has_focus(&self) -> bool {
            self.focused
        }

        fn on_event(&mut self, event: &Event, ctx: &mut EventCtx) {
            if matches!(event, Event::Action(Action::ScrollDown)) {
                self.hits.fetch_add(1, Ordering::Relaxed);
                ctx.set_handled();
            }
        }
    }

    #[test]
    fn scroll_actions_prefer_focused_target() {
        let first_hits = Arc::new(AtomicUsize::new(0));
        let second_hits = Arc::new(AtomicUsize::new(0));

        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(AppRoot::new()));
        let _first_id = tree.mount(
            root_id,
            Box::new(ScrollSink::new(false, first_hits.clone())),
        );
        let _second_id = tree.mount(
            root_id,
            Box::new(ScrollSink::new(true, second_hits.clone())),
        );

        let outcome = dispatch_scroll_action_tree(&mut tree, Action::ScrollDown, None);
        assert!(outcome.handled);
        assert_eq!(first_hits.load(Ordering::Relaxed), 0);
        assert_eq!(second_hits.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn scroll_actions_fallback_to_hovered_when_unfocused() {
        let first_hits = Arc::new(AtomicUsize::new(0));
        let second_hits = Arc::new(AtomicUsize::new(0));

        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(AppRoot::new()));
        let _first_id = tree.mount(
            root_id,
            Box::new(ScrollSink::new(false, first_hits.clone())),
        );
        let second_id = tree.mount(
            root_id,
            Box::new(ScrollSink::new(false, second_hits.clone())),
        );

        let outcome = dispatch_scroll_action_tree(&mut tree, Action::ScrollDown, Some(second_id));
        assert!(outcome.handled);
        assert_eq!(first_hits.load(Ordering::Relaxed), 0);
        assert_eq!(second_hits.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn scroll_actions_fallback_to_global_when_no_target_handles() {
        // Without focus or hover, scroll dispatches to the first visible child
        // under the arena root (screen/content root fallback).
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(AppRoot::new()));
        let first_hits = Arc::new(AtomicUsize::new(0));
        let _first_id = tree.mount(
            root_id,
            Box::new(ScrollSink::new(false, first_hits.clone())),
        );

        let outcome = dispatch_scroll_action_tree(&mut tree, Action::ScrollDown, None);
        assert!(outcome.handled);
        assert_eq!(first_hits.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn focused_path_binding_hints_collects_ancestor_chain() {
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(HintNode::new(
            false,
            vec![BindingHint::new("tab", "next focus")],
        )));
        let mid_id = tree.mount(
            root_id,
            Box::new(HintNode::new(false, vec![BindingHint::new("left", "back")])),
        );
        let _leaf_id = tree.mount(
            mid_id,
            Box::new(HintNode::new(
                true,
                vec![BindingHint::new("enter", "activate")],
            )),
        );

        let (hints, _sources) = active_binding_hints_tree(&tree);
        assert_eq!(
            hints,
            vec![
                BindingHint::new("enter", "activate").with_namespace(""),
                BindingHint::new("left", "back").with_namespace(""),
                BindingHint::new("tab", "next focus").with_namespace("")
            ]
        );
    }

    #[test]
    fn focused_path_binding_hints_returns_empty_without_focus() {
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(HintNode::new(
            false,
            vec![BindingHint::new("tab", "next")],
        )));
        let _leaf_id = tree.mount(
            root_id,
            Box::new(HintNode::new(
                false,
                vec![BindingHint::new("enter", "activate")],
            )),
        );

        // No focused node — falls back to root scope (single-child chain).
        let (hints, _) = active_binding_hints_tree(&tree);
        // Returns root + leaf hints via single-child fallback.
        assert!(!hints.is_empty());
    }

    #[test]
    fn focused_help_metadata_returns_focused_widget_help() {
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(HintNode::new(
            false,
            vec![BindingHint::new("tab", "next")],
        )));
        let _child_id = tree.mount(
            root_id,
            Box::new(
                HintNode::new(true, vec![BindingHint::new("enter", "activate")])
                    .with_help("## Focused help\nUse enter"),
            ),
        );

        let focused = focused_help_metadata_tree(&tree);
        assert!(matches!(
            focused.as_ref(),
            Some((_, markup)) if markup == "## Focused help\nUse enter"
        ));
    }

    #[test]
    fn focused_help_metadata_returns_none_without_focus() {
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(HintNode::new(
            false,
            vec![BindingHint::new("tab", "next")],
        )));
        let _child_id = tree.mount(
            root_id,
            Box::new(
                HintNode::new(false, vec![BindingHint::new("enter", "activate")])
                    .with_help("## Focused help"),
            ),
        );

        assert!(focused_help_metadata_tree(&tree).is_none());
    }

    #[test]
    fn focused_path_binding_hints_tracks_focus_transitions() {
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(HintNode::new(
            false,
            vec![BindingHint::new("tab", "next focus")],
        )));
        let child_id = tree.mount(
            root_id,
            Box::new(HintNode::new(
                true,
                vec![BindingHint::new("left/right", "switch tab")],
            )),
        );

        let (first, _) = active_binding_hints_tree(&tree);
        assert_eq!(
            first,
            vec![
                BindingHint::new("left/right", "switch tab").with_namespace(""),
                BindingHint::new("tab", "next focus").with_namespace(""),
            ]
        );

        // Transition focus from child to root.
        tree.get_mut(child_id).unwrap().widget.set_focus(false);
        tree.get_mut(root_id).unwrap().widget.set_focus(true);

        let (second, _) = active_binding_hints_tree(&tree);
        assert_eq!(
            second,
            vec![BindingHint::new("tab", "next focus").with_namespace("")]
        );
    }

    #[test]
    fn focused_help_metadata_tracks_focus_transitions() {
        // State 1: child has focus + help markup.
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(HintNode::new(
            false,
            vec![BindingHint::new("tab", "next focus")],
        )));
        let _child_id = tree.mount(
            root_id,
            Box::new(
                HintNode::new(true, vec![BindingHint::new("left/right", "switch tab")])
                    .with_help("## First"),
            ),
        );

        let first = focused_help_metadata_tree(&tree);
        assert!(matches!(
            first.as_ref(),
            Some((_, markup)) if markup == "## First"
        ));

        // State 2: focus moves to root which has its own help markup.
        let mut tree2 = WidgetTree::new();
        let _root_id2 = tree2.set_root(Box::new(
            HintNode::new(true, vec![BindingHint::new("tab", "next focus")]).with_help("## Second"),
        ));
        let _child_id2 = tree2.mount(
            _root_id2,
            Box::new(
                HintNode::new(false, vec![BindingHint::new("left/right", "switch tab")])
                    .with_help("## First"),
            ),
        );

        let second = focused_help_metadata_tree(&tree2);
        assert!(matches!(
            second.as_ref(),
            Some((_, markup)) if markup == "## Second"
        ));
    }

    #[test]
    fn active_binding_hints_returns_focused_chain_and_sources() {
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(HintNode::new(
            false,
            vec![BindingHint::new("tab", "next focus")],
        )));
        let mid_id = tree.mount(
            root_id,
            Box::new(HintNode::new(false, vec![BindingHint::new("left", "back")])),
        );
        let _leaf_id = tree.mount(
            mid_id,
            Box::new(HintNode::new(
                true,
                vec![BindingHint::new("enter", "activate")],
            )),
        );

        let (hints, sources) = active_binding_hints_tree(&tree);
        assert_eq!(
            hints,
            vec![
                BindingHint::new("enter", "activate").with_namespace(""),
                BindingHint::new("left", "back").with_namespace(""),
                BindingHint::new("tab", "next focus").with_namespace("")
            ]
        );
        assert_eq!(sources.len(), 3);
    }

    #[test]
    fn active_binding_hints_falls_back_to_single_child_scope_without_focus() {
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(HintNode::new(
            false,
            vec![BindingHint::new("q", "quit")],
        )));
        let _child_id = tree.mount(
            root_id,
            Box::new(HintNode::new(false, vec![BindingHint::new("f1", "help")])),
        );

        let (hints, sources) = active_binding_hints_tree(&tree);
        assert_eq!(
            hints,
            vec![
                BindingHint::new("q", "quit").with_namespace(""),
                BindingHint::new("f1", "help").with_namespace("")
            ]
        );
        assert_eq!(sources.len(), 2);
    }

    struct BindingEventProbe {
        focused: bool,
        hits: Arc<AtomicUsize>,
    }

    impl BindingEventProbe {
        fn new(focused: bool, hits: Arc<AtomicUsize>) -> Self {
            Self { focused, hits }
        }
    }

    impl Widget for BindingEventProbe {
        fn render(&self, _console: &Console, _options: &ConsoleOptions) -> Segments {
            Segments::new()
        }

        fn has_focus(&self) -> bool {
            self.focused
        }

        fn set_focus(&mut self, focused: bool) {
            self.focused = focused;
        }

        fn on_event(&mut self, event: &Event, _ctx: &mut EventCtx) {
            if matches!(event, Event::BindingsChanged(..)) {
                self.hits.fetch_add(1, Ordering::Relaxed);
            }
        }
    }

    #[test]
    fn broadcast_event_reaches_non_focused_siblings() {
        let focused_hits = Arc::new(AtomicUsize::new(0));
        let sibling_hits = Arc::new(AtomicUsize::new(0));

        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(AppRoot::new()));
        let _focused = tree.mount(
            root_id,
            Box::new(BindingEventProbe::new(true, focused_hits.clone())),
        );
        let _sibling = tree.mount(
            root_id,
            Box::new(BindingEventProbe::new(false, sibling_hits.clone())),
        );

        let _ = dispatch_event_broadcast_tree(
            &mut tree,
            &Event::BindingsChanged(vec![BindingHint::new("l", "Leto")]),
        );

        assert_eq!(focused_hits.load(Ordering::Relaxed), 1);
        assert_eq!(sibling_hits.load(Ordering::Relaxed), 1);
    }
}

#[cfg(test)]
mod envelope_tests {
    use super::*;
    use crate::message::{Message, MessageEnvelope, MessageEvent};
    use crate::node_id::node_id_from_ffi;
    use crate::widget_tree::WidgetTree;
    use crate::widgets::Label;
    use rich_rs::{Console, ConsoleOptions, Segments};
    use std::collections::VecDeque;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    // -----------------------------------------------------------------------
    // Test widget: counts how many times on_message is called
    // -----------------------------------------------------------------------
    struct MessageCounter {
        count: Arc<AtomicUsize>,
        stop_on_match: bool,
    }

    impl MessageCounter {
        fn new(count: Arc<AtomicUsize>) -> Self {
            Self {
                count,
                stop_on_match: false,
            }
        }

        fn stopping(count: Arc<AtomicUsize>) -> Self {
            Self {
                count,
                stop_on_match: true,
            }
        }
    }

    impl Widget for MessageCounter {
        fn render(&self, _console: &Console, _options: &ConsoleOptions) -> Segments {
            Segments::new()
        }

        fn on_message(&mut self, message: &MessageEvent, ctx: &mut EventCtx) {
            if matches!(message.message, Message::ButtonPressed(..)) {
                self.count.fetch_add(1, Ordering::Relaxed);
                if self.stop_on_match {
                    ctx.set_handled();
                }
            }
        }
    }

    /// Helper: build a MessageEvent from a sender FFI id and a Message.
    fn msg_event(sender_ffi: u64, message: Message) -> MessageEvent {
        MessageEvent {
            sender: node_id_from_ffi(sender_ffi),
            message,
            control: None,
        }
    }

    // =====================================================================
    // P4-02: Envelope bubble dispatch tests
    // =====================================================================

    #[test]
    fn envelope_message_bubbles_from_sender_to_root() {
        // Tree: root → mid → leaf (sender)
        let root_count = Arc::new(AtomicUsize::new(0));
        let mid_count = Arc::new(AtomicUsize::new(0));
        let leaf_count = Arc::new(AtomicUsize::new(0));

        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(MessageCounter::new(root_count.clone())));
        let mid_id = tree.mount(root_id, Box::new(MessageCounter::new(mid_count.clone())));
        let leaf_id = tree.mount(mid_id, Box::new(MessageCounter::new(leaf_count.clone())));

        let messages = vec![MessageEvent {
            sender: leaf_id,
            message: Message::ButtonPressed(crate::message::ButtonPressed {
                description: "test".into(),
                button_id: None,
            }),
            control: None,
        }];

        let outcome = dispatch_message_queue_tree(&mut tree, messages);
        // All three nodes on the bubble path should see the message.
        assert!(
            leaf_count.load(Ordering::Relaxed) >= 1,
            "leaf should see message"
        );
        assert!(
            mid_count.load(Ordering::Relaxed) >= 1,
            "mid should see message"
        );
        assert!(
            root_count.load(Ordering::Relaxed) >= 1,
            "root should see message"
        );
        assert!(outcome.handled || leaf_count.load(Ordering::Relaxed) > 0);
    }

    #[test]
    fn envelope_stop_halts_propagation() {
        // Tree: root → mid(stops) → leaf (sender)
        // Mid stops propagation, so root should NOT see the message.
        let root_count = Arc::new(AtomicUsize::new(0));
        let mid_count = Arc::new(AtomicUsize::new(0));
        let leaf_count = Arc::new(AtomicUsize::new(0));

        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(MessageCounter::new(root_count.clone())));
        let mid_id = tree.mount(
            root_id,
            Box::new(MessageCounter::stopping(mid_count.clone())),
        );
        let leaf_id = tree.mount(mid_id, Box::new(MessageCounter::new(leaf_count.clone())));

        let messages = vec![MessageEvent {
            sender: leaf_id,
            message: Message::ButtonPressed(crate::message::ButtonPressed {
                description: "stop".into(),
                button_id: None,
            }),
            control: None,
        }];

        let outcome = dispatch_message_queue_tree(&mut tree, messages);
        assert!(outcome.handled, "mid should have handled it");
        // Leaf sees it first (bubble starts at sender), mid stops.
        assert!(leaf_count.load(Ordering::Relaxed) >= 1, "leaf sees message");
        assert!(
            mid_count.load(Ordering::Relaxed) >= 1,
            "mid sees message and stops"
        );
        assert_eq!(
            root_count.load(Ordering::Relaxed),
            0,
            "root should NOT see message after stop"
        );
    }

    #[test]
    fn envelope_sender_not_in_tree_falls_back_to_broadcast() {
        // Message from unknown sender should still reach nodes via broadcast fallback.
        let root_count = Arc::new(AtomicUsize::new(0));

        let mut tree = WidgetTree::new();
        let _root_id = tree.set_root(Box::new(MessageCounter::new(root_count.clone())));

        let messages = vec![msg_event(
            99999,
            Message::ButtonPressed(crate::message::ButtonPressed {
                description: "ghost".into(),
                button_id: None,
            }),
        )];

        dispatch_message_queue_tree(&mut tree, messages);
        assert!(
            root_count.load(Ordering::Relaxed) >= 1,
            "broadcast fallback should reach root"
        );
    }

    #[test]
    fn envelope_default_prevented_propagates_to_outcome() {
        // Currently default_prevented tracks through the envelope. Since widgets
        // don't have direct access to prevent_default() yet (Widget trait takes
        // &MessageEvent, not &mut MessageEnvelope), this test verifies the
        // field exists and defaults to false for normal dispatch.
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(Label::new("x")));

        let messages = vec![MessageEvent {
            sender: root_id,
            message: Message::ButtonPressed(crate::message::ButtonPressed {
                description: "dp".into(),
                button_id: None,
            }),
            control: None,
        }];

        let outcome = dispatch_message_queue_tree(&mut tree, messages);
        assert!(
            !outcome.default_prevented,
            "default_prevented should be false when no handler calls prevent_default()"
        );
    }

    // =====================================================================
    // P4-14: Message queue coalescing tests
    // =====================================================================

    #[test]
    fn coalesce_removes_earlier_replaceable_same_sender_same_variant() {
        let sender = node_id_from_ffi(1);
        let mut queue: VecDeque<MessageEnvelope> = VecDeque::new();

        // Two InputChanged from the same sender — both replaceable.
        let mut env1 = MessageEnvelope::new(MessageEvent {
            sender,
            message: Message::InputChanged(crate::message::InputChanged {
                value: "a".into(),
                validation: crate::validation::ValidationResult::success(),
            }),
            control: None,
        });
        env1.set_replaceable(true);

        let mut env2 = MessageEnvelope::new(MessageEvent {
            sender,
            message: Message::InputChanged(crate::message::InputChanged {
                value: "ab".into(),
                validation: crate::validation::ValidationResult::success(),
            }),
            control: None,
        });
        env2.set_replaceable(true);

        queue.push_back(env1);
        queue.push_back(env2);
        coalesce_message_queue(&mut queue);

        assert_eq!(queue.len(), 1, "should coalesce to one message");
        match queue[0].message() {
            Message::InputChanged(crate::message::InputChanged { value, .. }) => {
                assert_eq!(value, "ab", "should keep the latest value");
            }
            other => panic!("unexpected message: {:?}", other),
        }
    }

    #[test]
    fn coalesce_preserves_non_replaceable_messages() {
        let sender = node_id_from_ffi(1);
        let mut queue: VecDeque<MessageEnvelope> = VecDeque::new();

        // Two ButtonPressed — not replaceable by default.
        let env1 = MessageEnvelope::new(MessageEvent {
            sender,
            message: Message::ButtonPressed(crate::message::ButtonPressed {
                description: "first".into(),
                button_id: None,
            }),
            control: None,
        });
        let env2 = MessageEnvelope::new(MessageEvent {
            sender,
            message: Message::ButtonPressed(crate::message::ButtonPressed {
                description: "second".into(),
                button_id: None,
            }),
            control: None,
        });

        queue.push_back(env1);
        queue.push_back(env2);
        coalesce_message_queue(&mut queue);

        assert_eq!(
            queue.len(),
            2,
            "non-replaceable messages should all survive"
        );
    }

    #[test]
    fn coalesce_different_senders_preserved() {
        let sender_a = node_id_from_ffi(1);
        let sender_b = node_id_from_ffi(2);
        let mut queue: VecDeque<MessageEnvelope> = VecDeque::new();

        let mut env1 = MessageEnvelope::new(MessageEvent {
            sender: sender_a,
            message: Message::InputChanged(crate::message::InputChanged {
                value: "a".into(),
                validation: crate::validation::ValidationResult::success(),
            }),
            control: None,
        });
        env1.set_replaceable(true);

        let mut env2 = MessageEnvelope::new(MessageEvent {
            sender: sender_b,
            message: Message::InputChanged(crate::message::InputChanged {
                value: "b".into(),
                validation: crate::validation::ValidationResult::success(),
            }),
            control: None,
        });
        env2.set_replaceable(true);

        queue.push_back(env1);
        queue.push_back(env2);
        coalesce_message_queue(&mut queue);

        assert_eq!(
            queue.len(),
            2,
            "different senders should not coalesce even with same variant"
        );
    }

    #[test]
    fn coalesce_mixed_replaceable_and_non_replaceable() {
        let sender = node_id_from_ffi(1);
        let mut queue: VecDeque<MessageEnvelope> = VecDeque::new();

        // Replaceable InputChanged #1
        let mut env1 = MessageEnvelope::new(MessageEvent {
            sender,
            message: Message::InputChanged(crate::message::InputChanged {
                value: "a".into(),
                validation: crate::validation::ValidationResult::success(),
            }),
            control: None,
        });
        env1.set_replaceable(true);

        // Non-replaceable ButtonPressed
        let env2 = MessageEnvelope::new(MessageEvent {
            sender,
            message: Message::ButtonPressed(crate::message::ButtonPressed {
                description: "click".into(),
                button_id: None,
            }),
            control: None,
        });

        // Replaceable InputChanged #2
        let mut env3 = MessageEnvelope::new(MessageEvent {
            sender,
            message: Message::InputChanged(crate::message::InputChanged {
                value: "ab".into(),
                validation: crate::validation::ValidationResult::success(),
            }),
            control: None,
        });
        env3.set_replaceable(true);

        queue.push_back(env1);
        queue.push_back(env2);
        queue.push_back(env3);
        coalesce_message_queue(&mut queue);

        // Two InputChanged coalesce to one, ButtonPressed survives.
        assert_eq!(queue.len(), 2, "InputChanged pair → 1, ButtonPressed → 1");
        // First remaining should be ButtonPressed (index 0 InputChanged was removed).
        assert!(matches!(queue[0].message(), Message::ButtonPressed(..)));
        // Second should be the latest InputChanged.
        match queue[1].message() {
            Message::InputChanged(crate::message::InputChanged { value, .. }) => {
                assert_eq!(value, "ab");
            }
            other => panic!("unexpected: {:?}", other),
        }
    }

    #[test]
    fn coalesce_empty_queue_is_noop() {
        let mut queue: VecDeque<MessageEnvelope> = VecDeque::new();
        coalesce_message_queue(&mut queue);
        assert!(queue.is_empty());
    }

    #[test]
    fn coalesce_single_element_is_noop() {
        let mut queue: VecDeque<MessageEnvelope> = VecDeque::new();
        let mut env = MessageEnvelope::new(MessageEvent {
            sender: node_id_from_ffi(1),
            message: Message::InputChanged(crate::message::InputChanged {
                value: "x".into(),
                validation: crate::validation::ValidationResult::success(),
            }),
            control: None,
        });
        env.set_replaceable(true);
        queue.push_back(env);
        coalesce_message_queue(&mut queue);
        assert_eq!(queue.len(), 1);
    }

    #[test]
    fn dispatch_coalesces_messages_via_message_can_replace() {
        let sender = node_id_from_ffi(1);
        let _count = Arc::new(AtomicUsize::new(0));

        let mut tree = WidgetTree::new();
        let _root_id = tree.set_root(Box::new(Label::new("x")));

        // Three InputChanged from the same sender — should coalesce to one
        // via Message::can_replace.
        let messages = vec![
            MessageEvent {
                sender,
                message: Message::InputChanged(crate::message::InputChanged {
                    value: "a".into(),
                    validation: crate::validation::ValidationResult::success(),
                }),
                control: None,
            },
            MessageEvent {
                sender,
                message: Message::InputChanged(crate::message::InputChanged {
                    value: "ab".into(),
                    validation: crate::validation::ValidationResult::success(),
                }),
                control: None,
            },
            MessageEvent {
                sender,
                message: Message::InputChanged(crate::message::InputChanged {
                    value: "abc".into(),
                    validation: crate::validation::ValidationResult::success(),
                }),
                control: None,
            },
        ];

        // No panic and dispatch succeeds.
        let _outcome = dispatch_message_queue_tree(&mut tree, messages);
    }

    #[test]
    fn message_can_replace_covers_known_variants() {
        // Spot-check that known rapid-fire message types are replaceable.
        assert!(
            Message::InputChanged(crate::message::InputChanged {
                value: "x".into(),
                validation: crate::validation::ValidationResult::success(),
            })
            .can_replace(&Message::InputChanged(crate::message::InputChanged {
                value: "y".into(),
                validation: crate::validation::ValidationResult::success(),
            }))
        );
        assert!(
            Message::TextAreaChanged(crate::message::TextAreaChanged { value: "x".into() })
                .can_replace(&Message::TextAreaChanged(crate::message::TextAreaChanged {
                    value: "y".into(),
                }))
        );
        assert!(
            Message::DataTableCursorMoved(crate::message::DataTableCursorMoved {
                row: 0,
                column: 0,
            })
            .can_replace(&Message::DataTableCursorMoved(
                crate::message::DataTableCursorMoved { row: 1, column: 1 }
            ))
        );
        assert!(
            Message::OptionHighlighted(crate::message::OptionHighlighted { index: 0 }).can_replace(
                &Message::OptionHighlighted(crate::message::OptionHighlighted { index: 1 })
            )
        );
        // Non-replaceable variants.
        assert!(
            !Message::ButtonPressed(crate::message::ButtonPressed {
                description: "x".into(),
                button_id: None,
            })
            .can_replace(&Message::ButtonPressed(crate::message::ButtonPressed {
                description: "y".into(),
                button_id: None,
            }))
        );
        assert!(
            !Message::InputSubmitted(crate::message::InputSubmitted { value: "x".into() })
                .can_replace(&Message::InputSubmitted(crate::message::InputSubmitted {
                    value: "y".into(),
                }))
        );
        // Different variants never replace each other by default.
        assert!(
            !Message::TextAreaChanged(crate::message::TextAreaChanged { value: "x".into() })
                .can_replace(&Message::InputChanged(crate::message::InputChanged {
                    value: "x".into(),
                    validation: crate::validation::ValidationResult::success(),
                }))
        );
    }

    // =====================================================================
    // P4-17: Envelope control field tests (routing integration)
    // =====================================================================

    #[test]
    fn envelope_control_defaults_to_sender_during_dispatch() {
        // When dispatch_message_queue_tree wraps a MessageEvent the resulting
        // envelope's control() should equal the event's sender.
        let sender = node_id_from_ffi(1);
        let mut tree = WidgetTree::new();
        let _root_id = tree.set_root(Box::new(Label::new("x")));

        let messages = vec![MessageEvent {
            sender,
            message: Message::ButtonPressed(crate::message::ButtonPressed {
                description: "ctrl".into(),
                button_id: None,
            }),
            control: None,
        }];

        // Build the envelope the same way dispatch does and verify control.
        let env = MessageEnvelope::new(messages[0].clone());
        assert_eq!(env.control(), Some(sender));

        // Full dispatch should not panic / break.
        let _outcome = dispatch_message_queue_tree(&mut tree, messages);
    }

    #[test]
    fn envelope_control_preserved_during_bubble() {
        // Tree: root → mid → leaf (sender).  All three nodes see the message
        // via bubble.  The envelope's control stays as the leaf (sender).
        let root_count = Arc::new(AtomicUsize::new(0));
        let mid_count = Arc::new(AtomicUsize::new(0));
        let leaf_count = Arc::new(AtomicUsize::new(0));

        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(MessageCounter::new(root_count.clone())));
        let mid_id = tree.mount(root_id, Box::new(MessageCounter::new(mid_count.clone())));
        let leaf_id = tree.mount(mid_id, Box::new(MessageCounter::new(leaf_count.clone())));

        let evt = MessageEvent {
            sender: leaf_id,
            message: Message::ButtonPressed(crate::message::ButtonPressed {
                description: "bubble".into(),
                button_id: None,
            }),
            control: None,
        };
        let mut env = MessageEnvelope::new(evt.clone());
        // Control should be the leaf (sender) before and after dispatch.
        assert_eq!(env.control(), Some(leaf_id));

        let mut ctx = EventCtx::default();
        dispatch_message_bubble(&mut tree, &mut env, &mut ctx);

        // Control must NOT have changed during bubble propagation.
        assert_eq!(
            env.control(),
            Some(leaf_id),
            "control must stay at sender during bubble"
        );
    }

    #[test]
    fn coalesced_messages_preserve_control_from_latest() {
        // When two replaceable messages from the same sender coalesce, the
        // surviving (latest) envelope keeps its control.
        let sender = node_id_from_ffi(5);
        let mut queue: VecDeque<MessageEnvelope> = VecDeque::new();

        let mut env1 = MessageEnvelope::new(MessageEvent {
            sender,
            message: Message::InputChanged(crate::message::InputChanged {
                value: "a".into(),
                validation: crate::validation::ValidationResult::success(),
            }),
            control: None,
        });
        env1.set_replaceable(true);

        let mut env2 = MessageEnvelope::new(MessageEvent {
            sender,
            message: Message::InputChanged(crate::message::InputChanged {
                value: "ab".into(),
                validation: crate::validation::ValidationResult::success(),
            }),
            control: None,
        });
        env2.set_replaceable(true);

        queue.push_back(env1);
        queue.push_back(env2);
        coalesce_message_queue(&mut queue);

        assert_eq!(queue.len(), 1);
        assert_eq!(
            queue[0].control(),
            Some(sender),
            "coalesced envelope should keep the latest control value"
        );
    }

    #[test]
    fn set_control_override_survives_coalescing() {
        // If we override the control on the later envelope, coalescing should
        // preserve that override (since the later one is kept).
        let sender = node_id_from_ffi(5);
        let override_node = node_id_from_ffi(77);
        let mut queue: VecDeque<MessageEnvelope> = VecDeque::new();

        let mut env1 = MessageEnvelope::new(MessageEvent {
            sender,
            message: Message::InputChanged(crate::message::InputChanged {
                value: "a".into(),
                validation: crate::validation::ValidationResult::success(),
            }),
            control: None,
        });
        env1.set_replaceable(true);

        let mut env2 = MessageEnvelope::new(MessageEvent {
            sender,
            message: Message::InputChanged(crate::message::InputChanged {
                value: "ab".into(),
                validation: crate::validation::ValidationResult::success(),
            }),
            control: None,
        });
        env2.set_replaceable(true);
        env2.set_control(override_node);

        queue.push_back(env1);
        queue.push_back(env2);
        coalesce_message_queue(&mut queue);

        assert_eq!(queue.len(), 1);
        assert_eq!(
            queue[0].control(),
            Some(override_node),
            "overridden control on the latest envelope should survive coalescing"
        );
    }

    // =====================================================================
    // Widget observability: widgets receive correct control via MessageEvent
    // =====================================================================

    use crate::node_id::NodeId;
    use std::sync::Mutex;

    /// Widget that captures the `control` value from the MessageEvent it receives.
    struct ControlCapture {
        captured: Arc<Mutex<Vec<Option<NodeId>>>>,
    }

    impl ControlCapture {
        fn new(captured: Arc<Mutex<Vec<Option<NodeId>>>>) -> Self {
            Self { captured }
        }
    }

    impl Widget for ControlCapture {
        fn render(&self, _console: &Console, _options: &ConsoleOptions) -> Segments {
            Segments::new()
        }

        fn on_message(&mut self, message: &MessageEvent, ctx: &mut EventCtx) {
            if matches!(message.message, Message::ButtonPressed(..)) {
                self.captured.lock().unwrap().push(message.control);
                ctx.set_handled();
            }
        }
    }

    #[test]
    fn widget_on_message_sees_promoted_control_from_envelope() {
        // When control is None on the event, the envelope promotes it to
        // Some(sender). dispatch_message_bubble must sync this back so the
        // widget's on_message handler sees Some(sender), not None.
        let captured = Arc::new(Mutex::new(Vec::new()));

        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(ControlCapture::new(captured.clone())));

        let messages = vec![MessageEvent {
            sender: root_id,
            message: Message::ButtonPressed(crate::message::ButtonPressed {
                description: "test".into(),
                button_id: None,
            }),
            control: None, // None — envelope should promote to Some(root_id)
        }];

        dispatch_message_queue_tree(&mut tree, messages);

        let values = captured.lock().unwrap();
        assert_eq!(values.len(), 1);
        assert_eq!(
            values[0],
            Some(root_id),
            "widget should see control = Some(sender) after envelope promotion"
        );
    }

    #[test]
    fn widget_on_message_sees_explicit_control() {
        // When control is explicitly set on the event, the widget should see
        // that value, not the sender.
        let captured = Arc::new(Mutex::new(Vec::new()));
        let explicit_control = node_id_from_ffi(999);

        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(ControlCapture::new(captured.clone())));

        let messages = vec![MessageEvent {
            sender: root_id,
            message: Message::ButtonPressed(crate::message::ButtonPressed {
                description: "explicit".into(),
                button_id: None,
            }),
            control: Some(explicit_control),
        }];

        dispatch_message_queue_tree(&mut tree, messages);

        let values = captured.lock().unwrap();
        assert_eq!(values.len(), 1);
        assert_eq!(
            values[0],
            Some(explicit_control),
            "widget should see the explicit control value from the event"
        );
    }
}

#[cfg(test)]
mod binding_tests {
    use super::*;
    use crate::keys::KeyEventData;
    use crate::widget_tree::WidgetTree;
    use crate::widgets::BindingDecl;
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
    use rich_rs::{Console, ConsoleOptions, Segments};

    fn key_event(code: KeyCode, mods: KeyModifiers) -> KeyEvent {
        KeyEvent::new(code, mods)
    }

    // -- BindingDecl construction tests --

    #[test]
    fn binding_decl_new_defaults() {
        let b = BindingDecl::new("enter", "submit", "Submit form");
        assert_eq!(b.key, "enter");
        assert_eq!(b.action, "submit");
        assert_eq!(b.description, "Submit form");
        assert!(b.show);
        assert!(!b.priority);
    }

    #[test]
    fn binding_decl_hidden_builder() {
        let b = BindingDecl::new("q", "quit", "Quit").hidden();
        assert!(!b.show);
        assert!(!b.priority);
    }

    #[test]
    fn binding_decl_priority_builder() {
        let b = BindingDecl::new("escape", "close", "Close").priority();
        assert!(b.show);
        assert!(b.priority);
    }

    #[test]
    fn binding_decl_chained_builders() {
        let b = BindingDecl::new("x", "delete", "Delete")
            .hidden()
            .priority();
        assert!(!b.show);
        assert!(b.priority);
    }

    // -- key_matches_binding tests --

    #[test]
    fn key_matches_single_binding() {
        let key = KeyEventData::from_crossterm(key_event(KeyCode::Enter, KeyModifiers::empty()));
        assert!(key_matches_binding(&key, "enter"));
        assert!(!key_matches_binding(&key, "space"));
    }

    #[test]
    fn key_matches_comma_separated_alternatives() {
        let key =
            KeyEventData::from_crossterm(key_event(KeyCode::Char('j'), KeyModifiers::empty()));
        assert!(key_matches_binding(&key, "j,down"));
        assert!(key_matches_binding(&key, "up,j"));
    }

    #[test]
    fn key_matches_via_alias() {
        // Tab and ctrl+i are aliases
        let key = KeyEventData::from_crossterm(key_event(KeyCode::Tab, KeyModifiers::empty()));
        assert!(key_matches_binding(&key, "ctrl+i"));
        assert!(key_matches_binding(&key, "tab"));
    }

    #[test]
    fn key_no_match_returns_false() {
        let key =
            KeyEventData::from_crossterm(key_event(KeyCode::Char('z'), KeyModifiers::empty()));
        assert!(!key_matches_binding(&key, "a,b,c"));
    }

    // -- match_binding_tree tests --

    /// Minimal widget that declares bindings and reports focus state.
    struct BindingWidget {
        focused: bool,
        decls: Vec<BindingDecl>,
    }

    impl BindingWidget {
        fn new(focused: bool, decls: Vec<BindingDecl>) -> Self {
            Self { focused, decls }
        }
    }

    impl Widget for BindingWidget {
        fn render(&self, _console: &Console, _options: &ConsoleOptions) -> Segments {
            Segments::new()
        }

        fn bindings(&self) -> Vec<BindingDecl> {
            self.decls.clone()
        }

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

        fn has_focus(&self) -> bool {
            self.focused
        }

        fn set_focus(&mut self, focused: bool) {
            self.focused = focused;
        }
    }

    /// Inert root widget.
    struct Root;

    impl Widget for Root {
        fn render(&self, _: &Console, _: &ConsoleOptions) -> Segments {
            Segments::new()
        }
    }

    #[test]
    fn match_binding_focused_widget() {
        // Tree: root → child (focused, binding "enter" → "submit")
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(Root));
        let _child_id = tree.mount(
            root_id,
            Box::new(BindingWidget::new(
                true,
                vec![BindingDecl::new("enter", "submit", "Submit")],
            )),
        );

        let key = KeyEventData::from_crossterm(key_event(KeyCode::Enter, KeyModifiers::empty()));
        let result = match_binding_tree(&tree, &key);
        assert!(result.is_some());
        let (node_id, action) = result.unwrap();
        assert_eq!(action, "submit");
        assert_eq!(node_id, _child_id);
    }

    #[test]
    fn match_binding_ancestor_fallback() {
        // Tree: root (binding "q" → "quit") → child (focused, no bindings)
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(BindingWidget::new(
            false,
            vec![BindingDecl::new("q", "app.quit", "Quit")],
        )));
        let _child_id = tree.mount(root_id, Box::new(BindingWidget::new(false, vec![])));
        // Focus the child
        if let Some(node) = tree.get_mut(_child_id) {
            node.widget.set_focus(true);
        }

        let key =
            KeyEventData::from_crossterm(key_event(KeyCode::Char('q'), KeyModifiers::empty()));
        let result = match_binding_tree(&tree, &key);
        assert!(result.is_some());
        let (node_id, action) = result.unwrap();
        assert_eq!(action, "app.quit");
        assert_eq!(node_id, root_id);
    }

    #[test]
    fn match_binding_priority_wins_over_normal() {
        // Tree: root (priority binding "escape" → "close_app")
        //       → child (focused, normal binding "escape" → "cancel")
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(BindingWidget::new(
            false,
            vec![BindingDecl::new("escape", "close_app", "Close app").priority()],
        )));
        let _child_id = tree.mount(
            root_id,
            Box::new(BindingWidget::new(
                true,
                vec![BindingDecl::new("escape", "cancel", "Cancel")],
            )),
        );

        let key = KeyEventData::from_crossterm(key_event(KeyCode::Esc, KeyModifiers::empty()));
        let result = match_binding_tree(&tree, &key);
        assert!(result.is_some());
        let (node_id, action) = result.unwrap();
        // Priority binding on child should be checked first (focused → root),
        // but child has normal binding, root has priority. Priority phase checks
        // child first (no priority there), then root (priority match!).
        assert_eq!(action, "close_app");
        assert_eq!(node_id, root_id);

        // Now verify that without priority, child would win.
        // Remove priority from root, make it normal.
        let mut tree2 = WidgetTree::new();
        let root_id2 = tree2.set_root(Box::new(BindingWidget::new(
            false,
            vec![BindingDecl::new("escape", "close_app", "Close app")],
        )));
        let child_id2 = tree2.mount(
            root_id2,
            Box::new(BindingWidget::new(
                true,
                vec![BindingDecl::new("escape", "cancel", "Cancel")],
            )),
        );

        let result2 = match_binding_tree(&tree2, &key);
        assert!(result2.is_some());
        let (node_id2, action2) = result2.unwrap();
        // Normal bindings: focused child wins (checked first in focused → root order).
        assert_eq!(action2, "cancel");
        assert_eq!(node_id2, child_id2);
    }

    #[test]
    fn match_binding_no_match_returns_none() {
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(BindingWidget::new(
            false,
            vec![BindingDecl::new("enter", "submit", "Submit")],
        )));
        let _child_id = tree.mount(root_id, Box::new(BindingWidget::new(true, vec![])));

        let key =
            KeyEventData::from_crossterm(key_event(KeyCode::Char('z'), KeyModifiers::empty()));
        let result = match_binding_tree(&tree, &key);
        assert!(result.is_none());
    }

    #[test]
    fn match_binding_no_focus_uses_root_scope_fallback() {
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(BindingWidget::new(
            false,
            vec![BindingDecl::new("enter", "submit", "Submit")],
        )));

        let key = KeyEventData::from_crossterm(key_event(KeyCode::Enter, KeyModifiers::empty()));
        let result = match_binding_tree(&tree, &key);
        assert!(result.is_some());
        let (node_id, action) = result.unwrap();
        assert_eq!(node_id, root_id);
        assert_eq!(action, "submit");
    }

    // -- binding hints integration --

    #[test]
    fn active_hints_include_declared_bindings() {
        let mut tree = WidgetTree::new();
        let root_id = tree.set_root(Box::new(BindingWidget::new(
            false,
            vec![BindingDecl::new("q", "quit", "Quit application")],
        )));
        let _child_id = tree.mount(
            root_id,
            Box::new(BindingWidget::new(
                true,
                vec![
                    BindingDecl::new("enter", "submit", "Submit form"),
                    BindingDecl::new("escape", "cancel", "Cancel").hidden(),
                ],
            )),
        );

        let (hints, _sources) = active_binding_hints_tree(&tree);
        // Root has 1 binding, child has 2 bindings = 3 total hints.
        assert_eq!(hints.len(), 3);

        // Check that the hidden binding is marked hidden in the hint.
        let escape_hint = hints.iter().find(|h| h.key == "escape").unwrap();
        assert!(!escape_hint.show); // hidden binding → show=false

        let enter_hint = hints.iter().find(|h| h.key == "enter").unwrap();
        assert!(enter_hint.show);

        let q_hint = hints.iter().find(|h| h.key == "q").unwrap();
        assert!(q_hint.show);
        assert_eq!(q_hint.description, "Quit application");
    }
}