euv-core 0.48.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
use super::*;

/// Blank default cell (`' '`, width `1`, default terminal attributes).
impl Default for TerminalCell {
    /// Creates a blank space terminal cell.
    ///
    /// # Returns
    ///
    /// - `Self` - Blank cell.
    fn default() -> Self {
        Self::blank()
    }
}

/// Construction, grapheme-cluster storage, and style inspection helpers for `TerminalCell`.
impl TerminalCell {
    /// Creates an empty single-column space cell with default attributes.
    ///
    /// # Returns
    ///
    /// - `Self` - Blank cell.
    #[must_use]
    pub const fn blank() -> Self {
        Self {
            ch: ' ',
            width: 1,
            fg: None,
            bg: None,
            bold: false,
            reverse: false,
            underline: false,
            tail_len: 0,
            tail_utf8: [0; TERMINAL_CELL_TAIL_CAPACITY],
        }
    }

    /// Creates a trailing continuation cell (`width == 0`) paired with a wide character lead cell.
    ///
    /// # Arguments
    ///
    /// - `Option<Color>` - Inherited foreground color.
    /// - `Option<Color>` - Inherited background color.
    /// - `bool` - Inherited bold flag.
    /// - `bool` - Inherited reverse-video flag.
    /// - `bool` - Inherited underline flag.
    ///
    /// # Returns
    ///
    /// - `Self` - Zero-width continuation cell.
    #[must_use]
    pub const fn continuation(
        fg: Option<Color>,
        bg: Option<Color>,
        bold: bool,
        reverse: bool,
        underline: bool,
    ) -> Self {
        Self {
            ch: '\0',
            width: 0,
            fg,
            bg,
            bold,
            reverse,
            underline,
            tail_len: 0,
            tail_utf8: [0; TERMINAL_CELL_TAIL_CAPACITY],
        }
    }

    /// Creates a styled single-scalar character cell with explicit display width and ANSI flags.
    ///
    /// # Arguments
    ///
    /// - `char` - Character scalar value.
    /// - `u8` - Display width (`1` or `2`).
    /// - `Option<Color>` - Optional foreground color.
    /// - `Option<Color>` - Optional background color.
    /// - `bool` - Bold flag.
    /// - `bool` - Reverse-video flag.
    /// - `bool` - Underline flag.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed styled cell.
    #[must_use]
    pub const fn styled(
        ch: char,
        width: u8,
        fg: Option<Color>,
        bg: Option<Color>,
        bold: bool,
        reverse: bool,
        underline: bool,
    ) -> Self {
        Self {
            ch,
            width,
            fg,
            bg,
            bold,
            reverse,
            underline,
            tail_len: 0,
            tail_utf8: [0; TERMINAL_CELL_TAIL_CAPACITY],
        }
    }

    /// Creates a styled cell from an Extended Grapheme Cluster (retaining combining marks, variation selectors, and ZWJ emoji inline without heap allocation).
    ///
    /// # Arguments
    ///
    /// - `&str` - Non-empty Extended Grapheme Cluster slice.
    /// - `u8` - Precomputed display width (`1` or `2`).
    /// - `Self` - Style template supplying colors and SGR emphasis flags.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed grapheme cell.
    #[must_use]
    pub fn from_grapheme(cluster: &str, width: u8, style: Self) -> Self {
        let mut iter: Chars<'_> = cluster.chars();
        let Some(first) = iter.next() else {
            return Self::blank();
        };
        let tail_str: &str = &cluster[first.len_utf8()..];
        let mut tail_utf8: [u8; TERMINAL_CELL_TAIL_CAPACITY] = [0; TERMINAL_CELL_TAIL_CAPACITY];
        let mut tail_len: usize = 0;
        for ch in tail_str.chars() {
            let mut enc: [u8; 4] = [0; 4];
            let encoded: &str = ch.encode_utf8(&mut enc);
            let bytes: &[u8] = encoded.as_bytes();
            if tail_len + bytes.len() > TERMINAL_CELL_TAIL_CAPACITY {
                break;
            }
            tail_utf8[tail_len..(tail_len + bytes.len())].copy_from_slice(bytes);
            tail_len += bytes.len();
        }
        Self {
            ch: first,
            width,
            fg: style.fg_color(),
            bg: style.bg_color(),
            bold: style.get_bold(),
            reverse: style.get_reverse(),
            underline: style.get_underline(),
            tail_len: tail_len as u8,
            tail_utf8,
        }
    }

    /// Returns the inline UTF-8 tail bytes for combining/ZWJ scalars attached to `ch`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Cell reference.
    ///
    /// # Returns
    ///
    /// - `&[u8]` - Valid UTF-8 tail byte slice (empty for single-scalar cells).
    #[must_use]
    pub fn tail_bytes(&self) -> &[u8] {
        let Self {
            tail_len,
            tail_utf8,
            ..
        } = self;
        let len: usize = (*tail_len as usize).min(TERMINAL_CELL_TAIL_CAPACITY);
        &tail_utf8[..len]
    }

    /// Appends the complete Extended Grapheme Cluster stored in this cell into `out`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Cell reference.
    /// - `&mut String` - Destination UTF-8 output buffer.
    pub fn push_grapheme_to(&self, out: &mut String) {
        let ch: char = self.get_ch();
        if ch == '\x1b' || ch == '\0' {
            return;
        }
        out.push(ch);
        let tail: &[u8] = self.tail_bytes();
        if !tail.is_empty()
            && let Ok(text) = from_utf8(tail)
        {
            out.push_str(text);
        }
    }

    /// Returns the optional 24-bit foreground color.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Cell reference.
    ///
    /// # Returns
    ///
    /// - `Option<Color>` - Foreground color when specified.
    #[must_use]
    pub const fn fg_color(&self) -> Option<Color> {
        let Self { fg, .. } = *self;
        fg
    }

    /// Returns the optional 24-bit background color.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Cell reference.
    ///
    /// # Returns
    ///
    /// - `Option<Color>` - Background color when specified.
    #[must_use]
    pub const fn bg_color(&self) -> Option<Color> {
        let Self { bg, .. } = *self;
        bg
    }

    /// Returns `true` when this cell is the trailing half of a wide character.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Cell reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` iff `width == 0`.
    #[must_use]
    pub const fn is_continuation(&self) -> bool {
        let Self { width, .. } = *self;
        width == 0
    }

    /// Returns `true` when this cell is the leading cell of a double-width character.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Cell reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` iff `width == 2`.
    #[must_use]
    pub const fn is_wide_lead(&self) -> bool {
        let Self { width, .. } = *self;
        width == 2
    }

    /// Returns `true` when two cells share identical SGR styling attributes.
    ///
    /// # Arguments
    ///
    /// - `&Self` - First cell reference.
    /// - `&Self` - Second cell reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when foreground, background, bold, reverse, and underline match.
    #[must_use]
    pub fn same_style(&self, other: &Self) -> bool {
        self.fg_color() == other.fg_color()
            && self.bg_color() == other.bg_color()
            && self.get_bold() == other.get_bold()
            && self.get_reverse() == other.get_reverse()
            && self.get_underline() == other.get_underline()
    }
}

/// Accessors for `TerminalFrameFingerprint`.
impl TerminalFrameFingerprint {
    /// Returns the focused scene node handle recorded in this fingerprint.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Fingerprint reference.
    ///
    /// # Returns
    ///
    /// - `Option<NodeId>` - Focused node identifier, if any.
    #[must_use]
    pub const fn focused_node(&self) -> Option<NodeId> {
        let Self { focused, .. } = *self;
        focused
    }
}

/// Accessors and constructors for `TerminalWriteResult`.
impl TerminalWriteResult {
    /// Returns the optional write error message when `status != CliWriteStatus::Written`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Write result reference.
    ///
    /// # Returns
    ///
    /// - `Option<&str>` - Error description if present.
    #[must_use]
    pub fn error_message(&self) -> Option<&str> {
        let Self { error_message, .. } = self;
        error_message.as_deref()
    }
}

/// Grid allocation, grapheme-aware wide-char-safe writing, row hashing, box drawing, and plain-text serialization for `TerminalCellGrid`.
impl TerminalCellGrid {
    /// Allocates a blank `cols x rows` terminal cell grid (clamped to at least `1 x 1`).
    ///
    /// # Arguments
    ///
    /// - `u16` - Column count.
    /// - `u16` - Row count.
    ///
    /// # Returns
    ///
    /// - `Self` - Blank grid with precomputed blank row hashes.
    #[must_use]
    pub fn allocate(cols: u16, rows: u16) -> Self {
        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
        let total: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
        let cells: Vec<TerminalCell> = vec![TerminalCell::blank(); total];
        let blank_hash: u64 = hash_terminal_row(&cells[..(clamped_cols as usize)]);
        Self {
            cols: clamped_cols,
            rows: clamped_rows,
            cells,
            row_hashes: vec![blank_hash; clamped_rows as usize],
            dirty_rows: vec![false; clamped_rows as usize],
            blank_row_hash: blank_hash,
        }
    }

    /// Resizes and clears the grid to `cols x rows`, reusing existing allocation capacity when dimensions match.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable grid.
    /// - `u16` - Target column count.
    /// - `u16` - Target row count.
    pub fn reset(&mut self, cols: u16, rows: u16) {
        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
        let total: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
        let rows_usize: usize = clamped_rows as usize;
        let cols_usize: usize = clamped_cols as usize;
        let same_shape: bool = self.get_cols() == clamped_cols
            && self.get_rows() == clamped_rows
            && self.get_cells().len() == total
            && self.get_row_hashes().len() == rows_usize
            && self.get_dirty_rows().len() == rows_usize;
        if same_shape {
            let blank_hash: u64 = self.get_blank_row_hash();
            let Self {
                cells,
                row_hashes,
                dirty_rows,
                ..
            } = self;
            for row in 0..rows_usize {
                if dirty_rows[row] {
                    let start: usize = row * cols_usize;
                    cells[start..(start + cols_usize)].fill(TerminalCell::blank());
                    row_hashes[row] = blank_hash;
                    dirty_rows[row] = false;
                }
            }
            return;
        }
        let cols_changed: bool = self.get_cols() != clamped_cols || self.get_cells().is_empty();
        self.set_cols(clamped_cols);
        self.set_rows(clamped_rows);
        let cells: &mut Vec<TerminalCell> = self.get_mut_cells();
        if cells.len() == total {
            cells.fill(TerminalCell::blank());
        } else {
            cells.clear();
            cells.resize(total, TerminalCell::blank());
        }
        let blank_hash: u64 = if cols_changed {
            let computed: u64 = hash_terminal_row(&self.get_cells()[..cols_usize]);
            self.set_blank_row_hash(computed);
            computed
        } else {
            self.get_blank_row_hash()
        };
        let row_hashes: &mut Vec<u64> = self.get_mut_row_hashes();
        if row_hashes.len() == rows_usize {
            row_hashes.fill(blank_hash);
        } else {
            row_hashes.clear();
            row_hashes.resize(rows_usize, blank_hash);
        }
        let dirty_rows: &mut Vec<bool> = self.get_mut_dirty_rows();
        if dirty_rows.len() == rows_usize {
            dirty_rows.fill(false);
        } else {
            dirty_rows.clear();
            dirty_rows.resize(rows_usize, false);
        }
    }

    /// Recomputes FNV-1a row hashes only for rows written during the current projection pass.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable grid.
    pub fn finalize_row_hashes(&mut self) {
        let cols: usize = self.get_cols() as usize;
        let rows: usize = self.get_rows() as usize;
        let Self {
            cells,
            row_hashes,
            dirty_rows,
            ..
        } = self;
        for row in 0..rows {
            if !dirty_rows.get(row).copied().unwrap_or(false) {
                continue;
            }
            let start: usize = row * cols;
            let end: usize = (start + cols).min(cells.len());
            if let Some(slot) = row_hashes.get_mut(row) {
                *slot = hash_terminal_row(&cells[start..end]);
            }
        }
    }

    /// Returns total number of character cells in the grid.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Grid reference.
    ///
    /// # Returns
    ///
    /// - `usize` - Total cell count (`cols * rows`).
    #[must_use]
    pub fn total_cells(&self) -> usize {
        self.get_cells().len()
    }

    /// Returns the flat vector index for `(col, row)` if within grid bounds.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Grid reference.
    /// - `u16` - Zero-based column coordinate.
    /// - `u16` - Zero-based row coordinate.
    ///
    /// # Returns
    ///
    /// - `Option<usize>` - Linear cell index if in bounds.
    #[must_use]
    fn cell_index(&self, col: u16, row: u16) -> Option<usize> {
        let cols: u16 = self.get_cols();
        let rows: u16 = self.get_rows();
        if col >= cols || row >= rows {
            return None;
        }
        Some((row as usize) * (cols as usize) + (col as usize))
    }

    /// Marks `row` as modified for incremental hash recomputation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable grid.
    /// - `u16` - Zero-based row coordinate.
    fn mark_row_dirty(&mut self, row: u16) {
        if let Some(flag) = self.get_mut_dirty_rows().get_mut(row as usize) {
            *flag = true;
        }
    }

    /// Reads the `TerminalCell` stored at `(col, row)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Grid reference.
    /// - `u16` - Zero-based column coordinate.
    /// - `u16` - Zero-based row coordinate.
    ///
    /// # Returns
    ///
    /// - `Option<TerminalCell>` - Cell copy if within bounds.
    #[must_use]
    pub fn cell(&self, col: u16, row: u16) -> Option<TerminalCell> {
        let idx: usize = self.cell_index(col, row)?;
        self.get_cells().get(idx).copied()
    }

    /// Clears both cells of any wide-character pair occupying `(col, row)` before overwriting that coordinate.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable grid.
    /// - `u16` - Zero-based column coordinate.
    /// - `u16` - Zero-based row coordinate.
    fn clear_wide_conflict(&mut self, col: u16, row: u16) {
        let Some(existing) = self.cell(col, row) else {
            return;
        };
        if existing.is_continuation() && col > 0 {
            if let Some(lead_idx) = self.cell_index(col - 1, row)
                && let Some(slot) = self.get_mut_cells().get_mut(lead_idx)
            {
                *slot = TerminalCell::blank();
            }
            if let Some(cur_idx) = self.cell_index(col, row)
                && let Some(slot) = self.get_mut_cells().get_mut(cur_idx)
            {
                *slot = TerminalCell::blank();
            }
            self.mark_row_dirty(row);
        } else if existing.is_wide_lead() {
            if let Some(trail_idx) = self.cell_index(col.saturating_add(1), row)
                && let Some(slot) = self.get_mut_cells().get_mut(trail_idx)
            {
                *slot = TerminalCell::blank();
            }
            if let Some(cur_idx) = self.cell_index(col, row)
                && let Some(slot) = self.get_mut_cells().get_mut(cur_idx)
            {
                *slot = TerminalCell::blank();
            }
            self.mark_row_dirty(row);
        }
    }

    /// Writes a single narrow or wide `TerminalCell` at `(col, row)`, cleanly clearing overwritten wide neighbors and clipping cleanly at the right edge.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable grid.
    /// - `u16` - Zero-based column coordinate.
    /// - `u16` - Zero-based row coordinate.
    /// - `TerminalCell` - Cell value to write.
    ///
    /// # Returns
    ///
    /// - `u16` - Number of columns consumed (`0`, `1`, or `2`).
    pub fn put_cell(&mut self, col: u16, row: u16, cell: TerminalCell) -> u16 {
        let cols: u16 = self.get_cols();
        let rows: u16 = self.get_rows();
        if col >= cols || row >= rows || cell.is_continuation() {
            return 0;
        }
        if cell.is_wide_lead() {
            if col.saturating_add(1) >= cols {
                self.clear_wide_conflict(col, row);
                if let Some(idx) = self.cell_index(col, row)
                    && let Some(slot) = self.get_mut_cells().get_mut(idx)
                {
                    *slot = TerminalCell::blank();
                }
                self.mark_row_dirty(row);
                return 0;
            }
            self.clear_wide_conflict(col, row);
            self.clear_wide_conflict(col + 1, row);
            if let Some(lead_idx) = self.cell_index(col, row)
                && let Some(slot) = self.get_mut_cells().get_mut(lead_idx)
            {
                *slot = cell;
            }
            if let Some(trail_idx) = self.cell_index(col + 1, row)
                && let Some(slot) = self.get_mut_cells().get_mut(trail_idx)
            {
                *slot = TerminalCell::continuation(
                    cell.fg_color(),
                    cell.bg_color(),
                    cell.get_bold(),
                    cell.get_reverse(),
                    cell.get_underline(),
                );
            }
            self.mark_row_dirty(row);
            return 2;
        }
        self.clear_wide_conflict(col, row);
        if let Some(idx) = self.cell_index(col, row)
            && let Some(slot) = self.get_mut_cells().get_mut(idx)
        {
            *slot = cell;
        }
        self.mark_row_dirty(row);
        1
    }

    /// Writes a printable ASCII slice directly into `row` starting at `col`, avoiding grapheme segmentation while preserving wide-character cleanup.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable grid.
    /// - `u16` - Starting zero-based column coordinate.
    /// - `u16` - Target zero-based row coordinate.
    /// - `&[u8]` - Printable ASCII byte slice (`0x20..=0x7E`, already truncated to fit row width).
    /// - `TerminalCell` - Style template supplying colors and SGR emphasis flags.
    ///
    /// # Returns
    ///
    /// - `u16` - Number of columns written.
    fn write_printable_ascii_run(
        &mut self,
        col: u16,
        row: u16,
        bytes: &[u8],
        style_cell: TerminalCell,
    ) -> u16 {
        let cols: usize = self.get_cols() as usize;
        let rows: usize = self.get_rows() as usize;
        let col_usize: usize = col as usize;
        let row_usize: usize = row as usize;
        if col_usize >= cols || row_usize >= rows || bytes.is_empty() {
            return 0;
        }
        let write_len: usize = bytes.len().min(cols - col_usize);
        let row_start: usize = row_usize * cols;
        let mut base: TerminalCell = TerminalCell::styled(
            ' ',
            1,
            style_cell.fg_color(),
            style_cell.bg_color(),
            style_cell.get_bold(),
            style_cell.get_reverse(),
            style_cell.get_underline(),
        );
        let Self {
            cells, dirty_rows, ..
        } = self;
        let row_slice: &mut [TerminalCell] = &mut cells[row_start..(row_start + cols)];
        for (offset, byte) in bytes[..write_len].iter().copied().enumerate() {
            let idx: usize = col_usize + offset;
            let existing_w: u8 = row_slice[idx].get_width();
            if existing_w == 0 && idx > 0 {
                row_slice[idx - 1] = TerminalCell::blank();
            } else if existing_w == 2 && idx + 1 < cols {
                row_slice[idx + 1] = TerminalCell::blank();
            }
            base.set_ch(byte as char);
            row_slice[idx] = base;
        }
        if let Some(flag) = dirty_rows.get_mut(row_usize) {
            *flag = true;
        }
        write_len as u16
    }

    /// Writes UTF-8 `text` onto `row` starting at `col` within `max_cols`, preserving Extended Grapheme Clusters (CJK wide glyphs, combining marks, ZWJ emoji) and clean right-edge truncation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable grid.
    /// - `u16` - Starting zero-based column coordinate.
    /// - `u16` - Target zero-based row coordinate.
    /// - `u16` - Maximum display columns allowed for this write.
    /// - `&str` - UTF-8 text slice to write.
    /// - `TerminalCell` - Style template supplying foreground, background, bold, reverse, and underline flags.
    ///
    /// # Returns
    ///
    /// - `u16` - Total display columns written.
    pub fn write_styled_text(
        &mut self,
        col: u16,
        row: u16,
        max_cols: u16,
        text: &str,
        style_cell: TerminalCell,
    ) -> u16 {
        let cols: u16 = self.get_cols();
        let rows: u16 = self.get_rows();
        if col >= cols || row >= rows || max_cols == 0 {
            return 0;
        }
        let limit: u16 = max_cols.min(cols.saturating_sub(col));
        let raw_bytes: &[u8] = text.as_bytes();
        let check_len: usize = raw_bytes.len().min(limit as usize);
        if text.is_ascii()
            && raw_bytes[..check_len]
                .iter()
                .all(|b: &u8| (0x20..=0x7E).contains(b))
        {
            return self.write_printable_ascii_run(col, row, &raw_bytes[..check_len], style_cell);
        }
        let mut used: u16 = 0;
        let mut rest: &str = text;
        while let Some((cluster, next_rest)) = next_grapheme_cluster(rest) {
            rest = next_rest;
            if cluster.starts_with('\n') || cluster.starts_with('\r') {
                break;
            }
            let width: u8 = grapheme_display_width(cluster);
            if width == 0 {
                continue;
            }
            let w_u16: u16 = width as u16;
            if used.saturating_add(w_u16) > limit {
                break;
            }
            let cell: TerminalCell = TerminalCell::from_grapheme(cluster, width, style_cell);
            let consumed: u16 = self.put_cell(col + used, row, cell);
            if consumed == 0 {
                break;
            }
            used = used.saturating_add(consumed);
        }
        used
    }

    /// Writes UTF-8 `text` onto `row` starting at `col` using default terminal style within `max_cols`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable grid.
    /// - `u16` - Starting zero-based column coordinate.
    /// - `u16` - Target zero-based row coordinate.
    /// - `u16` - Maximum display columns allowed.
    /// - `&str` - UTF-8 text slice to write.
    ///
    /// # Returns
    ///
    /// - `u16` - Total display columns written.
    pub fn write_text(&mut self, col: u16, row: u16, max_cols: u16, text: &str) -> u16 {
        self.write_styled_text(col, row, max_cols, text, TerminalCell::blank())
    }

    /// Draws a Unicode box-drawing border frame covering `[x, x + w) x [y, y + h)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable grid.
    /// - `u16` - Left column coordinate.
    /// - `u16` - Top row coordinate.
    /// - `u16` - Box width in columns.
    /// - `u16` - Box height in rows.
    /// - `TerminalCell` - Style template supplying foreground, background, bold, and reverse flags.
    pub fn draw_box(&mut self, x: u16, y: u16, w: u16, h: u16, style_cell: TerminalCell) {
        if w < 2 || h < 2 {
            return;
        }
        let right: u16 = x.saturating_add(w - 1);
        let bottom: u16 = y.saturating_add(h - 1);
        let fg: Option<Color> = style_cell.fg_color();
        let bg: Option<Color> = style_cell.bg_color();
        let bold: bool = style_cell.get_bold();
        let rev: bool = style_cell.get_reverse();
        let ul: bool = style_cell.get_underline();
        let _: u16 = self.put_cell(
            x,
            y,
            TerminalCell::styled(TERMINAL_BOX_TOP_LEFT, 1, fg, bg, bold, rev, ul),
        );
        let _: u16 = self.put_cell(
            right,
            y,
            TerminalCell::styled(TERMINAL_BOX_TOP_RIGHT, 1, fg, bg, bold, rev, ul),
        );
        let _: u16 = self.put_cell(
            x,
            bottom,
            TerminalCell::styled(TERMINAL_BOX_BOTTOM_LEFT, 1, fg, bg, bold, rev, ul),
        );
        let _: u16 = self.put_cell(
            right,
            bottom,
            TerminalCell::styled(TERMINAL_BOX_BOTTOM_RIGHT, 1, fg, bg, bold, rev, ul),
        );
        let horiz: TerminalCell =
            TerminalCell::styled(TERMINAL_BOX_HORIZONTAL, 1, fg, bg, bold, rev, ul);
        let mut cx: u16 = x + 1;
        while cx < right {
            let _: u16 = self.put_cell(cx, y, horiz);
            let _: u16 = self.put_cell(cx, bottom, horiz);
            cx += 1;
        }
        let vert: TerminalCell =
            TerminalCell::styled(TERMINAL_BOX_VERTICAL, 1, fg, bg, bold, rev, ul);
        let mut cy: u16 = y + 1;
        while cy < bottom {
            let _: u16 = self.put_cell(x, cy, vert);
            let _: u16 = self.put_cell(right, cy, vert);
            cy += 1;
        }
    }

    /// Serializes the grid into clean UTF-8 lines with full Extended Grapheme Clusters and zero ANSI escape sequences for piped CLI stdout.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Grid reference.
    ///
    /// # Returns
    ///
    /// - `String` - Plain-text UTF-8 representation trimmed of trailing whitespace per line and trailing blank lines.
    #[must_use]
    pub fn to_plain_text(&self) -> String {
        let cols: usize = self.get_cols() as usize;
        let rows: usize = self.get_rows() as usize;
        let cells: &[TerminalCell] = self.get_cells().as_slice();
        let mut lines: Vec<String> = Vec::with_capacity(rows);
        for row in 0..rows {
            let start: usize = row * cols;
            let end: usize = (start + cols).min(cells.len());
            let mut line: String = String::with_capacity(cols);
            for cell in &cells[start..end] {
                if cell.is_continuation() {
                    continue;
                }
                cell.push_grapheme_to(&mut line);
            }
            let trimmed_len: usize = line.trim_end().len();
            line.truncate(trimmed_len);
            lines.push(line);
        }
        while let Some(last) = lines.last() {
            if last.is_empty() {
                let _: Option<String> = lines.pop();
            } else {
                break;
            }
        }
        lines.join("\n")
    }
}

/// Session lifecycle entry and idempotent ANSI state restoration for `TerminalSessionGuard`.
impl TerminalSessionGuard {
    /// Builds the escape sequence required to enter the configured interactive terminal modes.
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether to enter the alternate screen buffer.
    /// - `bool` - Whether to hide the terminal cursor.
    /// - `bool` - Whether to enable raw bracketed input mode.
    ///
    /// # Returns
    ///
    /// - `String` - Concatenated ANSI enter sequence.
    #[must_use]
    pub fn build_enter_sequence(alt_screen: bool, cursor_hidden: bool, raw_mode: bool) -> String {
        let mut out: String = String::new();
        if alt_screen {
            out.push_str(ANSI_ENTER_ALT_SCREEN);
        }
        if cursor_hidden {
            out.push_str(ANSI_HIDE_CURSOR);
        }
        if raw_mode {
            out.push_str(ANSI_ENTER_RAW_MODES);
        }
        out
    }

    /// Builds the escape sequence required to cleanly restore terminal state upon exit or unwind.
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether alternate screen mode was entered.
    /// - `bool` - Whether cursor visibility was hidden.
    /// - `bool` - Whether raw input modes were enabled.
    ///
    /// # Returns
    ///
    /// - `String` - Concatenated ANSI restoration sequence.
    #[must_use]
    pub fn build_restore_sequence(alt_screen: bool, cursor_hidden: bool, raw_mode: bool) -> String {
        let mut out: String = String::from(ANSI_RESET_STYLE);
        if raw_mode {
            out.push_str(ANSI_LEAVE_RAW_MODES);
        }
        if cursor_hidden {
            out.push_str(ANSI_SHOW_CURSOR);
        }
        if alt_screen {
            out.push_str(ANSI_LEAVE_ALT_SCREEN);
        }
        out
    }

    /// Enters an interactive terminal session writing enter/restore sequences to an optional capture buffer.
    ///
    /// # Arguments
    ///
    /// - `bool` - Enter alternate screen buffer.
    /// - `bool` - Hide terminal cursor.
    /// - `bool` - Enable raw input tracking modes.
    /// - `Option<Rc<RefCell<String>>>` - Optional capture buffer for deterministic testing or virtual PTYs.
    ///
    /// # Returns
    ///
    /// - `Self` - Active RAII session guard.
    #[must_use]
    pub fn enter_captured(
        alt_screen: bool,
        cursor_hidden: bool,
        raw_mode: bool,
        sink: Option<Rc<RefCell<String>>>,
    ) -> Self {
        let enter_seq: String = Self::build_enter_sequence(alt_screen, cursor_hidden, raw_mode);
        if let Some(buf) = sink.as_ref()
            && let Ok(mut guard) = buf.try_borrow_mut()
        {
            guard.push_str(&enter_seq);
        }
        Self {
            alt_screen,
            cursor_hidden,
            raw_mode,
            restored: false,
            write_to_stdout: false,
            sink,
        }
    }

    /// Enters an interactive terminal session flushing enter and restore sequences directly to stdout on native targets.
    ///
    /// # Arguments
    ///
    /// - `bool` - Enter alternate screen buffer.
    /// - `bool` - Hide terminal cursor.
    /// - `bool` - Enable raw input tracking modes.
    ///
    /// # Returns
    ///
    /// - `Self` - Active RAII session guard bound to stdout.
    #[must_use]
    pub fn enter_stdout(alt_screen: bool, cursor_hidden: bool, raw_mode: bool) -> Self {
        let enter_seq: String = Self::build_enter_sequence(alt_screen, cursor_hidden, raw_mode);
        #[cfg(not(target_arch = "wasm32"))]
        {
            let mut stdout: io::Stdout = io::stdout();
            let _: io::Result<()> = stdout.write_all(enter_seq.as_bytes());
            let _: io::Result<()> = stdout.flush();
        }
        #[cfg(target_arch = "wasm32")]
        let _: &String = &enter_seq;
        Self {
            alt_screen,
            cursor_hidden,
            raw_mode,
            restored: false,
            write_to_stdout: true,
            sink: None,
        }
    }

    /// Restores terminal state immediately if not already restored and returns the emitted ANSI sequence.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable session guard.
    ///
    /// # Returns
    ///
    /// - `String` - Restoration escape sequence emitted (empty if already restored).
    pub fn restore_now(&mut self) -> String {
        if self.get_restored() {
            return String::new();
        }
        self.set_restored(true);
        let seq: String = Self::build_restore_sequence(
            self.get_alt_screen(),
            self.get_cursor_hidden(),
            self.get_raw_mode(),
        );
        let write_stdout: bool = self.get_write_to_stdout();
        let Self { sink, .. } = self;
        if let Some(buf) = sink.as_ref()
            && let Ok(mut guard) = buf.try_borrow_mut()
        {
            guard.push_str(&seq);
        }
        #[cfg(not(target_arch = "wasm32"))]
        if write_stdout {
            let mut stdout: io::Stdout = io::stdout();
            let _: io::Result<()> = stdout.write_all(seq.as_bytes());
            let _: io::Result<()> = stdout.flush();
        }
        #[cfg(target_arch = "wasm32")]
        let _: bool = write_stdout;
        seq
    }
}

/// Guaranteed RAII restoration of cursor, raw mode, and alternate screen on normal exit or panic unwind.
impl Drop for TerminalSessionGuard {
    /// Restores terminal modes automatically when the guard leaves scope.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable session guard being dropped.
    fn drop(&mut self) {
        let _: String = self.restore_now();
    }
}

/// Double-buffered semantic scene projection, zero-work idle short-circuit, virtualized scroll projection, and coalesced ANSI diff encoding for `TerminalRenderer`.
impl TerminalRenderer {
    /// Creates a fresh `TerminalRenderer` with empty diff history.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized terminal renderer.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns `true` when the persistent previous-frame back buffer has been allocated and holds a committed interactive frame.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Terminal renderer reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` iff a committed previous grid exists (always `false` in `StaticPlainText`-only runs).
    #[must_use]
    pub fn has_previous_frame(&self) -> bool {
        self.get_previous_valid() && !self.get_previous().get_cells().is_empty()
    }

    /// Returns the last committed frame fingerprint used for O(1) idle short-circuiting.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Terminal renderer reference.
    ///
    /// # Returns
    ///
    /// - `Option<TerminalFrameFingerprint>` - Cached frame fingerprint if valid.
    #[must_use]
    pub const fn last_fingerprint(&self) -> Option<TerminalFrameFingerprint> {
        let Self {
            last_fingerprint, ..
        } = *self;
        last_fingerprint
    }

    /// Marks the previous-frame back buffer invalid without deallocating its storage, forcing a clean full synchronization on the next interactive render.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable terminal renderer.
    pub fn invalidate(&mut self) {
        self.set_previous_valid(false);
        let Self {
            last_fingerprint, ..
        } = self;
        *last_fingerprint = None;
    }

    /// Computes an O(1) (plus O(#scroll_views)) frame fingerprint capturing scene revision, focus, caret blink, input caret offset, scroll offsets, viewport dimensions, and mode.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Terminal renderer reference.
    /// - `&SceneTree` - Retained UI scene tree.
    /// - `u16` - Clamped terminal column count.
    /// - `u16` - Clamped terminal row count.
    /// - `TerminalRenderMode` - Active render mode.
    ///
    /// # Returns
    ///
    /// - `TerminalFrameFingerprint` - Frame fingerprint for idle detection.
    #[must_use]
    fn compute_fingerprint(
        &self,
        tree: &SceneTree,
        cols: u16,
        rows: u16,
        mode: TerminalRenderMode,
    ) -> TerminalFrameFingerprint {
        let focused: Option<NodeId> = tree.get_focus().focused_node();
        let focused_caret_offset: usize = focused
            .and_then(|id: NodeId| tree.get_node(id))
            .map(|node: &SceneNode| match node.get_kind() {
                NodeKind::Input(inp) => inp.get_caret(),
                _ => 0,
            })
            .unwrap_or(0);
        let mut scroll_hash: u64 = TERMINAL_FNV_OFFSET_BASIS;
        for scroll_id in self.get_tracked_scroll_nodes().iter().copied() {
            if let Some(node) = tree.get_node(scroll_id) {
                let off: Point = node.get_layout_box().get_scroll_offset();
                scroll_hash = fnv1a_mix_u64(scroll_hash, off.get_x().to_bits() as u64);
                scroll_hash = fnv1a_mix_u64(scroll_hash, off.get_y().to_bits() as u64);
            }
        }
        TerminalFrameFingerprint {
            scene_revision: tree.get_revision(),
            focused,
            caret_visible: tree.get_caret_visible(),
            focused_caret_offset,
            scroll_hash,
            cols,
            rows,
            mode,
        }
    }

    /// Projects `tree` into a `cols x rows` character grid and returns either coalesced ANSI TUI diffs (committing via zero-clone double-buffer `swap`) or zero-ANSI static plain text.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable terminal renderer.
    /// - `&SceneTree` - Retained UI scene tree to project.
    /// - `u16` - Terminal viewport width in columns.
    /// - `u16` - Terminal viewport height in rows.
    /// - `TerminalRenderMode` - Interactive TUI diff mode or static plain-text CLI mode.
    ///
    /// # Returns
    ///
    /// - `(String, TerminalDiffStats)` - Rendered UTF-8 terminal payload and cell-diff telemetry.
    pub fn render_tree(
        &mut self,
        tree: &SceneTree,
        cols: u16,
        rows: u16,
        mode: TerminalRenderMode,
    ) -> (String, TerminalDiffStats) {
        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
        let total_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
        if mode == TerminalRenderMode::InteractiveTui {
            let fp: TerminalFrameFingerprint =
                self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
            if self.get_previous_valid() && self.last_fingerprint() == Some(fp) {
                self.set_last_projected_rows(0);
                let next_skipped: u64 = self.get_skipped_idle_frames().saturating_add(1);
                self.set_skipped_idle_frames(next_skipped);
                let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
                self.set_frames_rendered(next_frames);
                return (
                    String::new(),
                    TerminalDiffStats::new(total_cells, 0, 0, true, false),
                );
            }
        }
        let stats: TerminalDiffStats =
            self.project_and_encode_into_scratch(tree, clamped_cols, clamped_rows, mode);
        let output: String = self.get_ansi_scratch().clone();
        self.commit_after_write(tree, clamped_cols, clamped_rows, mode);
        (output, stats)
    }

    /// Projects `tree` into a `cols x rows` character grid and returns a zero-allocation borrowed view of the encoded ANSI or plain-text payload.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable terminal renderer.
    /// - `&SceneTree` - Retained UI scene tree to project.
    /// - `u16` - Terminal viewport width in columns.
    /// - `u16` - Terminal viewport height in rows.
    /// - `TerminalRenderMode` - Interactive TUI diff mode or static plain-text CLI mode.
    ///
    /// # Returns
    ///
    /// - `(&str, TerminalDiffStats)` - Borrowed UTF-8 terminal payload and cell-diff telemetry.
    pub fn render_tree_borrowed(
        &mut self,
        tree: &SceneTree,
        cols: u16,
        rows: u16,
        mode: TerminalRenderMode,
    ) -> (&str, TerminalDiffStats) {
        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
        let total_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
        if mode == TerminalRenderMode::InteractiveTui {
            let fp: TerminalFrameFingerprint =
                self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
            if self.get_previous_valid() && self.last_fingerprint() == Some(fp) {
                self.set_last_projected_rows(0);
                let next_skipped: u64 = self.get_skipped_idle_frames().saturating_add(1);
                self.set_skipped_idle_frames(next_skipped);
                let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
                self.set_frames_rendered(next_frames);
                self.get_mut_ansi_scratch().clear();
                return (
                    self.get_ansi_scratch().as_str(),
                    TerminalDiffStats::new(total_cells, 0, 0, true, false),
                );
            }
        }
        let stats: TerminalDiffStats =
            self.project_and_encode_into_scratch(tree, clamped_cols, clamped_rows, mode);
        self.commit_after_write(tree, clamped_cols, clamped_rows, mode);
        (self.get_ansi_scratch().as_str(), stats)
    }

    /// Projects `tree`, encodes the batched output into an internal scratch buffer, flushes it in one write call to `writer`, and swaps double-buffer ownership ONLY when writing succeeds.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable terminal renderer.
    /// - `&SceneTree` - Retained UI scene tree to project.
    /// - `u16` - Terminal viewport width in columns.
    /// - `u16` - Terminal viewport height in rows.
    /// - `TerminalRenderMode` - Interactive TUI diff mode or static plain-text CLI mode.
    /// - `&mut W` - Output writer receiving the single batched write.
    ///
    /// # Returns
    ///
    /// - `TerminalWriteResult` - Write status, diff stats, and whether double-buffer ownership was swapped.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn render_tree_to_writer<W>(
        &mut self,
        tree: &SceneTree,
        cols: u16,
        rows: u16,
        mode: TerminalRenderMode,
        writer: &mut W,
    ) -> TerminalWriteResult
    where
        W: Write,
    {
        let clamped_cols: u16 = cols.max(TERMINAL_MIN_COLS);
        let clamped_rows: u16 = rows.max(TERMINAL_MIN_ROWS);
        let total_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
        if mode == TerminalRenderMode::InteractiveTui {
            let fp: TerminalFrameFingerprint =
                self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
            if self.get_previous_valid() && self.last_fingerprint() == Some(fp) {
                self.set_last_projected_rows(0);
                let next_skipped: u64 = self.get_skipped_idle_frames().saturating_add(1);
                self.set_skipped_idle_frames(next_skipped);
                let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
                self.set_frames_rendered(next_frames);
                let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
                    mode,
                    gpu_routing_opted_out: true,
                    uses_screen_hz: false,
                    input_to_output_ms: None,
                    flush_latency_ms: 0.0,
                    bytes_written: 0,
                    total_bytes_written: self.get_total_bytes_written(),
                    changed_cells: 0,
                    unchanged_frame_skipped: true,
                    backpressure_events: self.get_backpressure_events(),
                    batched_flush_count: self.get_batched_flush_count(),
                };
                self.set_last_telemetry(telemetry);
                return TerminalWriteResult {
                    status: CliWriteStatus::Written,
                    stats: TerminalDiffStats::new(total_cells, 0, 0, true, false),
                    swapped: false,
                    error_message: None,
                    telemetry,
                };
            }
        }
        let stats: TerminalDiffStats =
            self.project_and_encode_into_scratch(tree, clamped_cols, clamped_rows, mode);
        let payload_bytes: &[u8] = self.get_ansi_scratch().as_bytes();
        let mut bytes_written: u64 = 0;
        let mut flush_latency_ms: f64 = 0.0;
        let mut bp_delta: u64 = 0;
        let mut flushed_batch: bool = false;
        if !payload_bytes.is_empty() {
            let flush_start: Instant = Instant::now();
            match write_all_with_backpressure(writer, payload_bytes) {
                Ok((written, bp_events)) => {
                    flush_latency_ms = flush_start.elapsed().as_secs_f64() * 1000.0;
                    bytes_written = written;
                    bp_delta = bp_events;
                    flushed_batch = true;
                }
                Err((err, written, bp_events)) => {
                    flush_latency_ms = flush_start.elapsed().as_secs_f64() * 1000.0;
                    let status: CliWriteStatus = classify_io_error(&err);
                    let next_total: u64 = self.get_total_bytes_written().saturating_add(written);
                    let next_bp: u64 = self
                        .get_backpressure_events()
                        .saturating_add(bp_events)
                        .saturating_add(1);
                    self.set_total_bytes_written(next_total);
                    self.set_backpressure_events(next_bp);
                    let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
                        mode,
                        gpu_routing_opted_out: true,
                        uses_screen_hz: false,
                        input_to_output_ms: self.take_input_to_output_ms(),
                        flush_latency_ms,
                        bytes_written: written,
                        total_bytes_written: next_total,
                        changed_cells: stats.get_changed_cells(),
                        unchanged_frame_skipped: false,
                        backpressure_events: next_bp,
                        batched_flush_count: self.get_batched_flush_count(),
                    };
                    self.set_last_telemetry(telemetry);
                    self.invalidate();
                    return TerminalWriteResult {
                        status,
                        stats,
                        swapped: false,
                        error_message: Some(err.to_string()),
                        telemetry,
                    };
                }
            }
        }
        let next_total: u64 = self.get_total_bytes_written().saturating_add(bytes_written);
        let next_bp: u64 = self.get_backpressure_events().saturating_add(bp_delta);
        let next_batches: u64 = self
            .get_batched_flush_count()
            .saturating_add(u64::from(flushed_batch));
        self.set_total_bytes_written(next_total);
        self.set_backpressure_events(next_bp);
        self.set_batched_flush_count(next_batches);
        let input_to_output_ms: Option<f64> = self.take_input_to_output_ms();
        let telemetry: TerminalNonGpuTelemetry = TerminalNonGpuTelemetry {
            mode,
            gpu_routing_opted_out: true,
            uses_screen_hz: false,
            input_to_output_ms,
            flush_latency_ms,
            bytes_written,
            total_bytes_written: next_total,
            changed_cells: stats.get_changed_cells(),
            unchanged_frame_skipped: stats.get_is_idle(),
            backpressure_events: next_bp,
            batched_flush_count: next_batches,
        };
        self.set_last_telemetry(telemetry);
        let swapped: bool = self.commit_after_write(tree, clamped_cols, clamped_rows, mode);
        TerminalWriteResult {
            status: CliWriteStatus::Written,
            stats,
            swapped,
            error_message: None,
            telemetry,
        }
    }

    /// Projects `tree` into `current` and encodes the payload into `ansi_scratch` without mutating `previous`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable terminal renderer.
    /// - `&SceneTree` - Retained UI scene tree.
    /// - `u16` - Clamped terminal columns.
    /// - `u16` - Clamped terminal rows.
    /// - `TerminalRenderMode` - Active render mode.
    ///
    /// # Returns
    ///
    /// - `TerminalDiffStats` - Per-frame cell diff telemetry.
    fn project_and_encode_into_scratch(
        &mut self,
        tree: &SceneTree,
        clamped_cols: u16,
        clamped_rows: u16,
        mode: TerminalRenderMode,
    ) -> TerminalDiffStats {
        self.get_mut_current().reset(clamped_cols, clamped_rows);
        self.get_mut_tracked_scroll_nodes().clear();
        let focused: Option<NodeId> = tree.get_focus().focused_node();
        let mut cursor_y: u16 = 0;
        let root_region: TerminalRegion =
            TerminalRegion::new(0, clamped_cols, clamped_rows, focused);
        self.project_node(tree, tree.get_root(), root_region, &mut cursor_y);
        self.set_last_projected_rows(cursor_y as usize);
        self.get_mut_current().finalize_row_hashes();
        let total_cells: usize = self.get_current().total_cells();
        self.get_mut_ansi_scratch().clear();
        match mode {
            TerminalRenderMode::StaticPlainText => {
                let plain: String = self.get_current().to_plain_text();
                let bytes: usize = plain.len();
                self.get_mut_ansi_scratch().push_str(&plain);
                TerminalDiffStats::new(total_cells, total_cells, bytes, false, true)
            }
            TerminalRenderMode::InteractiveTui => {
                let resized_or_first: bool = !self.get_previous_valid()
                    || self.get_last_cols() != clamped_cols
                    || self.get_last_rows() != clamped_rows
                    || self.get_previous().total_cells() != total_cells;
                if resized_or_first {
                    self.encode_full_frame_into_scratch();
                    let bytes: usize = self.get_ansi_scratch().len();
                    TerminalDiffStats::new(total_cells, total_cells, bytes, false, true)
                } else {
                    self.encode_diff_frame_into_scratch()
                }
            }
        }
    }

    /// Commits double-buffer ownership via zero-clone `swap` after a confirmed interactive write (leaving `previous` untouched in `StaticPlainText` mode).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable terminal renderer.
    /// - `&SceneTree` - Rendered scene tree.
    /// - `u16` - Clamped terminal columns.
    /// - `u16` - Clamped terminal rows.
    /// - `TerminalRenderMode` - Active render mode.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `current` and `previous` were swapped.
    fn commit_after_write(
        &mut self,
        tree: &SceneTree,
        clamped_cols: u16,
        clamped_rows: u16,
        mode: TerminalRenderMode,
    ) -> bool {
        self.set_last_cols(clamped_cols);
        self.set_last_rows(clamped_rows);
        let next_frames: u64 = self.get_frames_rendered().wrapping_add(1);
        self.set_frames_rendered(next_frames);
        if mode == TerminalRenderMode::StaticPlainText {
            self.set_previous_valid(false);
            let Self {
                last_fingerprint, ..
            } = self;
            *last_fingerprint = None;
            return false;
        }
        let fp: TerminalFrameFingerprint =
            self.compute_fingerprint(tree, clamped_cols, clamped_rows, mode);
        let Self {
            previous,
            current,
            previous_valid,
            last_fingerprint,
            ..
        } = self;
        swap(current, previous);
        let target_cells: usize = (clamped_cols as usize).saturating_mul(clamped_rows as usize);
        if current.total_cells() != target_cells {
            current.reset(clamped_cols, clamped_rows);
        }
        *previous_valid = true;
        *last_fingerprint = Some(fp);
        true
    }

    /// Processes a terminal keyboard event (`Tab`, `Shift+Tab`, arrows, `Enter`, `Escape`, `Ctrl+C`) against `tree`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable terminal renderer.
    /// - `&mut SceneTree` - Retained UI scene tree to update focus, scroll, or activation on.
    /// - `KeyEvent` - Normalized keyboard event.
    ///
    /// # Returns
    ///
    /// - `TerminalNavAction` - Resulting focus, scroll, activation, or exit action.
    pub fn handle_key(&mut self, tree: &mut SceneTree, key: KeyEvent) -> TerminalNavAction {
        let code: KeyCode = key.get_code();
        let mods: Modifiers = key.get_modifiers();
        if code == KeyCode::Escape
            || (mods.get_ctrl()
                && matches!(code, KeyCode::Character('c') | KeyCode::Character('C')))
        {
            self.set_exit_requested(true);
            return TerminalNavAction::ExitRequested;
        }
        if code == KeyCode::Tab {
            let focusables: Vec<NodeId> = Self::collect_focusables(tree);
            if focusables.is_empty() {
                return TerminalNavAction::Ignored;
            }
            let current: Option<NodeId> = tree.get_focus().focused_node();
            let next_target: NodeId = match current
                .and_then(|cur: NodeId| focusables.iter().position(|id: &NodeId| *id == cur))
            {
                Some(idx) => {
                    let next_idx: usize = if mods.get_shift() {
                        if idx == 0 {
                            focusables.len() - 1
                        } else {
                            idx - 1
                        }
                    } else {
                        (idx + 1) % focusables.len()
                    };
                    focusables[next_idx]
                }
                None => {
                    if mods.get_shift() {
                        focusables[focusables.len() - 1]
                    } else {
                        focusables[0]
                    }
                }
            };
            let callbacks: Vec<(UiEventHandler, UiEvent)> = tree.update_focus(Some(next_target));
            for (handler, ev) in callbacks.into_iter() {
                if let Ok(mut cb) = handler.try_borrow_mut() {
                    cb(&ev);
                }
            }
            return TerminalNavAction::FocusMoved(next_target);
        }
        if code == KeyCode::ArrowDown || code == KeyCode::ArrowUp {
            let delta_rows: i16 = if code == KeyCode::ArrowDown { 1 } else { -1 };
            if let Some(scroll_id) = Self::find_first_scroll_view(tree) {
                let current_y: f32 = tree
                    .get_node(scroll_id)
                    .map(|n: &SceneNode| n.get_layout_box().get_scroll_offset().get_y())
                    .unwrap_or(0.0);
                let next_y: f32 =
                    (current_y + (delta_rows as f32) * TERMINAL_SCROLL_STEP_PX).max(0.0);
                tree.set_scroll_offset(scroll_id, Point::new(0.0, next_y));
                return TerminalNavAction::Scrolled(delta_rows);
            }
            return TerminalNavAction::Ignored;
        }
        if code == KeyCode::Enter {
            if let Some(target) = tree.get_focus().focused_node() {
                let click_kind: UiEventKind = UiEventKind::Click(Point::default());
                let handler_opt: Option<UiEventHandler> = tree
                    .get_node(target)
                    .and_then(|node: &SceneNode| node.get_handlers().handler_for(&click_kind));
                if let Some(handler) = handler_opt
                    && let Ok(mut cb) = handler.try_borrow_mut()
                {
                    let click_ev: UiEvent = UiEvent::new(target, click_kind);
                    cb(&click_ev);
                }
                return TerminalNavAction::Activated(target);
            }
            return TerminalNavAction::Ignored;
        }
        TerminalNavAction::Ignored
    }

    /// Collects all visible focusable or clickable node handles in pre-order traversal.
    ///
    /// # Arguments
    ///
    /// - `&SceneTree` - Retained UI scene tree.
    ///
    /// # Returns
    ///
    /// - `Vec<NodeId>` - Ordered focus ring candidates.
    #[must_use]
    fn collect_focusables(tree: &SceneTree) -> Vec<NodeId> {
        let mut out: Vec<NodeId> = Vec::new();
        let mut stack: Vec<NodeId> = vec![tree.get_root()];
        while let Some(id) = stack.pop() {
            let Some(node) = tree.get_node(id) else {
                continue;
            };
            if node.style_ref().get_layout().get_display() == Display::None
                || node.style_ref().get_paint().get_opacity() <= 0.0
            {
                continue;
            }
            if Self::is_focusable_or_interactive(node) {
                out.push(id);
            }
            for child in tree.children_iter(id).rev() {
                stack.push(child);
            }
        }
        out
    }

    /// Finds the first visible `NodeKind::ScrollView` node in pre-order traversal.
    ///
    /// # Arguments
    ///
    /// - `&SceneTree` - Retained UI scene tree.
    ///
    /// # Returns
    ///
    /// - `Option<NodeId>` - First visible scroll container handle.
    #[must_use]
    fn find_first_scroll_view(tree: &SceneTree) -> Option<NodeId> {
        let mut stack: Vec<NodeId> = vec![tree.get_root()];
        while let Some(id) = stack.pop() {
            let Some(node) = tree.get_node(id) else {
                continue;
            };
            if node.style_ref().get_layout().get_display() == Display::None {
                continue;
            }
            if matches!(node.get_kind(), NodeKind::ScrollView) {
                return Some(id);
            }
            for child in tree.children_iter(id).rev() {
                stack.push(child);
            }
        }
        None
    }

    /// Returns `true` when `node` should participate in terminal focus and clickable affordances.
    ///
    /// # Arguments
    ///
    /// - `&SceneNode` - Candidate scene node.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether the node is focusable or interactive.
    #[must_use]
    fn is_focusable_or_interactive(node: &SceneNode) -> bool {
        node.get_interaction().get_focusable()
            || matches!(node.get_kind(), NodeKind::Input(_))
            || Self::is_clickable_node(node)
    }

    /// Returns `true` when `node` acts as a clickable button or interactive trigger.
    ///
    /// # Arguments
    ///
    /// - `&SceneNode` - Candidate scene node.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether the node has click semantics.
    #[must_use]
    fn is_clickable_node(node: &SceneNode) -> bool {
        node.get_handlers()
            .handler_for(&UiEventKind::Click(Point::default()))
            .is_some()
            || node.style_ref().get_paint().get_cursor() == CursorIcon::Pointer
            || node
                .a11y_props()
                .is_some_and(|a: A11yProps| a.get_role() == A11yRole::Button)
    }

    /// Returns `true` when a child node is visible for terminal projection.
    ///
    /// # Arguments
    ///
    /// - `&SceneTree` - Retained UI scene tree.
    /// - `NodeId` - Candidate node handle.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` iff node exists, `display != None`, and `opacity > 0.0`.
    #[must_use]
    fn is_node_visible(tree: &SceneTree, node_id: NodeId) -> bool {
        tree.get_node(node_id).is_some_and(|c: &SceneNode| {
            c.style_ref().get_layout().get_display() != Display::None
                && c.style_ref().get_paint().get_opacity() > 0.0
        })
    }

    /// Collects direct/descendant display label text for a clickable container button.
    ///
    /// # Arguments
    ///
    /// - `&SceneTree` - Retained UI scene tree.
    /// - `NodeId` - Button container node identifier.
    ///
    /// # Returns
    ///
    /// - `String` - Resolved button caption text.
    #[must_use]
    fn collect_button_label(tree: &SceneTree, node_id: NodeId) -> String {
        let Some(node) = tree.get_node(node_id) else {
            return String::new();
        };
        let mut parts: Vec<String> = Vec::new();
        let mut stack: Vec<NodeId> = tree.children_iter(node_id).rev().collect();
        while let Some(cid) = stack.pop() {
            let Some(child) = tree.get_node(cid) else {
                continue;
            };
            if child.style_ref().get_layout().get_display() == Display::None {
                continue;
            }
            if let NodeKind::Text(text) = child.get_kind() {
                let trimmed: &str = text.trim();
                if !trimmed.is_empty() {
                    parts.push(trimmed.to_string());
                }
            }
            for grand in tree.children_iter(cid).rev() {
                stack.push(grand);
            }
        }
        if !parts.is_empty() {
            return parts.join(" ");
        }
        node.a11y_props()
            .map(|a: A11yProps| a.get_label().clone())
            .unwrap_or_default()
    }

    /// Projects a single scene node subtree into the current `TerminalCellGrid` using terminal character coordinates directly.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable terminal renderer.
    /// - `&SceneTree` - Retained scene tree.
    /// - `NodeId` - Target node handle to project.
    /// - `TerminalRegion` - Active character-grid region and focus context.
    /// - `&mut u16` - Mutable current row cursor advanced as content is laid out.
    fn project_node(
        &mut self,
        tree: &SceneTree,
        node_id: NodeId,
        region: TerminalRegion,
        y: &mut u16,
    ) {
        let x: u16 = region.get_x();
        let avail_w: u16 = region.get_width();
        let max_y: u16 = region.get_max_y();
        let focused: Option<NodeId> = region.get_focused();
        if *y >= max_y || avail_w == 0 {
            return;
        }
        let Some(node) = tree.get_node(node_id) else {
            return;
        };
        let style: &Style = node.style_ref();
        let layout: LayoutStyle = style.get_layout();
        let paint: PaintStyle = style.get_paint();
        let text_style: TextStyle = style.get_text();
        if layout.get_display() == Display::None || paint.get_opacity() <= 0.0 {
            return;
        }
        let is_focused: bool = focused == Some(node_id) || node.get_interaction().get_focused();
        let is_bold: bool = matches!(
            text_style.get_weight(),
            FontWeight::SemiBold | FontWeight::Bold
        );
        let fg: Option<Color> = Some(text_style.get_color());
        let bg: Option<Color> = paint.background_color();
        let template: TerminalCell = TerminalCell::styled(
            ' ',
            1,
            fg,
            bg,
            is_bold,
            is_focused,
            text_style.get_underline(),
        );
        match node.get_kind() {
            NodeKind::Text(content) => {
                if Self::is_clickable_node(node) {
                    let display_str: String = if is_focused {
                        format!("> [ {content} ]")
                    } else {
                        format!("[ {content} ]")
                    };
                    self.write_wrapped_text(region, y, &display_str, template);
                } else {
                    self.write_wrapped_text(region, y, content.as_str(), template);
                }
            }
            NodeKind::Input(inp) => {
                let inner: String = if inp.get_value().is_empty() {
                    inp.get_placeholder().clone()
                } else if inp.get_password() {
                    let count: usize = inp.get_value().chars().count();
                    "*".repeat(count)
                } else {
                    inp.get_value().clone()
                };
                let formatted: String = if is_focused {
                    if tree.get_caret_visible() {
                        format!("> [ {inner}| ]")
                    } else {
                        format!("> [ {inner}  ]")
                    }
                } else {
                    format!("[ {inner} ]")
                };
                let _: u16 = self
                    .get_mut_current()
                    .write_styled_text(x, *y, avail_w, &formatted, template);
                *y = y.saturating_add(1);
            }
            NodeKind::Image(img) => {
                let alt: String = node
                    .a11y_props()
                    .map(|a: A11yProps| a.get_label().clone())
                    .filter(|s: &String| !s.is_empty())
                    .map(|lbl: String| format!("{TERMINAL_IMAGE_FALLBACK_PREFIX}{lbl}]"))
                    .unwrap_or_else(|| {
                        format!(
                            "{TERMINAL_IMAGE_DIM_PREFIX}{}x{}]",
                            img.get_width(),
                            img.get_height()
                        )
                    });
                let _: u16 = self
                    .get_mut_current()
                    .write_styled_text(x, *y, avail_w, &alt, template);
                *y = y.saturating_add(1);
            }
            NodeKind::Canvas(_) => {
                let alt: String = node
                    .a11y_props()
                    .map(|a: A11yProps| a.get_label().clone())
                    .filter(|s: &String| !s.is_empty())
                    .map(|lbl: String| format!("{TERMINAL_CANVAS_FALLBACK_PREFIX}{lbl}]"))
                    .unwrap_or_else(|| TERMINAL_CANVAS_FALLBACK.to_string());
                let _: u16 = self
                    .get_mut_current()
                    .write_styled_text(x, *y, avail_w, &alt, template);
                *y = y.saturating_add(1);
            }
            NodeKind::Fragment => {
                for child_id in tree.children_iter(node_id) {
                    if *y >= max_y {
                        break;
                    }
                    self.project_node(tree, child_id, region, y);
                }
            }
            NodeKind::ScrollView => {
                self.project_scroll_view(tree, node_id, region, y);
            }
            NodeKind::View | NodeKind::Portal => {
                let is_root: bool = node_id == tree.get_root();
                if !is_root && Self::is_clickable_node(node) {
                    let caption: String = Self::collect_button_label(tree, node_id);
                    if !caption.is_empty() {
                        let formatted: String = if is_focused {
                            format!("> [ {caption} ]")
                        } else {
                            format!("[ {caption} ]")
                        };
                        let _: u16 = self
                            .get_mut_current()
                            .write_styled_text(x, *y, avail_w, &formatted, template);
                        *y = y.saturating_add(1);
                        return;
                    }
                }
                let has_border: bool = !is_root
                    && (paint.get_border().get_width() > 0.0
                        || matches!(node.get_kind(), NodeKind::Portal))
                    && avail_w >= 4
                    && max_y.saturating_sub(*y) >= 3;
                if has_border {
                    let top_y: u16 = *y;
                    let inner_region: TerminalRegion = TerminalRegion::new(
                        x.saturating_add(1),
                        avail_w.saturating_sub(2),
                        max_y.saturating_sub(1),
                        focused,
                    );
                    let mut child_y: u16 = top_y.saturating_add(1);
                    self.project_children_flow(tree, node_id, node, inner_region, &mut child_y);
                    let box_h: u16 = child_y
                        .saturating_sub(top_y)
                        .saturating_add(1)
                        .max(3)
                        .min(max_y.saturating_sub(top_y));
                    let border_cell: TerminalCell = TerminalCell::styled(
                        ' ',
                        1,
                        Some(paint.get_border().get_color()),
                        bg,
                        false,
                        is_focused,
                        false,
                    );
                    self.get_mut_current()
                        .draw_box(x, top_y, avail_w, box_h, border_cell);
                    *y = top_y.saturating_add(box_h);
                } else {
                    self.project_children_flow(tree, node_id, node, region, y);
                }
            }
        }
    }

    /// Projects children of a container respecting row, column, and grid directions directly in character columns.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable terminal renderer.
    /// - `&SceneTree` - Retained scene tree.
    /// - `NodeId` - Container scene node handle.
    /// - `&SceneNode` - Container scene node.
    /// - `TerminalRegion` - Active character-grid region and focus context.
    /// - `&mut u16` - Mutable current row cursor.
    fn project_children_flow(
        &mut self,
        tree: &SceneTree,
        node_id: NodeId,
        node: &SceneNode,
        region: TerminalRegion,
        y: &mut u16,
    ) {
        let x: u16 = region.get_x();
        let avail_w: u16 = region.get_width();
        let max_y: u16 = region.get_max_y();
        let focused: Option<NodeId> = region.get_focused();
        let layout: LayoutStyle = node.style_ref().get_layout();
        let is_row: bool = matches!(
            layout.get_flex_direction(),
            FlexDirection::Row | FlexDirection::RowReverse
        ) && layout.get_display() == Display::Flex;
        if is_row {
            let visible_count: usize = tree
                .children_iter(node_id)
                .filter(|cid: &NodeId| Self::is_node_visible(tree, *cid))
                .count();
            if visible_count > 1 && avail_w >= (visible_count as u16).saturating_mul(2) {
                let count: u16 = visible_count as u16;
                let total_gaps: u16 = count.saturating_sub(1).saturating_mul(TERMINAL_ROW_GAP);
                let slot_w: u16 = avail_w.saturating_sub(total_gaps) / count;
                if slot_w >= 2 {
                    let row_start_y: u16 = *y;
                    let mut max_child_end: u16 = row_start_y;
                    let mut visible_idx: usize = 0;
                    for child_id in tree.children_iter(node_id) {
                        if !Self::is_node_visible(tree, child_id) {
                            continue;
                        }
                        let cx: u16 =
                            x.saturating_add((visible_idx as u16).saturating_mul(slot_w + 1));
                        let rem_w: u16 = avail_w.saturating_sub(cx.saturating_sub(x));
                        let col_w: u16 = if visible_idx + 1 == visible_count {
                            rem_w
                        } else {
                            slot_w.min(rem_w)
                        };
                        let mut cy: u16 = row_start_y;
                        let child_region: TerminalRegion =
                            TerminalRegion::new(cx, col_w, max_y, focused);
                        self.project_node(tree, child_id, child_region, &mut cy);
                        if cy > max_child_end {
                            max_child_end = cy;
                        }
                        visible_idx += 1;
                    }
                    *y = max_child_end;
                    return;
                }
            }
        }
        for child_id in tree.children_iter(node_id) {
            if *y >= max_y {
                break;
            }
            if Self::is_node_visible(tree, child_id) {
                self.project_node(tree, child_id, region, y);
            }
        }
    }

    /// Projects a `NodeKind::ScrollView` container with zero-allocation visible-range virtualization and a Unicode scrollbar rail.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable terminal renderer.
    /// - `&SceneTree` - Retained scene tree.
    /// - `NodeId` - Scroll container node handle.
    /// - `TerminalRegion` - Active character-grid region and focus context.
    /// - `&mut u16` - Mutable current row cursor.
    fn project_scroll_view(
        &mut self,
        tree: &SceneTree,
        node_id: NodeId,
        region: TerminalRegion,
        y: &mut u16,
    ) {
        self.get_mut_tracked_scroll_nodes().push(node_id);
        let x: u16 = region.get_x();
        let avail_w: u16 = region.get_width();
        let max_y: u16 = region.get_max_y();
        let focused: Option<NodeId> = region.get_focused();
        let Some(node) = tree.get_node(node_id) else {
            return;
        };
        let total_visible: usize = tree
            .children_iter(node_id)
            .filter(|cid: &NodeId| Self::is_node_visible(tree, *cid))
            .count();
        let avail_h: u16 = max_y.saturating_sub(*y);
        if avail_h == 0 || total_visible == 0 {
            return;
        }
        let scroll_y: f32 = node.get_layout_box().get_scroll_offset().get_y().max(0.0);
        let skip_items: usize = ((scroll_y / TERMINAL_SCROLL_STEP_PX).floor() as usize)
            .min(total_visible.saturating_sub(1));
        let needs_rail: bool = total_visible > (avail_h as usize) && avail_w >= 3;
        let inner_w: u16 = if needs_rail {
            avail_w.saturating_sub(1)
        } else {
            avail_w
        };
        let child_region: TerminalRegion = TerminalRegion::new(x, inner_w, max_y, focused);
        let start_y: u16 = *y;
        let mut seen_visible: usize = 0;
        for child_id in tree.children_iter(node_id) {
            if !Self::is_node_visible(tree, child_id) {
                continue;
            }
            if seen_visible < skip_items {
                seen_visible += 1;
                continue;
            }
            if *y >= max_y {
                break;
            }
            self.project_node(tree, child_id, child_region, y);
            seen_visible += 1;
        }
        if needs_rail {
            let rail_x: u16 = x.saturating_add(inner_w);
            let total_items: usize = total_visible.max(1);
            let thumb_offset: u16 = ((skip_items * (avail_h as usize)) / total_items)
                .min((avail_h - 1) as usize) as u16;
            for offset in 0..avail_h {
                let glyph: char = if offset == thumb_offset {
                    TERMINAL_SCROLL_THUMB
                } else {
                    TERMINAL_SCROLL_TRACK
                };
                let _: u16 = self.get_mut_current().put_cell(
                    rail_x,
                    start_y.saturating_add(offset),
                    TerminalCell::styled(glyph, 1, None, None, false, false, false),
                );
            }
        }
    }

    /// Writes `text` wrapped across consecutive terminal rows within `region` by Extended Grapheme Clusters without breaking CJK wide glyphs or ZWJ emoji sequences.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable terminal renderer.
    /// - `TerminalRegion` - Active character-grid region.
    /// - `&mut u16` - Mutable current row cursor.
    /// - `&str` - UTF-8 text to wrap.
    /// - `TerminalCell` - Style template cell.
    fn write_wrapped_text(
        &mut self,
        region: TerminalRegion,
        y: &mut u16,
        text: &str,
        template: TerminalCell,
    ) {
        let x: u16 = region.get_x();
        let avail_w: u16 = region.get_width();
        let max_y: u16 = region.get_max_y();
        if *y >= max_y || avail_w == 0 {
            return;
        }
        let mut wrote_any_line: bool = false;
        for raw_line in text.split('\n') {
            if *y >= max_y {
                break;
            }
            if raw_line.is_empty() {
                *y = y.saturating_add(1);
                wrote_any_line = true;
                continue;
            }
            let raw_bytes: &[u8] = raw_line.as_bytes();
            if raw_line.is_ascii() && raw_bytes.iter().all(|b: &u8| (0x20..=0x7E).contains(b)) {
                let chunk_len: usize = avail_w as usize;
                let mut offset: usize = 0;
                while offset < raw_bytes.len() {
                    if *y >= max_y {
                        return;
                    }
                    let end: usize = (offset + chunk_len).min(raw_bytes.len());
                    let _: u16 = self.get_mut_current().write_printable_ascii_run(
                        x,
                        *y,
                        &raw_bytes[offset..end],
                        template,
                    );
                    offset = end;
                    if offset < raw_bytes.len() {
                        *y = y.saturating_add(1);
                    }
                }
                *y = y.saturating_add(1);
                wrote_any_line = true;
                continue;
            }
            let mut cur_col: u16 = 0;
            let mut rest: &str = raw_line;
            while let Some((cluster, next_rest)) = next_grapheme_cluster(rest) {
                rest = next_rest;
                if cluster.starts_with('\r') {
                    continue;
                }
                let width: u8 = grapheme_display_width(cluster);
                if width == 0 {
                    continue;
                }
                let w_u16: u16 = width as u16;
                if w_u16 > avail_w {
                    continue;
                }
                if cur_col.saturating_add(w_u16) > avail_w {
                    *y = y.saturating_add(1);
                    if *y >= max_y {
                        return;
                    }
                    cur_col = 0;
                }
                let cell: TerminalCell = TerminalCell::from_grapheme(cluster, width, template);
                let consumed: u16 = self.get_mut_current().put_cell(x + cur_col, *y, cell);
                cur_col = cur_col.saturating_add(consumed);
            }
            *y = y.saturating_add(1);
            wrote_any_line = true;
        }
        if !wrote_any_line {
            *y = y.saturating_add(1);
        }
    }

    /// Encodes the full current grid into `ansi_scratch` using zero-allocation cursor and SGR delta sequences.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable terminal renderer.
    fn encode_full_frame_into_scratch(&mut self) {
        let sync_mode: bool = self.get_sync_output_mode();
        let Self {
            current,
            ansi_scratch,
            ..
        } = self;
        let cols: u16 = current.get_cols();
        let rows: u16 = current.get_rows();
        let needed: usize = current.total_cells().saturating_mul(2);
        if ansi_scratch.capacity() < needed {
            ansi_scratch.reserve(needed - ansi_scratch.capacity());
        }
        if sync_mode {
            ansi_scratch.push_str(ANSI_SYNC_UPDATE_BEGIN);
        }
        ansi_scratch.push_str(ANSI_CLEAR_AND_HOME);
        let mut active_style: Option<TerminalCell> = None;
        let mut cursor_pos: Option<(u16, u16)> = Some((0, 0));
        for row in 0..rows {
            append_cursor_move_smart(ansi_scratch, cursor_pos, 0, row);
            cursor_pos = Some((0, row));
            let mut col: u16 = 0;
            while col < cols {
                let Some(cell) = current.cell(col, row) else {
                    col += 1;
                    continue;
                };
                if cell.is_continuation() {
                    col += 1;
                    continue;
                }
                append_sgr_delta(ansi_scratch, active_style, &cell);
                active_style = Some(cell);
                cell.push_grapheme_to(ansi_scratch);
                let step: u16 = cell.get_width().max(1) as u16;
                cursor_pos = Some((col.saturating_add(step), row));
                col = col.saturating_add(step);
            }
        }
        ansi_scratch.push_str(ANSI_RESET_STYLE);
        if sync_mode {
            ansi_scratch.push_str(ANSI_SYNC_UPDATE_END);
        }
    }

    /// Encodes only cells changed relative to `previous` into `ansi_scratch`, skipping unchanged rows via row hashes and coalescing short runs and SGR deltas.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable terminal renderer.
    ///
    /// # Returns
    ///
    /// - `TerminalDiffStats` - Incremental diff telemetry (`is_idle == true` and `0` bytes when identical).
    fn encode_diff_frame_into_scratch(&mut self) -> TerminalDiffStats {
        let sync_mode: bool = self.get_sync_output_mode();
        let Self {
            previous,
            current,
            ansi_scratch,
            ..
        } = self;
        let total_cells: usize = current.total_cells();
        let cols: u16 = current.get_cols();
        let rows: u16 = current.get_rows();
        let mut changed_cells: usize = 0;
        let mut active_style: Option<TerminalCell> = None;
        let mut cursor_pos: Option<(u16, u16)> = None;
        let mut emitted_any: bool = false;
        for row in 0..rows {
            let row_idx: usize = row as usize;
            let cur_hash: Option<u64> = current.get_row_hashes().get(row_idx).copied();
            let prev_hash: Option<u64> = previous.get_row_hashes().get(row_idx).copied();
            if cur_hash.is_some() && cur_hash == prev_hash {
                continue;
            }
            let mut col: u16 = 0;
            while col < cols {
                let Some(cur_cell) = current.cell(col, row) else {
                    col += 1;
                    continue;
                };
                let Some(prev_cell) = previous.cell(col, row) else {
                    col += 1;
                    continue;
                };
                if cur_cell.is_continuation() {
                    col += 1;
                    continue;
                }
                let mut cell_dirty: bool =
                    Self::is_cell_dirty(current, previous, col, row, cur_cell, prev_cell);
                if !cell_dirty
                    && let Some((cur_cx, cur_cy)) = cursor_pos
                    && cur_cy == row
                    && cur_cx == col
                    && let Some(active) = active_style
                    && active.same_style(&cur_cell)
                    && Self::has_dirty_within_gap(current, previous, col, row, cols)
                {
                    cell_dirty = true;
                }
                if !cell_dirty {
                    col = col.saturating_add(cur_cell.get_width().max(1) as u16);
                    continue;
                }
                if !emitted_any && sync_mode {
                    ansi_scratch.push_str(ANSI_SYNC_UPDATE_BEGIN);
                }
                emitted_any = true;
                let step: u16 = cur_cell.get_width().max(1) as u16;
                if cur_cell != prev_cell {
                    changed_cells = changed_cells.saturating_add(step as usize);
                }
                append_cursor_move_smart(ansi_scratch, cursor_pos, col, row);
                append_sgr_delta(ansi_scratch, active_style, &cur_cell);
                active_style = Some(cur_cell);
                cur_cell.push_grapheme_to(ansi_scratch);
                cursor_pos = Some((col.saturating_add(step), row));
                col = col.saturating_add(step);
            }
        }
        if !emitted_any {
            return TerminalDiffStats::new(total_cells, 0, 0, true, false);
        }
        ansi_scratch.push_str(ANSI_RESET_STYLE);
        if sync_mode {
            ansi_scratch.push_str(ANSI_SYNC_UPDATE_END);
        }
        let output_bytes: usize = ansi_scratch.len();
        TerminalDiffStats::new(
            total_cells,
            changed_cells.max(1),
            output_bytes,
            false,
            false,
        )
    }

    /// Determines whether cell `(col, row)` must be emitted, including wide-character partner invalidation on both lead and continuation columns.
    ///
    /// # Arguments
    ///
    /// - `&TerminalCellGrid` - Active grid.
    /// - `&TerminalCellGrid` - Committed previous grid.
    /// - `u16` - Zero-based column coordinate.
    /// - `u16` - Zero-based row coordinate.
    /// - `TerminalCell` - Current cell value.
    /// - `TerminalCell` - Previous cell value.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `(col, row)` requires re-emission.
    #[must_use]
    fn is_cell_dirty(
        current: &TerminalCellGrid,
        previous: &TerminalCellGrid,
        col: u16,
        row: u16,
        cur_cell: TerminalCell,
        prev_cell: TerminalCell,
    ) -> bool {
        if cur_cell != prev_cell {
            return true;
        }
        if cur_cell.is_wide_lead()
            && col.saturating_add(1) < current.get_cols()
            && current.cell(col + 1, row) != previous.cell(col + 1, row)
        {
            return true;
        }
        if prev_cell.is_continuation() && !cur_cell.is_continuation() {
            return true;
        }
        if col > 0
            && let Some(prev_left) = previous.cell(col - 1, row)
            && prev_left.is_wide_lead()
            && current.cell(col - 1, row) != Some(prev_left)
        {
            return true;
        }
        false
    }

    /// Checks whether another dirty cell appears within `TERMINAL_COALESCE_GAP_MAX` columns so short same-style gaps avoid expensive cursor-move escapes.
    ///
    /// # Arguments
    ///
    /// - `&TerminalCellGrid` - Active grid.
    /// - `&TerminalCellGrid` - Committed previous grid.
    /// - `u16` - Starting column coordinate.
    /// - `u16` - Zero-based row coordinate.
    /// - `u16` - Total columns in the grid.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if coalescing across the current cell saves cursor movement.
    #[must_use]
    fn has_dirty_within_gap(
        current: &TerminalCellGrid,
        previous: &TerminalCellGrid,
        start_col: u16,
        row: u16,
        cols: u16,
    ) -> bool {
        let mut probe: u16 = start_col.saturating_add(1);
        let max_probe: u16 = start_col
            .saturating_add(TERMINAL_COALESCE_GAP_MAX)
            .min(cols.saturating_sub(1));
        while probe <= max_probe {
            if let (Some(c), Some(p)) = (current.cell(probe, row), previous.cell(probe, row))
                && !c.is_continuation()
                && Self::is_cell_dirty(current, previous, probe, row, c, p)
            {
                return true;
            }
            probe = probe.saturating_add(1);
        }
        false
    }

    /// Explicitly signals that TUI/CLI rendering opts out of graphical GPU routing.
    ///
    /// # Returns
    ///
    /// - `bool` - Always `true`.
    #[must_use]
    pub fn opts_out_of_gpu_routing(&self) -> bool {
        true
    }

    /// Records the arrival timestamp of a terminal input event for subsequent `input_to_output_ms` measurement.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn record_input_received(&mut self) {
        let Self { last_input_at, .. } = self;
        *last_input_at = Some(Instant::now());
    }

    /// Consumes the pending input timestamp and returns elapsed `input_to_output_ms` (`None` when unobservable).
    ///
    /// # Returns
    ///
    /// - `Option<f64>` - Elapsed milliseconds since the recorded input event.
    #[cfg(not(target_arch = "wasm32"))]
    fn take_input_to_output_ms(&mut self) -> Option<f64> {
        let Self { last_input_at, .. } = self;
        last_input_at
            .take()
            .map(|ts: Instant| ts.elapsed().as_secs_f64() * 1000.0)
    }

    /// Returns the most recent non-GPU, non-Hz TUI/CLI telemetry snapshot.
    ///
    /// # Returns
    ///
    /// - `TerminalNonGpuTelemetry` - Latest telemetry (`input_to_output_ms`, `flush_latency_ms`, `bytes_written`, backpressure).
    #[must_use]
    pub fn last_telemetry_report(&self) -> TerminalNonGpuTelemetry {
        self.get_last_telemetry()
    }
}

/// Accessors for `TerminalNonGpuTelemetry`.
impl TerminalNonGpuTelemetry {
    /// Returns the measured input-to-output latency in milliseconds (`None` when no input preceded the flush).
    ///
    /// # Returns
    ///
    /// - `Option<f64>` - Input-to-output latency in milliseconds.
    #[must_use]
    pub fn input_to_output_ms(&self) -> Option<f64> {
        let Self {
            input_to_output_ms, ..
        } = self;
        *input_to_output_ms
    }
}