ftui-render 0.3.1

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
#![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_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()
        }
    }
}

/// 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(),
        }
    }
}

/// 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,

    /// 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>,

    /// 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>,
}

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),
            pool,
            links: None,
            hit_grid: None,
            hit_owner_stack: Vec::new(),
            widget_budget: WidgetBudget::default(),
            widget_signals: Vec::new(),
            cursor_position: None,
            cursor_visible: true,
            degradation: DegradationLevel::Full,
            arena: 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,
            pool,
            links: None,
            hit_grid: None,
            hit_owner_stack: Vec::new(),
            widget_budget: WidgetBudget::default(),
            widget_signals: Vec::new(),
            cursor_position: None,
            cursor_visible: true,
            degradation: DegradationLevel::Full,
            arena: 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),
            pool,
            links: Some(links),
            hit_grid: None,
            hit_owner_stack: Vec::new(),
            widget_budget: WidgetBudget::default(),
            widget_signals: Vec::new(),
            cursor_position: None,
            cursor_visible: true,
            degradation: DegradationLevel::Full,
            arena: None,
        }
    }

    /// 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 {
        Self {
            buffer: Buffer::new(width, height),
            pool,
            links: None,
            hit_grid: Some(HitGrid::new(width, height)),
            hit_owner_stack: Vec::new(),
            widget_budget: WidgetBudget::default(),
            widget_signals: Vec::new(),
            cursor_position: None,
            cursor_visible: true,
            degradation: DegradationLevel::Full,
            arena: None,
        }
    }

    /// 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<&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 under the current budget.
    #[inline]
    pub fn should_render_widget(&self, widget_id: u64, essential: bool) -> bool {
        self.widget_budget.allows(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)
    }

    /// 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();
    }

    /// 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;
    }

    /// Get the bounding rectangle of the frame.
    #[inline]
    pub fn bounds(&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),
        }
    }

    /// 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);
    }

    #[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(42, false));

        // Set restricted budget
        frame.set_widget_budget(WidgetBudget::allow_only(vec![1, 2]));
        assert!(frame.should_render_widget(1, false));
        assert!(!frame.should_render_widget(42, false));
        assert!(frame.should_render_widget(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);
    }

    // --- 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);
    }
}