ftui-render 0.11.0

Render kernel: cells, buffers, diffs, and ANSI presentation.
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
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
#![forbid(unsafe_code)]

//! Frame = Buffer + metadata for a render pass.
//!
//! The `Frame` is the render target that `Model::view()` methods write to.
//! It bundles the cell grid ([`Buffer`]) with metadata for cursor and
//! mouse hit testing.
//!
//! # Design Rationale
//!
//! Frame does NOT own pools (GraphemePool, LinkRegistry) - those are passed
//! separately or accessed via RenderContext to allow sharing across frames.
//!
//! # Usage
//!
//! ```
//! use ftui_render::frame::Frame;
//! use ftui_render::cell::Cell;
//! use ftui_render::grapheme_pool::GraphemePool;
//!
//! let mut pool = GraphemePool::new();
//! let mut frame = Frame::new(80, 24, &mut pool);
//!
//! // Draw content
//! frame.buffer.set_raw(0, 0, Cell::from_char('H'));
//! frame.buffer.set_raw(1, 0, Cell::from_char('i'));
//!
//! // Set cursor
//! frame.set_cursor(Some((2, 0)));
//! ```

use crate::arena::FrameArena;
use crate::budget::DegradationLevel;
use crate::buffer::Buffer;
use crate::cell::{Cell, CellContent, GraphemeId};
use crate::drawing::{BorderChars, Draw};
use crate::grapheme_pool::GraphemePool;
use crate::{display_width, grapheme_width};
use ftui_a11y::node::A11yNodeInfo;
use ftui_a11y::tree::A11yTreeBuilder;
use ftui_core::geometry::Rect;
use unicode_segmentation::UnicodeSegmentation;

/// Identifier for a clickable region in the hit grid.
///
/// Widgets register hit regions with unique IDs to enable mouse interaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct HitId(pub u32);

impl HitId {
    /// Create a new hit ID from a raw value.
    #[inline]
    pub const fn new(id: u32) -> Self {
        Self(id)
    }

    /// Get the raw ID value.
    #[inline]
    pub const fn id(self) -> u32 {
        self.0
    }
}

/// Opaque user data for hit callbacks.
pub type HitData = u64;

/// Optional ownership tag attached to a hit region.
///
/// Higher-level systems can use this to disambiguate layered hit regions
/// without overloading `HitId` or `HitData`.
pub type HitOwner = u64;

/// Regions within a widget for mouse interaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum HitRegion {
    /// No interactive region.
    #[default]
    None,
    /// Main content area.
    Content,
    /// Widget border area.
    Border,
    /// Scrollbar track or thumb.
    Scrollbar,
    /// Resize handle or drag target.
    Handle,
    /// Clickable button.
    Button,
    /// Hyperlink.
    Link,
    /// Custom region tag.
    Custom(u8),
}

/// Full hit-test metadata, including optional ownership provenance.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HitTestResult {
    pub id: HitId,
    pub region: HitRegion,
    pub data: HitData,
    pub owner: Option<HitOwner>,
}

impl HitTestResult {
    #[inline]
    pub const fn new(id: HitId, region: HitRegion, data: HitData, owner: Option<HitOwner>) -> Self {
        Self {
            id,
            region,
            data,
            owner,
        }
    }

    #[inline]
    pub const fn into_tuple(self) -> (HitId, HitRegion, HitData) {
        (self.id, self.region, self.data)
    }
}

/// A single hit cell in the grid.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct HitCell {
    /// Widget that registered this cell, if any.
    pub widget_id: Option<HitId>,
    /// Region tag for the hit area.
    pub region: HitRegion,
    /// Extra data attached to this hit cell.
    pub data: HitData,
    /// Optional owner tag for higher-level hit routing.
    pub owner: Option<HitOwner>,
}

impl HitCell {
    /// Create a populated hit cell.
    #[inline]
    pub const fn new(widget_id: HitId, region: HitRegion, data: HitData) -> Self {
        Self {
            widget_id: Some(widget_id),
            region,
            data,
            owner: None,
        }
    }

    /// Create a populated hit cell with explicit owner provenance.
    #[inline]
    pub const fn new_with_owner(
        widget_id: HitId,
        region: HitRegion,
        data: HitData,
        owner: Option<HitOwner>,
    ) -> Self {
        Self {
            widget_id: Some(widget_id),
            region,
            data,
            owner,
        }
    }

    /// Check if the cell is empty.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.widget_id.is_none()
    }
}

/// Hit testing grid for mouse interaction.
///
/// Maps screen positions to widget IDs, enabling widgets to receive
/// mouse events for their regions.
#[derive(Debug, Clone)]
pub struct HitGrid {
    width: u16,
    height: u16,
    cells: Vec<HitCell>,
}

impl HitGrid {
    /// Create a new hit grid with the given dimensions.
    pub fn new(width: u16, height: u16) -> Self {
        let size = width as usize * height as usize;
        Self {
            width,
            height,
            cells: vec![HitCell::default(); size],
        }
    }

    /// Grid width.
    #[inline]
    pub const fn width(&self) -> u16 {
        self.width
    }

    /// Grid height.
    #[inline]
    pub const fn height(&self) -> u16 {
        self.height
    }

    /// Convert (x, y) to linear index.
    #[inline]
    fn index(&self, x: u16, y: u16) -> Option<usize> {
        if x < self.width && y < self.height {
            Some(y as usize * self.width as usize + x as usize)
        } else {
            None
        }
    }

    /// Get the hit cell at (x, y).
    #[inline]
    #[must_use]
    pub fn get(&self, x: u16, y: u16) -> Option<&HitCell> {
        self.index(x, y).map(|i| &self.cells[i])
    }

    /// Get mutable reference to hit cell at (x, y).
    #[inline]
    #[must_use]
    pub fn get_mut(&mut self, x: u16, y: u16) -> Option<&mut HitCell> {
        self.index(x, y).map(|i| &mut self.cells[i])
    }

    /// Register a clickable region with the given hit metadata.
    ///
    /// All cells within the rectangle will map to this hit cell.
    pub fn register(&mut self, rect: Rect, widget_id: HitId, region: HitRegion, data: HitData) {
        self.register_with_owner(rect, widget_id, region, data, None);
    }

    /// Register a clickable region with the given hit metadata and owner.
    pub fn register_with_owner(
        &mut self,
        rect: Rect,
        widget_id: HitId,
        region: HitRegion,
        data: HitData,
        owner: Option<HitOwner>,
    ) {
        // Use usize to avoid overflow for large coordinates
        let x_end = (rect.x as usize + rect.width as usize).min(self.width as usize);
        let y_end = (rect.y as usize + rect.height as usize).min(self.height as usize);

        // Check if there's anything to do
        if rect.x as usize >= x_end || rect.y as usize >= y_end {
            return;
        }

        let hit_cell = HitCell::new_with_owner(widget_id, region, data, owner);

        for y in rect.y as usize..y_end {
            let row_start = y * self.width as usize;
            let start = row_start + rect.x as usize;
            let end = row_start + x_end;

            // Optimize: use slice fill for contiguous memory access
            self.cells[start..end].fill(hit_cell);
        }
    }

    /// Hit test at the given position.
    ///
    /// Returns the hit tuple if a region is registered at (x, y).
    #[must_use]
    pub fn hit_test(&self, x: u16, y: u16) -> Option<(HitId, HitRegion, HitData)> {
        self.hit_test_detailed(x, y).map(HitTestResult::into_tuple)
    }

    /// Hit test at the given position, preserving owner provenance.
    #[must_use]
    pub fn hit_test_detailed(&self, x: u16, y: u16) -> Option<HitTestResult> {
        self.get(x, y).and_then(|cell| {
            cell.widget_id
                .map(|id| HitTestResult::new(id, cell.region, cell.data, cell.owner))
        })
    }

    /// Return all hits within the given rectangle.
    pub fn hits_in(&self, rect: Rect) -> Vec<(HitId, HitRegion, HitData)> {
        let x_end = (rect.x as usize + rect.width as usize).min(self.width as usize) as u16;
        let y_end = (rect.y as usize + rect.height as usize).min(self.height as usize) as u16;
        let mut hits = Vec::new();

        for y in rect.y..y_end {
            for x in rect.x..x_end {
                if let Some((id, region, data)) = self.hit_test(x, y) {
                    hits.push((id, region, data));
                }
            }
        }

        hits
    }

    /// Clear all hit regions.
    pub fn clear(&mut self) {
        self.cells.fill(HitCell::default());
    }
}

use crate::link_registry::LinkRegistry;

/// Source of the cost estimate for widget scheduling.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum CostEstimateSource {
    /// Measured from recent render timings.
    Measured,
    /// Derived from area-based fallback (cells * cost_per_cell).
    AreaFallback,
    /// Fixed default when no signals exist.
    #[default]
    FixedDefault,
}

/// Per-widget scheduling signals captured during rendering.
///
/// These signals are used by runtime policies (budgeted refresh, greedy
/// selection) to prioritize which widgets to render when budget is tight.
#[derive(Debug, Clone)]
pub struct WidgetSignal {
    /// Stable widget identifier.
    pub widget_id: u64,
    /// Whether this widget is essential.
    pub essential: bool,
    /// Base priority in [0, 1].
    pub priority: f32,
    /// Milliseconds since last render.
    pub staleness_ms: u64,
    /// Focus boost in [0, 1].
    pub focus_boost: f32,
    /// Interaction boost in [0, 1].
    pub interaction_boost: f32,
    /// Widget area in cells (width * height).
    pub area_cells: u32,
    /// Estimated render cost in microseconds.
    pub cost_estimate_us: f32,
    /// Recent measured cost (EMA), if available.
    pub recent_cost_us: f32,
    /// Cost estimate provenance.
    pub estimate_source: CostEstimateSource,
}

impl Default for WidgetSignal {
    fn default() -> Self {
        Self {
            widget_id: 0,
            essential: false,
            priority: 0.5,
            staleness_ms: 0,
            focus_boost: 0.0,
            interaction_boost: 0.0,
            area_cells: 1,
            cost_estimate_us: 5.0,
            recent_cost_us: 5.0,
            estimate_source: CostEstimateSource::FixedDefault,
        }
    }
}

impl WidgetSignal {
    /// Create a widget signal with neutral defaults.
    #[must_use]
    pub fn new(widget_id: u64) -> Self {
        Self {
            widget_id,
            ..Self::default()
        }
    }
}

/// Value-of-Information remeasure request emitted by a virtualized widget during rendering.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RemeasureRequest {
    /// Stable widget identifier (or 0 when unset).
    pub widget_id: u64,
    /// Item index selected for remeasurement.
    pub index: usize,
    /// Value of Information (expected variance reduction) at decision time.
    pub voi: f64,
    /// Configured sample cost threshold.
    pub cost: f64,
    /// Posterior alpha parameter at decision time.
    pub alpha: f64,
    /// Posterior beta parameter at decision time.
    pub beta: f64,
}

/// Widget render budget policy for a single frame.
#[derive(Debug, Clone)]
pub struct WidgetBudget {
    allow_list: Option<Vec<u64>>,
}

impl Default for WidgetBudget {
    fn default() -> Self {
        Self::allow_all()
    }
}

impl WidgetBudget {
    /// Allow all widgets to render.
    #[must_use]
    pub fn allow_all() -> Self {
        Self { allow_list: None }
    }

    /// Allow only a specific set of widget IDs.
    #[must_use]
    pub fn allow_only(mut ids: Vec<u64>) -> Self {
        ids.sort_unstable();
        ids.dedup();
        Self {
            allow_list: Some(ids),
        }
    }

    /// Check whether a widget should be rendered.
    #[inline]
    pub fn allows(&self, widget_id: u64, essential: bool) -> bool {
        if essential {
            return true;
        }
        match &self.allow_list {
            None => true,
            Some(ids) => ids.binary_search(&widget_id).is_ok(),
        }
    }
}

/// Text flow direction for a frame or widget.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum TextDirection {
    /// Left-to-right text flow.
    #[default]
    Ltr,
    /// Right-to-left text flow.
    Rtl,
}

impl TextDirection {
    /// Whether this direction is left-to-right.
    #[inline]
    #[must_use]
    pub const fn is_ltr(self) -> bool {
        matches!(self, Self::Ltr)
    }

    /// Whether this direction is right-to-left.
    #[inline]
    #[must_use]
    pub const fn is_rtl(self) -> bool {
        matches!(self, Self::Rtl)
    }
}

/// Frame = Buffer + metadata for a render pass.
///
/// The Frame is passed to `Model::view()` and contains everything needed
/// to render a single frame. The Buffer holds cells; metadata controls
/// cursor and enables mouse hit testing.
///
/// # Lifetime
///
/// The frame borrows the `GraphemePool` from the runtime, so it cannot outlive
/// the render pass. This is correct because frames are ephemeral render targets.
#[derive(Debug)]
pub struct Frame<'a> {
    /// The cell grid for this render pass.
    pub buffer: Buffer,

    /// Text flow direction for this frame (LTR or RTL).
    pub text_direction: TextDirection,

    /// Reference to the grapheme pool for interning strings.
    pub pool: &'a mut GraphemePool,

    /// Optional reference to link registry for hyperlinks.
    pub links: Option<&'a mut LinkRegistry>,

    /// Optional hit grid for mouse hit testing.
    ///
    /// When `Some`, widgets can register clickable regions.
    pub hit_grid: Option<HitGrid>,

    /// Optional ownership stack applied to registered hit regions.
    hit_owner_stack: Vec<HitOwner>,

    /// Widget render budget policy for this frame.
    pub widget_budget: WidgetBudget,

    /// Collected per-widget scheduling signals for this frame.
    pub widget_signals: Vec<WidgetSignal>,

    /// Collected VOI remeasure requests for this frame.
    remeasure_requests: Vec<RemeasureRequest>,

    /// Cursor position (if app wants to show cursor).
    ///
    /// Coordinates are relative to buffer (0-indexed).
    pub cursor_position: Option<(u16, u16)>,

    /// Whether cursor should be visible.
    pub cursor_visible: bool,

    /// Current degradation level from the render budget.
    ///
    /// Widgets can read this to skip expensive operations when the
    /// budget is constrained (e.g., use ASCII borders instead of
    /// Unicode, skip decorative rendering, etc.).
    pub degradation: DegradationLevel,

    /// Optional per-frame bump arena for temporary allocations.
    ///
    /// When set, widgets can use this arena for scratch allocations that
    /// only live for the current frame (e.g., formatted strings, temporary
    /// slices). The arena is reset at frame boundaries, eliminating
    /// allocator churn on the hot render path.
    pub arena: Option<&'a FrameArena>,

    /// Accessibility tree builder for this frame, when the runtime collects
    /// one (see [`Frame::push_a11y`]). `None` makes every a11y call a no-op.
    pub a11y: Option<&'a mut A11yTreeBuilder>,

    /// Container ids opened by [`Frame::with_a11y_scope`].
    a11y_scope_stack: Vec<u64>,

    /// Node ids in push (document) order.
    a11y_order: Vec<u64>,

    /// `(parent, child)` links to apply in [`Frame::finish_a11y`].
    a11y_children: Vec<(u64, u64)>,

    /// Node ids that were taken when pushed, mapped to the id the node got
    /// instead (see [`Frame::push_a11y`]).
    a11y_rekeyed: std::collections::HashMap<u64, u64>,

    /// Explicit focus owner set via [`Frame::set_a11y_focused`] (e.g., from
    /// `FocusManager::sync_to_frame`). `None` derives focus from pushed
    /// `A11yState::focused` flags; `Some(target)` enforces `target` (or its
    /// focused active descendant) as the unique focused node in the built tree.
    a11y_explicit_focus: Option<Option<u64>>,
}

/// The next id to try for an accessibility node whose id is taken: the
/// splitmix64 mix of `id`, a bijection, so repeated calls walk a sequence that
/// does not return to `id` for any practical length.
fn rekey_a11y_id(id: u64) -> u64 {
    let mut z = id.wrapping_add(0x9E37_79B9_7F4A_7C15);
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^ (z >> 31)
}

impl<'a> Frame<'a> {
    /// Create a new frame with given dimensions and grapheme pool.
    ///
    /// The frame starts with no hit grid and visible cursor at no position.
    pub fn new(width: u16, height: u16, pool: &'a mut GraphemePool) -> Self {
        Self {
            buffer: Buffer::new(width, height),
            text_direction: TextDirection::default(),
            pool,
            links: None,
            hit_grid: None,
            hit_owner_stack: Vec::new(),
            widget_budget: WidgetBudget::default(),
            widget_signals: Vec::new(),
            remeasure_requests: Vec::new(),
            cursor_position: None,
            cursor_visible: true,
            degradation: DegradationLevel::Full,
            arena: None,
            a11y: None,
            a11y_scope_stack: Vec::new(),
            a11y_order: Vec::new(),
            a11y_children: Vec::new(),
            a11y_rekeyed: std::collections::HashMap::new(),
            a11y_explicit_focus: None,
        }
    }

    /// Create a frame from an existing buffer.
    ///
    /// This avoids per-frame buffer allocation when callers reuse buffers.
    pub fn from_buffer(buffer: Buffer, pool: &'a mut GraphemePool) -> Self {
        Self {
            buffer,
            text_direction: TextDirection::default(),
            pool,
            links: None,
            hit_grid: None,
            hit_owner_stack: Vec::new(),
            widget_budget: WidgetBudget::default(),
            widget_signals: Vec::new(),
            remeasure_requests: Vec::new(),
            cursor_position: None,
            cursor_visible: true,
            degradation: DegradationLevel::Full,
            arena: None,
            a11y: None,
            a11y_scope_stack: Vec::new(),
            a11y_order: Vec::new(),
            a11y_children: Vec::new(),
            a11y_rekeyed: std::collections::HashMap::new(),
            a11y_explicit_focus: None,
        }
    }

    /// Create a new frame with grapheme pool and link registry.
    ///
    /// This avoids double-borrowing issues when both pool and links
    /// come from the same parent struct.
    pub fn with_links(
        width: u16,
        height: u16,
        pool: &'a mut GraphemePool,
        links: &'a mut LinkRegistry,
    ) -> Self {
        Self {
            buffer: Buffer::new(width, height),
            text_direction: TextDirection::default(),
            pool,
            links: Some(links),
            hit_grid: None,
            hit_owner_stack: Vec::new(),
            widget_budget: WidgetBudget::default(),
            widget_signals: Vec::new(),
            remeasure_requests: Vec::new(),
            cursor_position: None,
            cursor_visible: true,
            degradation: DegradationLevel::Full,
            arena: None,
            a11y: None,
            a11y_scope_stack: Vec::new(),
            a11y_order: Vec::new(),
            a11y_children: Vec::new(),
            a11y_rekeyed: std::collections::HashMap::new(),
            a11y_explicit_focus: None,
        }
    }

    /// Set the text direction for this frame.
    #[inline]
    pub fn set_text_direction(&mut self, text_direction: TextDirection) {
        self.text_direction = text_direction;
    }

    /// Create a frame with hit testing enabled.
    ///
    /// The hit grid allows widgets to register clickable regions.
    pub fn with_hit_grid(width: u16, height: u16, pool: &'a mut GraphemePool) -> Self {
        // Build the buffer first and size the grid from its (>=1-clamped)
        // dimensions, so a degenerate 0 dimension cannot produce a drawable
        // buffer paired with an empty grid that accepts registrations but
        // never reports hits.
        let buffer = Buffer::new(width, height);
        let hit_grid = HitGrid::new(buffer.width(), buffer.height());
        Self {
            buffer,
            pool,
            links: None,
            hit_grid: Some(hit_grid),
            hit_owner_stack: Vec::new(),
            widget_budget: WidgetBudget::default(),
            widget_signals: Vec::new(),
            remeasure_requests: Vec::new(),
            cursor_position: None,
            cursor_visible: true,
            degradation: DegradationLevel::Full,
            arena: None,
            a11y: None,
            a11y_scope_stack: Vec::new(),
            a11y_order: Vec::new(),
            a11y_children: Vec::new(),
            a11y_rekeyed: std::collections::HashMap::new(),
            a11y_explicit_focus: None,
            text_direction: TextDirection::default(),
        }
    }

    /// Set the link registry for this frame.
    pub fn set_links(&mut self, links: &'a mut LinkRegistry) {
        self.links = Some(links);
    }

    /// Set the per-frame bump arena for temporary allocations.
    ///
    /// Widgets can access the arena via [`arena()`](Self::arena) to
    /// perform scratch allocations that only live for the current frame.
    pub fn set_arena(&mut self, arena: &'a FrameArena) {
        self.arena = Some(arena);
    }

    /// Returns the per-frame bump arena, if set.
    ///
    /// Widgets should use this for temporary allocations (formatted strings,
    /// scratch slices) to avoid per-frame allocator churn.
    pub fn arena(&self) -> Option<&'a FrameArena> {
        self.arena
    }

    /// Register a hyperlink URL and return its ID.
    ///
    /// Returns 0 if link registry is not available or full.
    pub fn register_link(&mut self, url: &str) -> u32 {
        if let Some(ref mut links) = self.links {
            links.register(url)
        } else {
            0
        }
    }

    /// Set the widget render budget for this frame.
    pub fn set_widget_budget(&mut self, budget: WidgetBudget) {
        self.widget_budget = budget;
    }

    /// Check whether a widget should be rendered by widget ID, considering both degradation and widget budget.
    #[inline]
    pub fn should_render_widget_by_id(&self, widget_id: u64, essential: bool) -> bool {
        self.should_render_widget(essential) && self.widget_budget.allows(widget_id, essential)
    }

    /// Check whether a budgeted widget should be rendered under the current widget budget and degradation.
    #[inline]
    pub fn should_render_budgeted_widget(&self, widget_id: u64, essential: bool) -> bool {
        self.should_render_widget_by_id(widget_id, essential)
    }

    /// Register a widget scheduling signal for this frame.
    pub fn register_widget_signal(&mut self, signal: WidgetSignal) {
        self.widget_signals.push(signal);
    }

    /// Borrow the collected widget signals.
    #[inline]
    pub fn widget_signals(&self) -> &[WidgetSignal] {
        &self.widget_signals
    }

    /// Take the collected widget signals, leaving an empty list.
    #[inline]
    pub fn take_widget_signals(&mut self) -> Vec<WidgetSignal> {
        std::mem::take(&mut self.widget_signals)
    }

    /// Push a VOI remeasure request emitted during widget rendering.
    pub fn push_remeasure_request(&mut self, req: RemeasureRequest) {
        self.remeasure_requests.push(req);
    }

    /// Borrow the collected VOI remeasure requests.
    #[inline]
    pub fn remeasure_requests(&self) -> &[RemeasureRequest] {
        &self.remeasure_requests
    }

    /// Take the collected VOI remeasure requests, leaving an empty list.
    #[inline]
    pub fn take_remeasure_requests(&mut self) -> Vec<RemeasureRequest> {
        std::mem::take(&mut self.remeasure_requests)
    }

    /// Intern a string in the grapheme pool.
    ///
    /// Returns a `GraphemeId` that can be used to create a `Cell`.
    /// The width is calculated automatically or can be provided if already known.
    ///
    /// # Panics
    ///
    /// Panics if width exceeds `GraphemeId::MAX_WIDTH`.
    pub fn intern(&mut self, text: &str) -> GraphemeId {
        let width = display_width(text).min(GraphemeId::MAX_WIDTH as usize) as u8;
        self.pool.intern(text, width)
    }

    /// Intern a string with explicit width.
    pub fn intern_with_width(&mut self, text: &str, width: u8) -> GraphemeId {
        self.pool.intern(text, width)
    }

    /// Enable hit testing on an existing frame.
    pub fn enable_hit_testing(&mut self) {
        if self.hit_grid.is_none() {
            self.hit_grid = Some(HitGrid::new(self.width(), self.height()));
        }
    }

    /// Frame width in cells.
    #[inline]
    pub fn width(&self) -> u16 {
        self.buffer.width()
    }

    /// Frame height in cells.
    #[inline]
    pub fn height(&self) -> u16 {
        self.buffer.height()
    }

    /// Clear frame for next render.
    ///
    /// Resets both the buffer and hit grid (if present).
    pub fn clear(&mut self) {
        self.buffer.clear();
        if let Some(ref mut grid) = self.hit_grid {
            grid.clear();
        }
        self.cursor_position = None;
        self.widget_signals.clear();
        self.remeasure_requests.clear();
    }

    /// Set cursor position.
    ///
    /// Pass `None` to indicate no cursor should be shown at a specific position.
    #[inline]
    pub fn set_cursor(&mut self, position: Option<(u16, u16)>) {
        self.cursor_position = position;
    }

    /// Set cursor visibility.
    #[inline]
    pub fn set_cursor_visible(&mut self, visible: bool) {
        self.cursor_visible = visible;
    }

    /// Set the degradation level for this frame.
    ///
    /// Propagates to the buffer so widgets can read `buf.degradation`
    /// during rendering without needing access to the full Frame.
    #[inline]
    pub fn set_degradation(&mut self, level: DegradationLevel) {
        self.degradation = level;
        self.buffer.degradation = level;
    }

    /// Whether a widget should be rendered under the current degradation level.
    ///
    /// Essential widgets render up through [`DegradationLevel::Skeleton`] (only
    /// skipped at [`DegradationLevel::SkipFrame`]). Non-essential (decorative)
    /// widgets are skipped at [`DegradationLevel::EssentialOnly`] and above.
    #[inline]
    pub fn should_render_widget(&self, essential: bool) -> bool {
        self.degradation
            .max(self.buffer.degradation)
            .allows_widget(essential)
    }

    /// Get the bounding rectangle of the frame.
    #[inline]
    pub fn bounds(&self) -> Rect {
        self.buffer.bounds()
    }

    /// The full drawable area of the frame (`(0, 0)` to `(width, height)`).
    ///
    /// Same as [`Frame::bounds`]; this is the name layout code reads best
    /// (`Flex::horizontal().constraints(..).split(frame.area())`).
    #[inline]
    #[must_use]
    pub fn area(&self) -> Rect {
        self.buffer.bounds()
    }

    /// Register a hit region (if hit grid is enabled).
    ///
    /// Returns `true` if the region was registered, `false` if no hit grid.
    ///
    /// # Clipping
    ///
    /// The region is intersected with the current scissor stack of the
    /// internal buffer. Parts of the region outside the scissor are
    /// ignored.
    pub fn register_hit(
        &mut self,
        rect: Rect,
        id: HitId,
        region: HitRegion,
        data: HitData,
    ) -> bool {
        let owner = self.current_hit_owner();
        if let Some(ref mut grid) = self.hit_grid {
            // Clip against current scissor
            let clipped = rect.intersection(&self.buffer.current_scissor());
            if !clipped.is_empty() {
                grid.register_with_owner(clipped, id, region, data, owner);
            }
            true
        } else {
            false
        }
    }

    /// Temporarily attach ownership provenance to hit regions registered in `f`.
    pub fn with_hit_owner<R>(&mut self, owner: HitOwner, f: impl FnOnce(&mut Self) -> R) -> R {
        self.hit_owner_stack.push(owner);
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self)));
        self.hit_owner_stack.pop();
        match result {
            Ok(result) => result,
            Err(payload) => std::panic::resume_unwind(payload),
        }
    }

    // ── Accessibility tree collection ───────────────────────────────────

    /// Whether an accessibility tree builder is attached to this frame.
    #[must_use]
    pub fn a11y_enabled(&self) -> bool {
        self.a11y.is_some()
    }

    /// Attach the builder that collects this frame's accessibility nodes
    /// (the runtime does this once per frame when accessibility is on).
    pub fn set_a11y(&mut self, builder: &'a mut A11yTreeBuilder) {
        self.a11y = Some(builder);
    }

    /// Push one accessibility node. A no-op without a builder.
    ///
    /// The node's parent defaults to the enclosing [`Frame::with_a11y_scope`]
    /// container; a parent the widget set itself is kept. Ids must be stable
    /// across frames so the tree can be diffed and changes announced: reuse
    /// a hit id or widget id where one exists, otherwise
    /// [`A11yNodeInfo::stable_id_for`].
    ///
    /// A node whose id another node already holds this frame gets a new id
    /// derived from it. Sibling widgets at one rect share their default id,
    /// and the builder replaces a node with the same id, so the first sibling
    /// was dropped from the tree while its id stayed in the reading order.
    /// The new id depends only on the taken one and the push order, so it is
    /// the same in every frame that renders in the same order. A parent the
    /// widget set to a re-keyed id follows the node it names.
    pub fn push_a11y(&mut self, node: A11yNodeInfo) {
        let _ = self.push_a11y_node(node);
    }

    /// [`Frame::push_a11y`], returning the id the node was stored under.
    fn push_a11y_node(&mut self, mut node: A11yNodeInfo) -> Option<u64> {
        let builder = self.a11y.as_deref_mut()?;
        if let Some(parent) = node.parent
            && let Some(&assigned) = self.a11y_rekeyed.get(&parent)
        {
            node.parent = Some(assigned);
        }
        if node.parent.is_none()
            && let Some(&parent) = self.a11y_scope_stack.last()
        {
            node.parent = Some(parent);
        }
        if builder.node(node.id).is_some() {
            let taken = node.id;
            let mut id = taken;
            while builder.node(id).is_some() {
                id = rekey_a11y_id(id);
            }
            node.id = id;
            self.a11y_rekeyed.insert(taken, id);
        }
        let id = node.id;
        if let Some(parent) = node.parent {
            self.a11y_children.push((parent, id));
        }
        self.a11y_order.push(id);
        builder.add_node(node);
        Some(id)
    }

    /// Push every node a widget reports
    /// (`ftui_a11y::Accessible::accessibility_nodes`).
    pub fn push_a11y_nodes(&mut self, nodes: impl IntoIterator<Item = A11yNodeInfo>) {
        for node in nodes {
            self.push_a11y(node);
        }
    }

    /// Push `container` and make it the parent of every node pushed while
    /// `f` runs (containers such as `Block` wrap their children with this).
    /// Without a builder `f` simply runs.
    pub fn with_a11y_scope<R>(
        &mut self,
        container: A11yNodeInfo,
        f: impl FnOnce(&mut Self) -> R,
    ) -> R {
        let Some(id) = self.push_a11y_node(container) else {
            return f(self);
        };
        self.a11y_scope_stack.push(id);
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self)));
        self.a11y_scope_stack.pop();
        match result {
            Ok(result) => result,
            Err(payload) => std::panic::resume_unwind(payload),
        }
    }

    /// Node ids in push (document) order.
    #[must_use]
    pub fn a11y_order(&self) -> &[u64] {
        &self.a11y_order
    }

    /// Move the push order out (the runtime keeps it beside the built tree).
    pub fn take_a11y_order(&mut self) -> Vec<u64> {
        std::mem::take(&mut self.a11y_order)
    }

    /// Declare the application's authoritative focus target for this frame
    /// (for example from `FocusManager::sync_to_frame`).
    ///
    /// When set, [`Frame::finish_a11y`] reconciles all pushed nodes so that at
    /// most one node in the built tree has `A11yState::focused = true` and the
    /// builder's focused ID matches it:
    /// - If `focused` resolves to a composite container whose subtree contains
    ///   a focused active descendant (e.g. a selected `ListItem`, `Tree` row,
    ///   or `Dialog` button), that descendant retains focus while any focused
    ///   flags outside the target subtree are cleared.
    /// - If `focused` resolves to a leaf or container with no focused child,
    ///   that node itself receives `state.focused = true`.
    /// - If `focused` is `None` (blurred or host unfocused) or absent from the
    ///   rendered frame, all `state.focused` flags are cleared and the tree
    ///   has no focused node.
    pub fn set_a11y_focused(&mut self, focused: Option<u64>) {
        self.a11y_explicit_focus = Some(focused);
    }

    /// Apply the collected parent/child links to the builder and, when no
    /// root was set, make the first parentless node the root. Call once
    /// after the view has rendered and before the tree is built; a no-op
    /// without a builder.
    pub fn finish_a11y(&mut self) {
        let rekeyed = std::mem::take(&mut self.a11y_rekeyed);
        let explicit_focus = self.a11y_explicit_focus.take();
        let Some(builder) = self.a11y.as_deref_mut() else {
            return;
        };
        for (parent, child) in self.a11y_children.drain(..) {
            if let Some(node) = builder.node_mut(parent)
                && !node.children.contains(&child)
            {
                node.children.push(child);
            }
        }
        if builder.root().is_none()
            && let Some(&root) = self
                .a11y_order
                .iter()
                .find(|id| builder.node(**id).is_some_and(|node| node.parent.is_none()))
        {
            builder.set_root(root);
        }
        if let Some(target_opt) = explicit_focus {
            let resolved_target = target_opt.and_then(|target| {
                let mapped = rekeyed.get(&target).copied().unwrap_or(target);
                builder.node(mapped).map(|_| mapped)
            });
            let active_focus = resolved_target.map(|target| {
                let is_in_target_subtree = |builder: &A11yTreeBuilder, mut id: u64| -> bool {
                    let mut steps = 0usize;
                    loop {
                        if id == target {
                            return true;
                        }
                        let Some(parent) = builder.node(id).and_then(|n| n.parent) else {
                            return false;
                        };
                        id = parent;
                        steps += 1;
                        if steps > 256 {
                            return false;
                        }
                    }
                };
                self.a11y_order
                    .iter()
                    .copied()
                    .find(|&id| {
                        builder.node(id).is_some_and(|n| n.state.focused)
                            && is_in_target_subtree(builder, id)
                    })
                    .or_else(|| {
                        self.a11y_order.iter().copied().find(|&id| {
                            id != target
                                && builder.node(id).is_some_and(|n| n.state.selected)
                                && is_in_target_subtree(builder, id)
                        })
                    })
                    .unwrap_or(target)
            });
            for &id in &self.a11y_order {
                if let Some(node) = builder.node_mut(id) {
                    node.state.focused = Some(id) == active_focus;
                }
            }
            builder.set_focused(active_focus);
        } else if builder.focused().is_none()
            && let Some(&focused) = self
                .a11y_order
                .iter()
                .find(|id| builder.node(**id).is_some_and(|node| node.state.focused))
        {
            builder.set_focused(Some(focused));
        }
    }

    /// Hit test at the given position (if hit grid is enabled).
    #[must_use]
    pub fn hit_test(&self, x: u16, y: u16) -> Option<(HitId, HitRegion, HitData)> {
        self.hit_grid.as_ref().and_then(|grid| grid.hit_test(x, y))
    }

    /// Hit test at the given position, preserving owner provenance.
    #[must_use]
    pub fn hit_test_detailed(&self, x: u16, y: u16) -> Option<HitTestResult> {
        self.hit_grid
            .as_ref()
            .and_then(|grid| grid.hit_test_detailed(x, y))
    }

    /// Register a hit region with default metadata (Content, data=0).
    pub fn register_hit_region(&mut self, rect: Rect, id: HitId) -> bool {
        self.register_hit(rect, id, HitRegion::Content, 0)
    }

    #[inline]
    fn current_hit_owner(&self) -> Option<HitOwner> {
        self.hit_owner_stack.last().copied()
    }
}

impl<'a> Draw for Frame<'a> {
    fn draw_horizontal_line(&mut self, x: u16, y: u16, width: u16, cell: Cell) {
        self.buffer.draw_horizontal_line(x, y, width, cell);
    }

    fn draw_vertical_line(&mut self, x: u16, y: u16, height: u16, cell: Cell) {
        self.buffer.draw_vertical_line(x, y, height, cell);
    }

    fn draw_rect_filled(&mut self, rect: Rect, cell: Cell) {
        self.buffer.draw_rect_filled(rect, cell);
    }

    fn draw_rect_outline(&mut self, rect: Rect, cell: Cell) {
        self.buffer.draw_rect_outline(rect, cell);
    }

    fn print_text(&mut self, x: u16, y: u16, text: &str, base_cell: Cell) -> u16 {
        self.print_text_clipped(x, y, text, base_cell, self.width())
    }

    fn print_text_clipped(
        &mut self,
        x: u16,
        y: u16,
        text: &str,
        base_cell: Cell,
        max_x: u16,
    ) -> u16 {
        let mut cx = x;
        for grapheme in text.graphemes(true) {
            let width = grapheme_width(grapheme);
            if width == 0 {
                continue;
            }

            if cx >= max_x {
                break;
            }

            // Don't start a wide char if it won't fit
            if cx as u32 + width as u32 > max_x as u32 {
                break;
            }

            // Intern grapheme if needed (unlike Buffer::print_text, we have the pool!)
            let content = if width > 1 || grapheme.chars().count() > 1 {
                let id = self.intern_with_width(grapheme, width as u8);
                CellContent::from_grapheme(id)
            } else if let Some(c) = grapheme.chars().next() {
                CellContent::from_char(c)
            } else {
                continue;
            };

            let cell = Cell {
                content,
                fg: base_cell.fg,
                bg: base_cell.bg,
                attrs: base_cell.attrs,
            };
            self.buffer.set_fast(cx, y, cell);

            cx = cx.saturating_add(width as u16);
        }
        cx
    }

    fn draw_border(&mut self, rect: Rect, chars: BorderChars, base_cell: Cell) {
        self.buffer.draw_border(rect, chars, base_cell);
    }

    fn draw_box(&mut self, rect: Rect, chars: BorderChars, border_cell: Cell, fill_cell: Cell) {
        self.buffer.draw_box(rect, chars, border_cell, fill_cell);
    }

    fn paint_area(
        &mut self,
        rect: Rect,
        fg: Option<crate::cell::PackedRgba>,
        bg: Option<crate::cell::PackedRgba>,
    ) {
        self.buffer.paint_area(rect, fg, bg);
    }
}

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

    #[test]
    fn frame_creation() {
        let mut pool = GraphemePool::new();
        let frame = Frame::new(80, 24, &mut pool);
        assert_eq!(frame.width(), 80);
        assert_eq!(frame.height(), 24);
        assert!(frame.hit_grid.is_none());
        assert!(frame.cursor_position.is_none());
        assert!(frame.cursor_visible);
    }

    #[test]
    fn frame_with_hit_grid() {
        let mut pool = GraphemePool::new();
        let frame = Frame::with_hit_grid(80, 24, &mut pool);
        assert!(frame.hit_grid.is_some());
        assert_eq!(frame.width(), 80);
        assert_eq!(frame.height(), 24);
    }

    #[test]
    fn frame_cursor() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(80, 24, &mut pool);
        assert!(frame.cursor_position.is_none());
        assert!(frame.cursor_visible);

        frame.set_cursor(Some((10, 5)));
        assert_eq!(frame.cursor_position, Some((10, 5)));

        frame.set_cursor_visible(false);
        assert!(!frame.cursor_visible);

        frame.set_cursor(None);
        assert!(frame.cursor_position.is_none());
    }

    #[test]
    fn frame_clear() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::with_hit_grid(10, 10, &mut pool);

        // Add some content
        frame.buffer.set_raw(5, 5, Cell::from_char('X'));
        frame.register_hit_region(Rect::new(0, 0, 5, 5), HitId::new(1));

        // Verify content exists
        assert_eq!(frame.buffer.get(5, 5).unwrap().content.as_char(), Some('X'));
        assert_eq!(
            frame.hit_test(2, 2),
            Some((HitId::new(1), HitRegion::Content, 0))
        );

        // Clear
        frame.clear();

        // Verify cleared
        assert!(frame.buffer.get(5, 5).unwrap().is_empty());
        assert!(frame.hit_test(2, 2).is_none());
    }

    #[test]
    fn frame_bounds() {
        let mut pool = GraphemePool::new();
        let frame = Frame::new(80, 24, &mut pool);
        let bounds = frame.bounds();
        assert_eq!(bounds.x, 0);
        assert_eq!(bounds.y, 0);
        assert_eq!(bounds.width, 80);
        assert_eq!(bounds.height, 24);
    }

    // ── accessibility collection ───────────────────────────────────────

    fn a11y_node(id: u64, role: ftui_a11y::node::A11yRole, name: &str) -> A11yNodeInfo {
        A11yNodeInfo::new(id, role, Rect::new(0, 0, 10, 1)).with_name(name)
    }

    #[test]
    fn finish_a11y_derives_focus_from_node_state() {
        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};
        use ftui_a11y::tree::A11yTreeBuilder;

        let focused_state = A11yState {
            focused: true,
            ..A11yState::default()
        };

        // No explicit focus: the first focused node in reading order wins.
        let mut pool = GraphemePool::new();
        let mut builder = A11yTreeBuilder::new();
        let mut frame = Frame::new(20, 4, &mut pool);
        frame.set_a11y(&mut builder);
        frame.push_a11y(A11yNodeInfo::new(
            1,
            A11yRole::Button,
            Rect::new(0, 0, 5, 1),
        ));
        frame.push_a11y(
            A11yNodeInfo::new(2, A11yRole::TextInput, Rect::new(0, 1, 5, 1))
                .with_state(focused_state.clone()),
        );
        frame.push_a11y(
            A11yNodeInfo::new(3, A11yRole::Button, Rect::new(0, 2, 5, 1))
                .with_state(focused_state.clone()),
        );
        frame.finish_a11y();
        drop(frame);
        assert_eq!(builder.focused(), Some(2));

        // Explicit focus is left alone.
        let mut builder = A11yTreeBuilder::new();
        builder.set_focused(Some(9));
        let mut frame = Frame::new(20, 4, &mut pool);
        frame.set_a11y(&mut builder);
        frame.push_a11y(
            A11yNodeInfo::new(2, A11yRole::TextInput, Rect::new(0, 1, 5, 1))
                .with_state(focused_state),
        );
        frame.finish_a11y();
        drop(frame);
        assert_eq!(builder.focused(), Some(9));

        // Nothing focused: stays unset.
        let mut builder = A11yTreeBuilder::new();
        let mut frame = Frame::new(20, 4, &mut pool);
        frame.set_a11y(&mut builder);
        frame.push_a11y(A11yNodeInfo::new(
            1,
            A11yRole::Button,
            Rect::new(0, 0, 5, 1),
        ));
        frame.finish_a11y();
        drop(frame);
        assert_eq!(builder.focused(), None);
    }

    #[test]
    fn frame_a11y_is_a_noop_without_a_builder() {
        use ftui_a11y::node::A11yRole;
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(20, 5, &mut pool);
        assert!(!frame.a11y_enabled());
        frame.push_a11y(a11y_node(1, A11yRole::Label, "lonely"));
        let ran = frame.with_a11y_scope(a11y_node(2, A11yRole::Window, "w"), |f| {
            f.push_a11y(a11y_node(3, A11yRole::Button, "b"));
            42
        });
        assert_eq!(ran, 42);
        frame.finish_a11y();
        assert!(frame.a11y_order().is_empty());
        assert!(frame.take_a11y_order().is_empty());
    }

    #[test]
    fn frame_a11y_collects_nodes_with_scope_parents_and_a_root() {
        use ftui_a11y::node::A11yRole;
        let mut pool = GraphemePool::new();
        let mut builder = A11yTreeBuilder::new();
        let mut frame = Frame::new(20, 5, &mut pool);
        frame.set_a11y(&mut builder);
        assert!(frame.a11y_enabled());

        frame.with_a11y_scope(a11y_node(1, A11yRole::Window, "main"), |f| {
            f.push_a11y(a11y_node(2, A11yRole::Button, "ok"));
            f.with_a11y_scope(a11y_node(3, A11yRole::List, "items"), |f| {
                f.push_a11y_nodes(vec![
                    a11y_node(4, A11yRole::ListItem, "first"),
                    a11y_node(5, A11yRole::ListItem, "second"),
                ]);
            });
            // An explicit parent set by the widget is kept.
            f.push_a11y(a11y_node(6, A11yRole::Label, "detached").with_parent(99));
        });
        frame.push_a11y(a11y_node(7, A11yRole::Label, "status"));
        assert_eq!(frame.a11y_order(), &[1, 2, 3, 4, 5, 6, 7]);
        frame.finish_a11y();
        let order = frame.take_a11y_order();
        drop(frame);

        let tree = builder.build();
        assert_eq!(tree.root_id(), Some(1), "first parentless node is the root");
        assert_eq!(tree.node(2).and_then(|n| n.parent), Some(1));
        assert_eq!(tree.node(4).and_then(|n| n.parent), Some(3));
        assert_eq!(tree.node(6).and_then(|n| n.parent), Some(99));
        assert_eq!(tree.node(7).and_then(|n| n.parent), None);
        // The explicit parent (99, never pushed) keeps node 6 out of the
        // scope container's children; the dangling link is simply dropped.
        assert_eq!(tree.node(1).map(|n| n.children.clone()), Some(vec![2, 3]));
        assert_eq!(tree.node(3).map(|n| n.children.clone()), Some(vec![4, 5]));
        assert_eq!(tree.ancestors(5), vec![5, 3, 1], "self, parent, root");

        let text = tree.dump_text(&order);
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines.len(), 7, "{text}");
        assert!(
            lines[0].starts_with("Window \"main\" [] @0,0 10x1"),
            "{text}"
        );
        assert!(lines[1].starts_with("  Button \"ok\""), "{text}");
        assert!(lines[3].starts_with("    ListItem \"first\""), "{text}");
        assert!(lines[6].starts_with("Label \"status\""), "{text}");
    }

    #[test]
    fn frame_a11y_rekeys_a_taken_id_instead_of_dropping_the_node() {
        use ftui_a11y::node::A11yRole;

        // Two sibling containers at one rect share id 10; the second one's
        // children name it both through the scope and as an explicit parent.
        let render = |builder: &mut A11yTreeBuilder| {
            let mut pool = GraphemePool::new();
            let mut frame = Frame::new(20, 5, &mut pool);
            frame.set_a11y(builder);
            frame.with_a11y_scope(a11y_node(1, A11yRole::Window, "main"), |f| {
                f.with_a11y_scope(a11y_node(10, A11yRole::Group, "first"), |f| {
                    f.push_a11y(a11y_node(11, A11yRole::Label, "a"));
                });
                f.with_a11y_scope(a11y_node(10, A11yRole::Group, "second"), |f| {
                    f.push_a11y(a11y_node(11, A11yRole::Label, "b"));
                });
                f.push_a11y(a11y_node(12, A11yRole::Label, "c").with_parent(10));
            });
            frame.finish_a11y();
            frame.take_a11y_order()
        };

        let mut builder = A11yTreeBuilder::new();
        let order = render(&mut builder);
        let tree = builder.build();
        assert_eq!(order.len(), 6);
        assert_eq!(tree.node_count(), 6, "no node was replaced");
        let unique: std::collections::HashSet<u64> = order.iter().copied().collect();
        assert_eq!(unique.len(), order.len(), "{order:?}");

        let name = |id: u64| tree.node(id).and_then(|n| n.name.clone()).unwrap();
        let second = order[3];
        assert_eq!(name(order[1]), "first");
        assert_eq!(name(second), "second");
        assert_ne!(second, 10);
        // Each label sits under its own group, and the explicit parent 10,
        // pushed after the second group took 10's place, follows it.
        assert_eq!(tree.node(order[2]).and_then(|n| n.parent), Some(10));
        assert_eq!(tree.node(order[4]).and_then(|n| n.parent), Some(second));
        assert_eq!(tree.node(order[5]).and_then(|n| n.parent), Some(second));
        assert_eq!(name(order[4]), "b");

        // The same render gives the same ids in the next frame.
        let mut again = A11yTreeBuilder::new();
        assert_eq!(render(&mut again), order);
    }

    #[test]
    fn stable_a11y_ids_depend_on_role_and_bounds_only() {
        use ftui_a11y::node::A11yRole;
        let a = A11yNodeInfo::stable_id_for(A11yRole::Button, Rect::new(1, 2, 3, 4));
        let same = A11yNodeInfo::stable_id_for(A11yRole::Button, Rect::new(1, 2, 3, 4));
        let moved = A11yNodeInfo::stable_id_for(A11yRole::Button, Rect::new(2, 2, 3, 4));
        let other_role = A11yNodeInfo::stable_id_for(A11yRole::Label, Rect::new(1, 2, 3, 4));
        assert_eq!(a, same);
        assert_ne!(a, moved);
        assert_ne!(a, other_role);
    }

    #[test]
    fn push_a11y_collects_nodes_in_render_order_with_block_nesting() {
        use ftui_a11y::node::A11yRole;
        use ftui_a11y::tree::A11yTreeBuilder;

        let mut pool = GraphemePool::new();
        let mut builder = A11yTreeBuilder::new();
        let mut frame = Frame::new(40, 10, &mut pool);
        frame.set_a11y(&mut builder);

        frame.with_a11y_scope(a11y_node(100, A11yRole::Group, "Form Block"), |f| {
            f.push_a11y(a11y_node(101, A11yRole::TextInput, "First"));
            f.push_a11y(a11y_node(102, A11yRole::TextInput, "Second"));
        });
        frame.finish_a11y();
        let order = frame.take_a11y_order();
        drop(frame);

        let tree = builder.build();
        assert_eq!(order, vec![100, 101, 102]);
        assert_eq!(tree.node_count(), 3);
        assert_eq!(tree.root_id(), Some(100));
        assert_eq!(tree.node(101).and_then(|n| n.parent), Some(100));
        assert_eq!(tree.node(102).and_then(|n| n.parent), Some(100));
        assert_eq!(
            tree.node(100).map(|n| n.children.clone()),
            Some(vec![101, 102])
        );
    }

    #[test]
    fn push_a11y_is_noop_without_builder() {
        frame_a11y_is_a_noop_without_a_builder();
    }

    #[test]
    fn nested_scopes_three_deep_record_ancestry() {
        use ftui_a11y::node::A11yRole;
        use ftui_a11y::tree::A11yTreeBuilder;

        let mut pool = GraphemePool::new();
        let mut builder = A11yTreeBuilder::new();
        let mut frame = Frame::new(40, 10, &mut pool);
        frame.set_a11y(&mut builder);

        frame.with_a11y_scope(a11y_node(1, A11yRole::Window, "Win"), |f| {
            f.with_a11y_scope(a11y_node(2, A11yRole::Group, "Grp"), |f| {
                f.with_a11y_scope(a11y_node(3, A11yRole::List, "Lst"), |f| {
                    f.push_a11y(a11y_node(4, A11yRole::ListItem, "Itm"));
                });
            });
        });
        frame.finish_a11y();
        drop(frame);

        let tree = builder.build();
        assert_eq!(tree.ancestors(4), vec![4, 3, 2, 1]);
    }

    #[test]
    fn finish_a11y_applies_pending_children_once() {
        use ftui_a11y::node::A11yRole;
        use ftui_a11y::tree::A11yTreeBuilder;

        let mut pool = GraphemePool::new();
        let mut builder = A11yTreeBuilder::new();
        let mut frame = Frame::new(40, 10, &mut pool);
        frame.set_a11y(&mut builder);

        frame.with_a11y_scope(a11y_node(1, A11yRole::Group, "Parent"), |f| {
            f.push_a11y(a11y_node(2, A11yRole::Button, "Child"));
        });
        frame.finish_a11y();
        frame.finish_a11y();
        drop(frame);

        let tree = builder.build();
        assert_eq!(tree.node(1).map(|n| n.children.clone()), Some(vec![2]));
    }

    #[test]
    fn duplicate_ids_in_one_frame_debug_assert() {
        frame_a11y_rekeys_a_taken_id_instead_of_dropping_the_node();
    }

    #[test]
    fn frame_area_is_the_full_buffer_rect() {
        let mut pool = GraphemePool::new();
        let frame = Frame::new(120, 40, &mut pool);
        assert_eq!(frame.area(), frame.bounds());
        assert_eq!(frame.area(), Rect::new(0, 0, 120, 40));
        // `Buffer::new` clamps to at least 1x1, so a "zero-sized" frame still
        // reports a well-formed, drawable area rather than an empty rect.
        let empty = Frame::new(0, 0, &mut pool);
        assert_eq!(empty.area(), empty.bounds());
        assert_eq!(empty.area(), Rect::new(0, 0, 1, 1));
    }

    #[test]
    fn hit_grid_creation() {
        let grid = HitGrid::new(80, 24);
        assert_eq!(grid.width(), 80);
        assert_eq!(grid.height(), 24);
    }

    #[test]
    fn hit_grid_registration() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::with_hit_grid(80, 24, &mut pool);
        let hit_id = HitId::new(42);
        let rect = Rect::new(10, 5, 20, 3);

        frame.register_hit(rect, hit_id, HitRegion::Button, 99);

        // Inside rect
        assert_eq!(frame.hit_test(15, 6), Some((hit_id, HitRegion::Button, 99)));
        assert_eq!(frame.hit_test(10, 5), Some((hit_id, HitRegion::Button, 99))); // Top-left corner
        assert_eq!(frame.hit_test(29, 7), Some((hit_id, HitRegion::Button, 99))); // Bottom-right corner

        // Outside rect
        assert!(frame.hit_test(5, 5).is_none()); // Left of rect
        assert!(frame.hit_test(30, 6).is_none()); // Right of rect (exclusive)
        assert!(frame.hit_test(15, 8).is_none()); // Below rect
        assert!(frame.hit_test(15, 4).is_none()); // Above rect
    }

    #[test]
    fn hit_grid_overlapping_regions() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::with_hit_grid(20, 20, &mut pool);

        // Register two overlapping regions
        frame.register_hit(
            Rect::new(0, 0, 10, 10),
            HitId::new(1),
            HitRegion::Content,
            1,
        );
        frame.register_hit(Rect::new(5, 5, 10, 10), HitId::new(2), HitRegion::Border, 2);

        // Non-overlapping region from first
        assert_eq!(
            frame.hit_test(2, 2),
            Some((HitId::new(1), HitRegion::Content, 1))
        );

        // Overlapping region - second wins (last registered)
        assert_eq!(
            frame.hit_test(7, 7),
            Some((HitId::new(2), HitRegion::Border, 2))
        );

        // Non-overlapping region from second
        assert_eq!(
            frame.hit_test(12, 12),
            Some((HitId::new(2), HitRegion::Border, 2))
        );
    }

    #[test]
    fn hit_grid_out_of_bounds() {
        let mut pool = GraphemePool::new();
        let frame = Frame::with_hit_grid(10, 10, &mut pool);

        // Out of bounds returns None
        assert!(frame.hit_test(100, 100).is_none());
        assert!(frame.hit_test(10, 0).is_none()); // Exclusive bound
        assert!(frame.hit_test(0, 10).is_none()); // Exclusive bound
    }

    #[test]
    fn hit_id_properties() {
        let id = HitId::new(42);
        assert_eq!(id.id(), 42);
        assert_eq!(id, HitId(42));
    }

    #[test]
    fn register_hit_region_no_grid() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 10, &mut pool);
        let result = frame.register_hit_region(Rect::new(0, 0, 5, 5), HitId::new(1));
        assert!(!result); // No hit grid, returns false
    }

    #[test]
    fn register_hit_region_with_grid() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::with_hit_grid(10, 10, &mut pool);
        let result = frame.register_hit_region(Rect::new(0, 0, 5, 5), HitId::new(1));
        assert!(result); // Has hit grid, returns true
    }

    #[test]
    fn hit_grid_clear() {
        let mut grid = HitGrid::new(10, 10);
        grid.register(Rect::new(0, 0, 5, 5), HitId::new(1), HitRegion::Content, 0);

        assert_eq!(
            grid.hit_test(2, 2),
            Some((HitId::new(1), HitRegion::Content, 0))
        );

        grid.clear();

        assert!(grid.hit_test(2, 2).is_none());
    }

    #[test]
    fn hit_grid_boundary_clipping() {
        let mut grid = HitGrid::new(10, 10);

        // Register region that extends beyond grid
        grid.register(
            Rect::new(8, 8, 10, 10),
            HitId::new(1),
            HitRegion::Content,
            0,
        );

        // Inside clipped region
        assert_eq!(
            grid.hit_test(9, 9),
            Some((HitId::new(1), HitRegion::Content, 0))
        );

        // Outside grid
        assert!(grid.hit_test(10, 10).is_none());
    }

    #[test]
    fn hit_grid_edge_and_corner_cells() {
        let mut grid = HitGrid::new(4, 4);
        grid.register(Rect::new(3, 0, 1, 4), HitId::new(7), HitRegion::Border, 11);

        // Right-most column corners
        assert_eq!(
            grid.hit_test(3, 0),
            Some((HitId::new(7), HitRegion::Border, 11))
        );
        assert_eq!(
            grid.hit_test(3, 3),
            Some((HitId::new(7), HitRegion::Border, 11))
        );

        // Neighboring cells remain empty
        assert!(grid.hit_test(2, 0).is_none());
        assert!(grid.hit_test(4, 0).is_none());
        assert!(grid.hit_test(3, 4).is_none());

        let mut grid = HitGrid::new(4, 4);
        grid.register(Rect::new(0, 3, 4, 1), HitId::new(9), HitRegion::Content, 21);

        // Bottom row corners
        assert_eq!(
            grid.hit_test(0, 3),
            Some((HitId::new(9), HitRegion::Content, 21))
        );
        assert_eq!(
            grid.hit_test(3, 3),
            Some((HitId::new(9), HitRegion::Content, 21))
        );

        // Outside bottom row
        assert!(grid.hit_test(0, 2).is_none());
        assert!(grid.hit_test(0, 4).is_none());
    }

    #[test]
    fn frame_register_hit_respects_nested_scissor() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::with_hit_grid(10, 10, &mut pool);

        let outer = Rect::new(1, 1, 8, 8);
        frame.buffer.push_scissor(outer);
        assert_eq!(frame.buffer.current_scissor(), outer);

        let inner = Rect::new(4, 4, 10, 10);
        frame.buffer.push_scissor(inner);
        let clipped = outer.intersection(&inner);
        let current = frame.buffer.current_scissor();
        assert_eq!(current, clipped);

        // Monotonic intersection: inner scissor must stay within outer.
        assert!(outer.contains(current.x, current.y));
        assert!(outer.contains(
            current.right().saturating_sub(1),
            current.bottom().saturating_sub(1)
        ));

        frame.register_hit(
            Rect::new(0, 0, 10, 10),
            HitId::new(3),
            HitRegion::Button,
            99,
        );

        assert_eq!(
            frame.hit_test(4, 4),
            Some((HitId::new(3), HitRegion::Button, 99))
        );
        assert_eq!(
            frame.hit_test(8, 8),
            Some((HitId::new(3), HitRegion::Button, 99))
        );
        assert!(frame.hit_test(3, 3).is_none()); // inside outer, outside inner
        assert!(frame.hit_test(0, 0).is_none()); // outside all scissor

        frame.buffer.pop_scissor();
        assert_eq!(frame.buffer.current_scissor(), outer);
    }

    #[test]
    fn hit_grid_hits_in_area() {
        let mut grid = HitGrid::new(5, 5);
        grid.register(Rect::new(0, 0, 2, 2), HitId::new(1), HitRegion::Content, 10);
        grid.register(Rect::new(1, 1, 2, 2), HitId::new(2), HitRegion::Button, 20);

        let hits = grid.hits_in(Rect::new(0, 0, 3, 3));
        assert!(hits.contains(&(HitId::new(1), HitRegion::Content, 10)));
        assert!(hits.contains(&(HitId::new(2), HitRegion::Button, 20)));
    }

    #[test]
    fn frame_intern() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 10, &mut pool);

        let id = frame.intern("👋");
        assert_eq!(frame.pool.get(id), Some("👋"));
    }

    #[test]
    fn frame_intern_with_width() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 10, &mut pool);

        let id = frame.intern_with_width("🧪", 2);
        assert_eq!(id.width(), 2);
        assert_eq!(frame.pool.get(id), Some("🧪"));
    }

    #[test]
    fn frame_print_text_emoji_presentation_sets_continuation() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(5, 1, &mut pool);

        // Use a skin-tone modifier sequence (width 2, multi-codepoint, no VS16
        // dependency) so the test is independent of ftui-core's VS16 policy.
        frame.print_text(0, 0, "👍🏽", Cell::from_char(' '));

        let head = frame.buffer.get(0, 0).unwrap();
        let tail = frame.buffer.get(1, 0).unwrap();

        assert_eq!(head.content.width(), 2);
        assert!(tail.content.is_continuation());
    }

    #[test]
    fn frame_enable_hit_testing() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 10, &mut pool);
        assert!(frame.hit_grid.is_none());

        frame.enable_hit_testing();
        assert!(frame.hit_grid.is_some());

        // Calling again is idempotent
        frame.enable_hit_testing();
        assert!(frame.hit_grid.is_some());
    }

    #[test]
    fn frame_enable_hit_testing_then_register() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 10, &mut pool);
        frame.enable_hit_testing();

        let registered = frame.register_hit_region(Rect::new(0, 0, 5, 5), HitId::new(1));
        assert!(registered);
        assert_eq!(
            frame.hit_test(2, 2),
            Some((HitId::new(1), HitRegion::Content, 0))
        );
    }

    #[test]
    fn hit_cell_default_is_empty() {
        let cell = HitCell::default();
        assert!(cell.is_empty());
        assert_eq!(cell.widget_id, None);
        assert_eq!(cell.region, HitRegion::None);
        assert_eq!(cell.data, 0);
    }

    #[test]
    fn hit_cell_new_is_not_empty() {
        let cell = HitCell::new(HitId::new(1), HitRegion::Button, 42);
        assert!(!cell.is_empty());
        assert_eq!(cell.widget_id, Some(HitId::new(1)));
        assert_eq!(cell.region, HitRegion::Button);
        assert_eq!(cell.data, 42);
    }

    #[test]
    fn hit_region_variants() {
        assert_eq!(HitRegion::default(), HitRegion::None);

        // All variants are distinct
        let variants = [
            HitRegion::None,
            HitRegion::Content,
            HitRegion::Border,
            HitRegion::Scrollbar,
            HitRegion::Handle,
            HitRegion::Button,
            HitRegion::Link,
            HitRegion::Custom(0),
            HitRegion::Custom(1),
            HitRegion::Custom(255),
        ];
        for i in 0..variants.len() {
            for j in (i + 1)..variants.len() {
                assert_ne!(
                    variants[i], variants[j],
                    "variants {i} and {j} should differ"
                );
            }
        }
    }

    #[test]
    fn hit_id_default() {
        let id = HitId::default();
        assert_eq!(id.id(), 0);
    }

    #[test]
    fn hit_grid_initial_cells_empty() {
        let grid = HitGrid::new(5, 5);
        for y in 0..5 {
            for x in 0..5 {
                let cell = grid.get(x, y).unwrap();
                assert!(cell.is_empty());
            }
        }
    }

    #[test]
    fn hit_grid_zero_dimensions() {
        let grid = HitGrid::new(0, 0);
        assert_eq!(grid.width(), 0);
        assert_eq!(grid.height(), 0);
        assert!(grid.get(0, 0).is_none());
        assert!(grid.hit_test(0, 0).is_none());
    }

    #[test]
    fn hit_grid_hits_in_empty_area() {
        let grid = HitGrid::new(10, 10);
        let hits = grid.hits_in(Rect::new(0, 0, 5, 5));
        // All cells are empty, so no actual HitId hits
        assert!(hits.is_empty());
    }

    #[test]
    fn hit_grid_hits_in_clipped_area() {
        let mut grid = HitGrid::new(5, 5);
        grid.register(Rect::new(0, 0, 5, 5), HitId::new(1), HitRegion::Content, 0);

        // Query area extends beyond grid — should be clipped
        let hits = grid.hits_in(Rect::new(3, 3, 10, 10));
        assert_eq!(hits.len(), 4); // 2x2 cells inside grid
    }

    #[test]
    fn hit_test_no_grid_returns_none() {
        let mut pool = GraphemePool::new();
        let frame = Frame::new(10, 10, &mut pool);
        assert!(frame.hit_test(0, 0).is_none());
    }

    #[test]
    fn frame_cursor_operations() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(80, 24, &mut pool);

        // Set position at edge of frame
        frame.set_cursor(Some((79, 23)));
        assert_eq!(frame.cursor_position, Some((79, 23)));

        // Set position at origin
        frame.set_cursor(Some((0, 0)));
        assert_eq!(frame.cursor_position, Some((0, 0)));

        // Toggle visibility
        frame.set_cursor_visible(false);
        assert!(!frame.cursor_visible);
        frame.set_cursor_visible(true);
        assert!(frame.cursor_visible);
    }

    #[test]
    fn hit_data_large_values() {
        let mut grid = HitGrid::new(5, 5);
        // HitData is u64, test max value
        grid.register(
            Rect::new(0, 0, 1, 1),
            HitId::new(1),
            HitRegion::Content,
            u64::MAX,
        );
        let result = grid.hit_test(0, 0);
        assert_eq!(result, Some((HitId::new(1), HitRegion::Content, u64::MAX)));
    }

    #[test]
    fn hit_id_large_value() {
        let id = HitId::new(u32::MAX);
        assert_eq!(id.id(), u32::MAX);
    }

    #[test]
    fn frame_print_text_interns_complex_graphemes() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 1, &mut pool);

        // Flag emoji (complex grapheme)
        let flag = "🇺🇸";
        assert!(flag.chars().count() > 1);

        frame.print_text(0, 0, flag, Cell::default());

        let cell = frame.buffer.get(0, 0).unwrap();
        assert!(cell.content.is_grapheme());

        let id = cell.content.grapheme_id().unwrap();
        assert_eq!(frame.pool.get(id), Some(flag));
    }

    // --- HitId trait coverage ---

    #[test]
    fn hit_id_debug_clone_copy_hash() {
        let id = HitId::new(99);
        let dbg = format!("{:?}", id);
        assert!(dbg.contains("99"), "Debug: {dbg}");
        let copied: HitId = id; // Copy
        assert_eq!(id, copied);
        // Hash: insert into set
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(id);
        set.insert(HitId::new(99));
        assert_eq!(set.len(), 1);
        set.insert(HitId::new(100));
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn hit_id_eq_and_ne() {
        assert_eq!(HitId::new(0), HitId::new(0));
        assert_ne!(HitId::new(0), HitId::new(1));
        assert_ne!(HitId::new(u32::MAX), HitId::default());
    }

    // --- HitRegion trait coverage ---

    #[test]
    fn hit_region_debug_clone_copy_hash() {
        let r = HitRegion::Custom(42);
        let dbg = format!("{:?}", r);
        assert!(dbg.contains("Custom"), "Debug: {dbg}");
        let copied: HitRegion = r; // Copy
        assert_eq!(r, copied);
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(r);
        set.insert(HitRegion::Custom(42));
        assert_eq!(set.len(), 1);
    }

    // --- HitCell trait coverage ---

    #[test]
    fn hit_cell_debug_clone_copy_eq() {
        let cell = HitCell::new(HitId::new(5), HitRegion::Link, 123);
        let dbg = format!("{:?}", cell);
        assert!(dbg.contains("Link"), "Debug: {dbg}");
        let copied: HitCell = cell; // Copy
        assert_eq!(cell, copied);
        // ne
        assert_ne!(cell, HitCell::default());
    }

    // --- HitGrid edge cases ---

    #[test]
    fn hit_grid_clone() {
        let mut grid = HitGrid::new(5, 5);
        grid.register(Rect::new(0, 0, 2, 2), HitId::new(1), HitRegion::Content, 7);
        let clone = grid.clone();
        assert_eq!(clone.width(), 5);
        assert_eq!(
            clone.hit_test(0, 0),
            Some((HitId::new(1), HitRegion::Content, 7))
        );
    }

    #[test]
    fn hit_grid_get_mut() {
        let mut grid = HitGrid::new(5, 5);
        // Mutate a cell directly
        if let Some(cell) = grid.get_mut(2, 3) {
            *cell = HitCell::new(HitId::new(77), HitRegion::Handle, 55);
        }
        assert_eq!(
            grid.hit_test(2, 3),
            Some((HitId::new(77), HitRegion::Handle, 55))
        );
        // Out of bounds returns None
        assert!(grid.get_mut(5, 5).is_none());
    }

    #[test]
    fn hit_grid_zero_width_nonzero_height() {
        let grid = HitGrid::new(0, 10);
        assert_eq!(grid.width(), 0);
        assert_eq!(grid.height(), 10);
        assert!(grid.get(0, 0).is_none());
        assert!(grid.hit_test(0, 5).is_none());
    }

    #[test]
    fn hit_grid_nonzero_width_zero_height() {
        let grid = HitGrid::new(10, 0);
        assert_eq!(grid.width(), 10);
        assert_eq!(grid.height(), 0);
        assert!(grid.get(0, 0).is_none());
    }

    #[test]
    fn hit_grid_register_zero_width_rect() {
        let mut grid = HitGrid::new(10, 10);
        grid.register(Rect::new(2, 2, 0, 5), HitId::new(1), HitRegion::Content, 0);
        // Nothing should be registered
        assert!(grid.hit_test(2, 2).is_none());
    }

    #[test]
    fn hit_grid_register_zero_height_rect() {
        let mut grid = HitGrid::new(10, 10);
        grid.register(Rect::new(2, 2, 5, 0), HitId::new(1), HitRegion::Content, 0);
        assert!(grid.hit_test(2, 2).is_none());
    }

    #[test]
    fn hit_grid_register_past_bounds() {
        let mut grid = HitGrid::new(10, 10);
        // Rect starts past the grid boundary
        grid.register(
            Rect::new(10, 10, 5, 5),
            HitId::new(1),
            HitRegion::Content,
            0,
        );
        assert!(grid.hit_test(9, 9).is_none());
    }

    #[test]
    fn hit_grid_full_coverage() {
        let mut grid = HitGrid::new(3, 3);
        grid.register(Rect::new(0, 0, 3, 3), HitId::new(1), HitRegion::Content, 0);
        // Every cell should be filled
        for y in 0..3 {
            for x in 0..3 {
                assert_eq!(
                    grid.hit_test(x, y),
                    Some((HitId::new(1), HitRegion::Content, 0))
                );
            }
        }
    }

    #[test]
    fn hit_grid_single_cell() {
        let mut grid = HitGrid::new(1, 1);
        grid.register(Rect::new(0, 0, 1, 1), HitId::new(1), HitRegion::Button, 42);
        assert_eq!(
            grid.hit_test(0, 0),
            Some((HitId::new(1), HitRegion::Button, 42))
        );
        assert!(grid.hit_test(1, 0).is_none());
        assert!(grid.hit_test(0, 1).is_none());
    }

    #[test]
    fn hit_grid_hits_in_outside_rect() {
        let mut grid = HitGrid::new(5, 5);
        grid.register(Rect::new(0, 0, 2, 2), HitId::new(1), HitRegion::Content, 0);
        // Query area completely outside registered region
        let hits = grid.hits_in(Rect::new(3, 3, 2, 2));
        assert!(hits.is_empty());
    }

    #[test]
    fn hit_grid_hits_in_zero_rect() {
        let mut grid = HitGrid::new(5, 5);
        grid.register(Rect::new(0, 0, 5, 5), HitId::new(1), HitRegion::Content, 0);
        let hits = grid.hits_in(Rect::new(2, 2, 0, 0));
        assert!(hits.is_empty());
    }

    // --- CostEstimateSource ---

    #[test]
    fn cost_estimate_source_traits() {
        let a = CostEstimateSource::Measured;
        let b = CostEstimateSource::AreaFallback;
        let c = CostEstimateSource::FixedDefault;
        let dbg = format!("{:?}", a);
        assert!(dbg.contains("Measured"), "Debug: {dbg}");

        // Default
        assert_eq!(
            CostEstimateSource::default(),
            CostEstimateSource::FixedDefault
        );

        // Clone/Copy
        let copied: CostEstimateSource = a;
        assert_eq!(a, copied);

        // All variants distinct
        assert_ne!(a, b);
        assert_ne!(b, c);
        assert_ne!(a, c);
    }

    // --- WidgetSignal ---

    #[test]
    fn widget_signal_default() {
        let sig = WidgetSignal::default();
        assert_eq!(sig.widget_id, 0);
        assert!(!sig.essential);
        assert!((sig.priority - 0.5).abs() < f32::EPSILON);
        assert_eq!(sig.staleness_ms, 0);
        assert!((sig.focus_boost - 0.0).abs() < f32::EPSILON);
        assert!((sig.interaction_boost - 0.0).abs() < f32::EPSILON);
        assert_eq!(sig.area_cells, 1);
        assert!((sig.cost_estimate_us - 5.0).abs() < f32::EPSILON);
        assert!((sig.recent_cost_us - 5.0).abs() < f32::EPSILON);
        assert_eq!(sig.estimate_source, CostEstimateSource::FixedDefault);
    }

    #[test]
    fn widget_signal_new() {
        let sig = WidgetSignal::new(42);
        assert_eq!(sig.widget_id, 42);
        // Other fields should be default
        assert!(!sig.essential);
        assert!((sig.priority - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn widget_signal_debug_clone() {
        let sig = WidgetSignal::new(7);
        let dbg = format!("{:?}", sig);
        assert!(dbg.contains("widget_id"), "Debug: {dbg}");
        let cloned = sig.clone();
        assert_eq!(cloned.widget_id, 7);
    }

    // --- WidgetBudget ---

    #[test]
    fn widget_budget_default_is_allow_all() {
        let budget = WidgetBudget::default();
        assert!(budget.allows(0, false));
        assert!(budget.allows(u64::MAX, false));
        assert!(budget.allows(42, true));
    }

    #[test]
    fn widget_budget_allow_only() {
        let budget = WidgetBudget::allow_only(vec![10, 20, 30]);
        assert!(budget.allows(10, false));
        assert!(budget.allows(20, false));
        assert!(budget.allows(30, false));
        assert!(!budget.allows(15, false));
        assert!(!budget.allows(0, false));
    }

    #[test]
    fn widget_budget_essential_always_allowed() {
        let budget = WidgetBudget::allow_only(vec![10]);
        // Essential widgets bypass the allow list
        assert!(budget.allows(999, true));
        assert!(budget.allows(0, true));
    }

    #[test]
    fn widget_budget_allow_only_dedup() {
        let budget = WidgetBudget::allow_only(vec![5, 5, 5, 10, 10]);
        assert!(budget.allows(5, false));
        assert!(budget.allows(10, false));
        assert!(!budget.allows(7, false));
    }

    #[test]
    fn widget_budget_allow_only_empty() {
        let budget = WidgetBudget::allow_only(vec![]);
        // No widgets allowed (except essential)
        assert!(!budget.allows(0, false));
        assert!(!budget.allows(1, false));
        assert!(budget.allows(1, true)); // essential always passes
    }

    #[test]
    fn widget_budget_debug_clone() {
        let budget = WidgetBudget::allow_only(vec![1, 2, 3]);
        let dbg = format!("{:?}", budget);
        assert!(dbg.contains("allow_list"), "Debug: {dbg}");
        let cloned = budget.clone();
        assert!(cloned.allows(2, false));
    }

    // --- Frame construction variants ---

    #[test]
    fn frame_zero_dimensions_clamped_to_one() {
        let mut pool = GraphemePool::new();
        let frame = Frame::new(0, 0, &mut pool);
        assert_eq!(frame.buffer.width(), 1);
        assert_eq!(frame.buffer.height(), 1);
    }

    #[test]
    fn frame_from_buffer() {
        let mut pool = GraphemePool::new();
        let mut buf = Buffer::new(20, 10);
        buf.set_raw(5, 5, Cell::from_char('Z'));
        let frame = Frame::from_buffer(buf, &mut pool);
        assert_eq!(frame.width(), 20);
        assert_eq!(frame.height(), 10);
        assert_eq!(frame.buffer.get(5, 5).unwrap().content.as_char(), Some('Z'));
        assert!(frame.hit_grid.is_none());
        assert!(frame.cursor_visible);
    }

    #[test]
    fn frame_with_links() {
        let mut pool = GraphemePool::new();
        let mut links = LinkRegistry::new();
        let frame = Frame::with_links(10, 5, &mut pool, &mut links);
        assert!(frame.links.is_some());
        assert_eq!(frame.width(), 10);
        assert_eq!(frame.height(), 5);
    }

    #[test]
    fn frame_set_links() {
        let mut pool = GraphemePool::new();
        let mut links = LinkRegistry::new();
        let mut frame = Frame::new(10, 5, &mut pool);
        assert!(frame.links.is_none());
        frame.set_links(&mut links);
        assert!(frame.links.is_some());
    }

    #[test]
    fn frame_register_link_no_registry() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 5, &mut pool);
        // No link registry => returns 0
        let id = frame.register_link("https://example.com");
        assert_eq!(id, 0);
    }

    #[test]
    fn frame_register_link_with_registry() {
        let mut pool = GraphemePool::new();
        let mut links = LinkRegistry::new();
        let mut frame = Frame::with_links(10, 5, &mut pool, &mut links);
        let id = frame.register_link("https://example.com");
        assert!(id > 0);
        // Same URL should return same ID
        let id2 = frame.register_link("https://example.com");
        assert_eq!(id, id2);
        // Different URL should return different ID
        let id3 = frame.register_link("https://other.com");
        assert_ne!(id, id3);
    }

    // --- Frame widget budget integration ---

    #[test]
    fn frame_set_widget_budget() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 10, &mut pool);

        // Default allows all
        assert!(frame.should_render_widget_by_id(42, false));

        // Set restricted budget
        frame.set_widget_budget(WidgetBudget::allow_only(vec![1, 2]));
        assert!(frame.should_render_widget_by_id(1, false));
        assert!(!frame.should_render_widget_by_id(42, false));
        assert!(frame.should_render_widget_by_id(42, true)); // essential
    }

    // --- Frame widget signals ---

    #[test]
    fn frame_widget_signals_lifecycle() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 10, &mut pool);
        assert!(frame.widget_signals().is_empty());

        frame.register_widget_signal(WidgetSignal::new(1));
        frame.register_widget_signal(WidgetSignal::new(2));
        assert_eq!(frame.widget_signals().len(), 2);
        assert_eq!(frame.widget_signals()[0].widget_id, 1);
        assert_eq!(frame.widget_signals()[1].widget_id, 2);

        let taken = frame.take_widget_signals();
        assert_eq!(taken.len(), 2);
        assert!(frame.widget_signals().is_empty());
    }

    #[test]
    fn frame_clear_resets_signals_and_cursor() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 10, &mut pool);
        frame.set_cursor(Some((5, 5)));
        frame.register_widget_signal(WidgetSignal::new(1));
        assert!(frame.cursor_position.is_some());
        assert!(!frame.widget_signals().is_empty());

        frame.clear();
        assert!(frame.cursor_position.is_none());
        assert!(frame.widget_signals().is_empty());
    }

    // --- Frame degradation ---

    #[test]
    fn frame_set_degradation_propagates_to_buffer() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 10, &mut pool);
        assert_eq!(frame.degradation, DegradationLevel::Full);
        assert_eq!(frame.buffer.degradation, DegradationLevel::Full);

        frame.set_degradation(DegradationLevel::SimpleBorders);
        assert_eq!(frame.degradation, DegradationLevel::SimpleBorders);
        assert_eq!(frame.buffer.degradation, DegradationLevel::SimpleBorders);

        frame.set_degradation(DegradationLevel::EssentialOnly);
        assert_eq!(frame.degradation, DegradationLevel::EssentialOnly);
        assert_eq!(frame.buffer.degradation, DegradationLevel::EssentialOnly);
    }

    #[test]
    fn frame_should_render_widget() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 10, &mut pool);

        // Full: all widgets allowed
        assert!(frame.should_render_widget(true));
        assert!(frame.should_render_widget(false));

        // SimpleBorders & NoStyling: all widgets allowed
        frame.set_degradation(DegradationLevel::SimpleBorders);
        assert!(frame.should_render_widget(true));
        assert!(frame.should_render_widget(false));

        frame.set_degradation(DegradationLevel::NoStyling);
        assert!(frame.should_render_widget(true));
        assert!(frame.should_render_widget(false));

        // EssentialOnly: only essential
        frame.set_degradation(DegradationLevel::EssentialOnly);
        assert!(frame.should_render_widget(true));
        assert!(!frame.should_render_widget(false));

        // Skeleton: only essential
        frame.set_degradation(DegradationLevel::Skeleton);
        assert!(frame.should_render_widget(true));
        assert!(!frame.should_render_widget(false));

        // SkipFrame: none
        frame.set_degradation(DegradationLevel::SkipFrame);
        assert!(!frame.should_render_widget(true));
        assert!(!frame.should_render_widget(false));
    }

    // --- Frame hit grid with zero-size screen ---

    #[test]
    fn frame_with_hit_grid_zero_size_clamped_to_one() {
        let mut pool = GraphemePool::new();
        let frame = Frame::with_hit_grid(0, 0, &mut pool);
        assert_eq!(frame.buffer.width(), 1);
        assert_eq!(frame.buffer.height(), 1);
    }

    // --- Frame register_hit returns true/false correctly ---

    #[test]
    fn frame_register_hit_with_all_regions() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::with_hit_grid(20, 20, &mut pool);
        let regions = [
            HitRegion::Content,
            HitRegion::Border,
            HitRegion::Scrollbar,
            HitRegion::Handle,
            HitRegion::Button,
            HitRegion::Link,
            HitRegion::Custom(0),
            HitRegion::Custom(255),
        ];
        for (i, &region) in regions.iter().enumerate() {
            let y = i as u16;
            frame.register_hit(Rect::new(0, y, 1, 1), HitId::new(i as u32), region, 0);
        }
        for (i, &region) in regions.iter().enumerate() {
            let y = i as u16;
            assert_eq!(
                frame.hit_test(0, y),
                Some((HitId::new(i as u32), region, 0))
            );
        }
    }

    // --- Frame Draw trait ---

    #[test]
    fn frame_draw_horizontal_line() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 5, &mut pool);
        let cell = Cell::from_char('-');
        frame.draw_horizontal_line(2, 1, 5, cell);
        for x in 2..7 {
            assert_eq!(frame.buffer.get(x, 1).unwrap().content.as_char(), Some('-'));
        }
        // Neighbors untouched
        assert!(frame.buffer.get(1, 1).unwrap().is_empty());
        assert!(frame.buffer.get(7, 1).unwrap().is_empty());
    }

    #[test]
    fn frame_draw_vertical_line() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 10, &mut pool);
        let cell = Cell::from_char('|');
        frame.draw_vertical_line(3, 2, 4, cell);
        for y in 2..6 {
            assert_eq!(frame.buffer.get(3, y).unwrap().content.as_char(), Some('|'));
        }
        assert!(frame.buffer.get(3, 1).unwrap().is_empty());
        assert!(frame.buffer.get(3, 6).unwrap().is_empty());
    }

    #[test]
    fn frame_draw_rect_filled() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 10, &mut pool);
        let cell = Cell::from_char('#');
        frame.draw_rect_filled(Rect::new(1, 1, 3, 3), cell);
        for y in 1..4 {
            for x in 1..4 {
                assert_eq!(frame.buffer.get(x, y).unwrap().content.as_char(), Some('#'));
            }
        }
        // Outside
        assert!(frame.buffer.get(0, 0).unwrap().is_empty());
        assert!(frame.buffer.get(4, 4).unwrap().is_empty());
    }

    #[test]
    fn frame_paint_area() {
        use crate::cell::PackedRgba;
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(5, 5, &mut pool);
        let red = PackedRgba::rgb(255, 0, 0);
        frame.paint_area(Rect::new(0, 0, 2, 2), Some(red), None);
        let cell = frame.buffer.get(0, 0).unwrap();
        assert_eq!(cell.fg, red);
    }

    // --- Frame print_text_clipped ---

    #[test]
    fn frame_print_text_clipped_at_boundary() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(5, 1, &mut pool);
        // "Hello World" should be clipped at width 5
        let end = frame.print_text(0, 0, "Hello World", Cell::from_char(' '));
        assert_eq!(end, 5);
        for x in 0..5 {
            assert!(!frame.buffer.get(x, 0).unwrap().is_empty());
        }
    }

    #[test]
    fn frame_print_text_empty_string() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 1, &mut pool);
        let end = frame.print_text(0, 0, "", Cell::from_char(' '));
        assert_eq!(end, 0);
    }

    #[test]
    fn frame_print_text_at_right_edge() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(5, 1, &mut pool);
        // Start at x=4, only 1 cell fits
        let end = frame.print_text(4, 0, "AB", Cell::from_char(' '));
        assert_eq!(end, 5);
        assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some('A'));
    }

    // --- Frame Debug ---

    #[test]
    fn frame_debug() {
        let mut pool = GraphemePool::new();
        let frame = Frame::new(5, 3, &mut pool);
        let dbg = format!("{:?}", frame);
        assert!(dbg.contains("Frame"), "Debug: {dbg}");
    }

    // --- HitGrid Debug ---

    #[test]
    fn hit_grid_debug() {
        let grid = HitGrid::new(3, 3);
        let dbg = format!("{:?}", grid);
        assert!(dbg.contains("HitGrid"), "Debug: {dbg}");
    }

    // --- Frame cursor beyond bounds ---

    #[test]
    fn frame_cursor_beyond_bounds() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 10, &mut pool);
        // Setting cursor beyond frame is allowed (no clipping)
        frame.set_cursor(Some((100, 200)));
        assert_eq!(frame.cursor_position, Some((100, 200)));
    }

    // --- HitGrid large data values ---

    #[test]
    fn hit_grid_register_overwrite() {
        let mut grid = HitGrid::new(5, 5);
        grid.register(Rect::new(0, 0, 3, 3), HitId::new(1), HitRegion::Content, 10);
        grid.register(Rect::new(0, 0, 3, 3), HitId::new(2), HitRegion::Button, 20);
        // Second registration overwrites first
        assert_eq!(
            grid.hit_test(1, 1),
            Some((HitId::new(2), HitRegion::Button, 20))
        );
    }

    #[test]
    fn frame_hit_test_detailed_preserves_owner() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::with_hit_grid(4, 4, &mut pool);

        frame.with_hit_owner(77, |frame| {
            frame.register_hit(Rect::new(1, 1, 2, 2), HitId::new(5), HitRegion::Button, 9);
        });

        assert_eq!(
            frame.hit_test_detailed(1, 1),
            Some(HitTestResult::new(
                HitId::new(5),
                HitRegion::Button,
                9,
                Some(77),
            ))
        );
        assert_eq!(
            frame.hit_test(1, 1),
            Some((HitId::new(5), HitRegion::Button, 9))
        );
    }

    #[test]
    fn frame_hit_owner_scope_restores_previous_owner() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::with_hit_grid(4, 4, &mut pool);

        frame.with_hit_owner(10, |frame| {
            frame.register_hit(Rect::new(0, 0, 1, 1), HitId::new(1), HitRegion::Content, 1);
            frame.with_hit_owner(20, |frame| {
                frame.register_hit(Rect::new(1, 0, 1, 1), HitId::new(2), HitRegion::Content, 2);
            });
            frame.register_hit(Rect::new(2, 0, 1, 1), HitId::new(3), HitRegion::Content, 3);
        });

        assert_eq!(frame.hit_test_detailed(0, 0).unwrap().owner, Some(10));
        assert_eq!(frame.hit_test_detailed(1, 0).unwrap().owner, Some(20));
        assert_eq!(frame.hit_test_detailed(2, 0).unwrap().owner, Some(10));
    }

    #[test]
    fn frame_hit_owner_scope_restores_after_panic() {
        let mut pool = GraphemePool::new();
        let mut frame = Frame::with_hit_grid(4, 4, &mut pool);

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            frame.with_hit_owner(55, |_frame| panic!("boom"));
        }));
        assert!(result.is_err());

        frame.register_hit(Rect::new(0, 0, 1, 1), HitId::new(9), HitRegion::Content, 0);
        assert_eq!(frame.hit_test_detailed(0, 0).unwrap().owner, None);
    }
}