bettertui_engine 0.1.1

High-performance terminal UI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
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
//! Rendering pipeline: Renderer, RenderFrame, RenderBackend, AnsiBackend, Painter, RenderPipeline, RenderTree.

use std::cell::RefCell;
use std::collections::HashMap;

use tracing::{debug, info};

use crate::dirty_diff::{DirtyDiff, DirtyRegion};
use crate::framebuffer::{Cell, CellAttributes, FrameBuffer};
use crate::hit_grid::HitGrid;
use crate::protocol::ScreenMode;
use crate::scheduler::{FrameStatus, Scheduler};
use crate::taffy::build_render_tree_with_viewport;
use crate::taffy::{ClipBounds, LayoutTreeSync, PaintBounds, PaintContext, PaintFlags, Viewport};
use crate::text::{TextAlign, ViewportConfig, layout_text};
use crate::tree::NodeArena;
use crate::tree::{Color, NamedColor, NodeId, Overflow, Rect, ResolvedStyle};

// ═══════════════════════════════════════════════════════════════════════════════
// === backend.rs ===
// ═══════════════════════════════════════════════════════════════════════════════

pub trait RenderBackend: Send {
    fn encode(&mut self, buffer: &FrameBuffer, regions: &[DirtyRegion]);
    fn finish(&self) -> &[u8];
    fn reset(&mut self);
    fn set_cursor_position(&mut self, x: u16, y: u16, visible: bool);
    /// Called at the start of each frame. Emit mode-switching ANSI sequences here.
    fn begin_frame(&mut self, _screen_mode: &ScreenMode, _width: u16, _height: u16) {}
    /// Called at the end of each frame. Emit cleanup sequences here.
    fn end_frame(&mut self, _screen_mode: &ScreenMode) {}
}

// ═══════════════════════════════════════════════════════════════════════════════
// === ansi.rs ===
// ═══════════════════════════════════════════════════════════════════════════════

pub struct AnsiBackend {
    buffer: Vec<u8>,
    cursor_x: u16,
    cursor_y: u16,
    previous_mode: ScreenMode,
    entered_alternate: bool,
    /// Link id of the currently-open OSC 8 hyperlink (`0` = none open).
    current_link: u16,
}

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

impl AnsiBackend {
    pub fn new() -> Self {
        Self {
            buffer: Vec::with_capacity(4096),
            cursor_x: u16::MAX,
            cursor_y: u16::MAX,
            previous_mode: ScreenMode::AlternateScreen,
            entered_alternate: false,
            current_link: 0,
        }
    }

    fn encode_region(&mut self, buffer: &FrameBuffer, region: &DirtyRegion) {
        for y in region.y..region.y + region.height {
            self.move_to(region.x, y);

            // Run-length coalescing: batch consecutive same-styled cells
            let mut x = region.x;
            while x < region.x + region.width {
                let cell = buffer.get(x, y);
                let run_start = x;
                x += 1;
                while x < region.x + region.width {
                    let next = buffer.get(x, y);
                    if next.fg == cell.fg
                        && next.bg == cell.bg
                        && next.attributes == cell.attributes
                        && next.link_id == cell.link_id
                    {
                        x += 1;
                    } else {
                        break;
                    }
                }
                let run_len = x - run_start;

                // Open/close OSC 8 hyperlink when the run's link changes.
                self.sync_link(cell.link_id, buffer);

                // Emit SGR once for entire run
                self.encode_cell(&cell);

                // Emit all characters in the run
                for cx in run_start..run_start + run_len {
                    self.push_char(buffer.get(cx, y).ch);
                }
                self.cursor_x += run_len;
            }
        }
    }

    /// Emits the OSC 8 sequence needed to transition the open hyperlink to
    /// `link_id` (0 closes any open link). No-op when already in that state.
    fn sync_link(&mut self, link_id: u16, buffer: &FrameBuffer) {
        if link_id == self.current_link {
            return;
        }
        match buffer.link_url(link_id) {
            Some(url) => {
                // OSC 8 ; params ; URI ST — params left empty (no id needed on emit).
                self.buffer.extend_from_slice(b"\x1b]8;;");
                self.buffer.extend_from_slice(url.as_bytes());
                self.buffer.extend_from_slice(b"\x1b\\");
                self.current_link = link_id;
            }
            None => {
                // Close the currently open link (empty URI).
                self.buffer.extend_from_slice(b"\x1b]8;;\x1b\\");
                self.current_link = 0;
            }
        }
    }

    fn encode_cell(&mut self, cell: &Cell) {
        self.begin_sgr();
        self.buffer.push(b'0');
        self.push_fg_sgr(cell.fg);
        self.push_bg_sgr(cell.bg);
        self.push_attrs_sgr(cell.attributes);
        self.end_sgr();
    }

    fn begin_sgr(&mut self) {
        self.buffer.extend_from_slice(b"\x1b[");
    }

    fn end_sgr(&mut self) {
        self.buffer.push(b'm');
    }

    fn push_fg_sgr(&mut self, color: Color) {
        match color {
            Color::Default => self.push_param(39),
            Color::Named(named) => {
                let code = match named {
                    NamedColor::Black => 30,
                    NamedColor::Red => 31,
                    NamedColor::Green => 32,
                    NamedColor::Yellow => 33,
                    NamedColor::Blue => 34,
                    NamedColor::Magenta => 35,
                    NamedColor::Cyan => 36,
                    NamedColor::White => 37,
                    NamedColor::BrightBlack => 90,
                    NamedColor::BrightRed => 91,
                    NamedColor::BrightGreen => 92,
                    NamedColor::BrightYellow => 93,
                    NamedColor::BrightBlue => 94,
                    NamedColor::BrightMagenta => 95,
                    NamedColor::BrightCyan => 96,
                    NamedColor::BrightWhite => 97,
                };
                self.push_param(code);
            }
            Color::Rgb { r, g, b } => {
                self.push_param(38);
                self.push_param(2);
                self.push_param(r as u32);
                self.push_param(g as u32);
                self.push_param(b as u32);
            }
            Color::Indexed(i) => {
                self.push_param(38);
                self.push_param(5);
                self.push_param(i as u32);
            }
        }
    }

    fn push_bg_sgr(&mut self, color: Color) {
        match color {
            Color::Default => self.push_param(49),
            Color::Named(named) => {
                let code = match named {
                    NamedColor::Black => 40,
                    NamedColor::Red => 41,
                    NamedColor::Green => 42,
                    NamedColor::Yellow => 43,
                    NamedColor::Blue => 44,
                    NamedColor::Magenta => 45,
                    NamedColor::Cyan => 46,
                    NamedColor::White => 47,
                    NamedColor::BrightBlack => 100,
                    NamedColor::BrightRed => 101,
                    NamedColor::BrightGreen => 102,
                    NamedColor::BrightYellow => 103,
                    NamedColor::BrightBlue => 104,
                    NamedColor::BrightMagenta => 105,
                    NamedColor::BrightCyan => 106,
                    NamedColor::BrightWhite => 107,
                };
                self.push_param(code);
            }
            Color::Rgb { r, g, b } => {
                self.push_param(48);
                self.push_param(2);
                self.push_param(r as u32);
                self.push_param(g as u32);
                self.push_param(b as u32);
            }
            Color::Indexed(i) => {
                self.push_param(48);
                self.push_param(5);
                self.push_param(i as u32);
            }
        }
    }

    fn push_attrs_sgr(&mut self, attrs: CellAttributes) {
        if attrs.contains(CellAttributes::BOLD) {
            self.push_param(1);
        }
        if attrs.contains(CellAttributes::DIM) {
            self.push_param(2);
        }
        if attrs.contains(CellAttributes::ITALIC) {
            self.push_param(3);
        }
        if attrs.contains(CellAttributes::UNDERLINE) {
            self.push_param(4);
        }
        if attrs.contains(CellAttributes::STRIKETHROUGH) {
            self.push_param(9);
        }
        if attrs.contains(CellAttributes::INVERSE) {
            self.push_param(7);
        }
        if attrs.contains(CellAttributes::HIDDEN) {
            self.push_param(8);
        }
    }

    fn push_param(&mut self, n: u32) {
        if !self.buffer.ends_with(b"[") && !self.buffer.ends_with(b";") {
            self.buffer.push(b';');
        }
        let mut buf = [0u8; 10];
        let mut i = buf.len();
        let mut val = n;
        if val == 0 {
            i -= 1;
            buf[i] = b'0';
        } else {
            while val > 0 {
                i -= 1;
                buf[i] = b'0' + (val % 10) as u8;
                val /= 10;
            }
        }
        self.buffer.extend_from_slice(&buf[i..]);
    }

    fn push_char(&mut self, ch: char) {
        let mut buf = [0u8; 4];
        let s = ch.encode_utf8(&mut buf);
        self.buffer.extend_from_slice(s.as_bytes());
    }

    fn move_to(&mut self, x: u16, y: u16) {
        if x == self.cursor_x && y == self.cursor_y {
            return;
        }
        self.buffer.extend_from_slice(b"\x1b[");
        self.push_u16(y + 1);
        self.buffer.push(b';');
        self.push_u16(x + 1);
        self.buffer.push(b'H');
        self.cursor_x = x;
        self.cursor_y = y;
    }

    fn push_u16(&mut self, n: u16) {
        if n == 0 {
            self.buffer.push(b'0');
            return;
        }
        let mut buf = [0u8; 5];
        let mut i = buf.len();
        let mut val = n;
        while val > 0 {
            i -= 1;
            buf[i] = b'0' + (val % 10) as u8;
            val /= 10;
        }
        self.buffer.extend_from_slice(&buf[i..]);
    }

    fn hide_cursor(&mut self) {
        self.buffer.extend_from_slice(b"\x1b[?25l");
    }

    fn show_cursor(&mut self) {
        self.buffer.extend_from_slice(b"\x1b[?25h");
    }

    pub fn reset_sgr(&mut self) {
        self.buffer.extend_from_slice(b"\x1b[0m");
    }

    /// Begin synchronized output (DECSET 2026).
    pub fn begin_sync(&mut self) {
        self.buffer.extend_from_slice(b"\x1b[?2026h");
    }

    /// End synchronized output (DECSET 2026).
    pub fn end_sync(&mut self) {
        self.buffer.extend_from_slice(b"\x1b[?2026l");
    }

    /// Emit split-footer scroll region: main viewport rows 1..footer_start.
    /// After this, cursor movement in rows >= footer_start is clipped.
    pub fn set_scroll_region(&mut self, footer_start: u16, _total_height: u16) {
        self.buffer.extend_from_slice(b"\x1b[");
        self.push_u16(1);
        self.buffer.push(b';');
        self.push_u16(footer_start);
        self.buffer.push(b'r');
    }

    /// Reset scroll region to full terminal height.
    pub fn reset_scroll_region(&mut self, total_height: u16) {
        self.buffer.extend_from_slice(b"\x1b[");
        self.push_u16(1);
        self.buffer.push(b';');
        self.push_u16(total_height);
        self.buffer.push(b'r');
    }

    /// Switch to main screen (exit alternate screen).
    pub fn exit_alternate_screen(&mut self) {
        self.buffer.extend_from_slice(b"\x1b[?1049l");
    }

    /// Enter alternate screen (save main screen).
    pub fn enter_alternate_screen(&mut self) {
        self.buffer.extend_from_slice(b"\x1b[?1049h");
    }
}

impl RenderBackend for AnsiBackend {
    fn encode(&mut self, buffer: &FrameBuffer, regions: &[DirtyRegion]) {
        // NOTE: Do NOT clear self.buffer here — begin_frame() already wrote
        // sync/mode sequences into it. Clearing would destroy that output.
        self.cursor_x = u16::MAX;
        self.cursor_y = u16::MAX;
        self.current_link = 0;

        if regions.is_empty() {
            return;
        }

        self.hide_cursor();

        // Reset all SGR attributes at frame start so stale state (e.g. DIM left
        // active by a previous screen) cannot bleed into this frame's cells.
        self.reset_sgr();

        for region in regions {
            self.encode_region(buffer, region);
        }

        // Close any hyperlink left open by the final run so it does not bleed
        // into subsequent output.
        if self.current_link != 0 {
            self.buffer.extend_from_slice(b"\x1b]8;;\x1b\\");
            self.current_link = 0;
        }
    }

    fn finish(&self) -> &[u8] {
        &self.buffer
    }

    fn reset(&mut self) {
        self.buffer.clear();
    }

    fn set_cursor_position(&mut self, x: u16, y: u16, visible: bool) {
        self.move_to(x, y);
        if visible {
            self.show_cursor();
        } else {
            self.hide_cursor();
        }
    }

    fn begin_frame(&mut self, screen_mode: &ScreenMode, _width: u16, height: u16) {
        // Clear the output buffer at frame start so stale data from the
        // previous frame is gone. encode() will append cell data after this.
        self.buffer.clear();

        self.begin_sync();

        let mode_changed = *screen_mode != self.previous_mode;

        if mode_changed {
            match screen_mode {
                ScreenMode::AlternateScreen => {
                    if !self.entered_alternate {
                        self.enter_alternate_screen();
                        self.entered_alternate = true;
                    }
                    self.reset_scroll_region(height);
                }
                ScreenMode::MainScreen => {
                    if self.entered_alternate {
                        self.exit_alternate_screen();
                        self.entered_alternate = false;
                    }
                    self.reset_scroll_region(height);
                }
                ScreenMode::SplitFooter { height: footer_h } => {
                    if self.entered_alternate {
                        self.exit_alternate_screen();
                        self.entered_alternate = false;
                    }
                    let footer_start = height.saturating_sub(*footer_h);
                    self.set_scroll_region(footer_start, height);
                    // Move cursor to footer start
                    self.move_to(0, footer_start);
                }
            }
            self.previous_mode = *screen_mode;
        }
    }

    fn end_frame(&mut self, _screen_mode: &ScreenMode) {
        self.end_sync();
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// === object.rs ===
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct RenderObject {
    pub id: NodeId,
    pub bounds: PaintBounds,
    pub clip: Option<ClipBounds>,
    pub style: ResolvedStyle,
    pub opacity: f32,
    pub z_index: i32,
    pub translate_x: i32,
    pub translate_y: i32,
    pub text: Option<Box<str>>,
    pub text_align: TextAlign,
    pub text_wrap: bool,
    pub overflow: Overflow,
    pub flags: PaintFlags,
    /// Number of descendants in the flat DFS render list.
    /// Used by the paint loop to know the range of each node's children
    /// so scissor rects can be pushed before children and popped after.
    pub subtree_size: usize,
}

impl RenderObject {
    pub fn new(id: NodeId) -> Self {
        Self {
            id,
            bounds: PaintBounds::default(),
            clip: None,
            style: ResolvedStyle::default(),
            opacity: 1.0,
            z_index: 0,
            translate_x: 0,
            translate_y: 0,
            text: None,
            text_align: TextAlign::Left,
            text_wrap: false,
            overflow: Overflow::Visible,
            flags: PaintFlags::empty(),
            subtree_size: 0,
        }
    }

    pub fn has_background(&self) -> bool {
        self.style.bg.is_some()
    }

    pub fn has_text(&self) -> bool {
        self.text.is_some()
    }

    pub fn is_visible(&self) -> bool {
        self.opacity > 0.0 && !self.flags.contains(PaintFlags::HIDDEN)
    }

    pub fn translated_bounds(&self) -> PaintBounds {
        let mut b = self.bounds;
        b.x = (b.x as i32 + self.translate_x).max(0) as u16;
        b.y = (b.y as i32 + self.translate_y).max(0) as u16;
        b
    }

    pub fn content_rect(&self) -> Rect {
        let b = &self.bounds;
        Rect::new(
            b.x + b.padding_left,
            b.y + b.padding_top,
            b.width.saturating_sub(b.padding_left + b.padding_right),
            b.height.saturating_sub(b.padding_top + b.padding_bottom),
        )
    }
}

/// Render commands for structured rendering pipeline.
///
/// This enum follows the render command pattern, allowing
/// proper stacking of scissor rects and opacity values.
#[derive(Debug, Clone)]
pub enum RenderCommand {
    /// Render a renderable object
    Render { object: RenderObject },
    /// Push a scissor rect for clipping
    PushScissorRect { x: u16, y: u16, width: u16, height: u16 },
    /// Pop the top scissor rect
    PopScissorRect,
    /// Push an opacity value (multiplied with current)
    PushOpacity { opacity: f32 },
    /// Pop the top opacity value
    PopOpacity,
}

impl RenderCommand {
    pub fn render(obj: RenderObject) -> Self {
        Self::Render { object: obj }
    }

    pub fn push_scissor(x: u16, y: u16, width: u16, height: u16) -> Self {
        Self::PushScissorRect { x, y, width, height }
    }

    pub fn pop_scissor() -> Self {
        Self::PopScissorRect
    }

    pub fn push_opacity(opacity: f32) -> Self {
        Self::PushOpacity { opacity }
    }

    pub fn pop_opacity() -> Self {
        Self::PopOpacity
    }
}

#[derive(Debug, Clone)]
pub struct RenderTree {
    objects: Vec<RenderObject>,
    index: HashMap<NodeId, usize>,
    root: Option<NodeId>,
    sorted_cache: RefCell<Option<Vec<usize>>>,
    /// Cached render commands for reuse.
    cached_commands: RefCell<Option<Vec<RenderCommand>>>,
    /// Layout generation when commands were cached.
    cached_generation: RefCell<u64>,
    /// Render list revision when commands were cached.
    cached_revision: RefCell<u64>,
}

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

impl RenderTree {
    pub fn new() -> Self {
        Self {
            objects: Vec::new(),
            index: HashMap::new(),
            root: None,
            sorted_cache: RefCell::new(None),
            cached_commands: RefCell::new(None),
            cached_generation: RefCell::new(0),
            cached_revision: RefCell::new(0),
        }
    }

    pub fn push(&mut self, obj: RenderObject) {
        let idx = self.objects.len();
        if self.root.is_none() {
            self.root = Some(obj.id);
        }
        self.index.insert(obj.id, idx);
        self.objects.push(obj);
        *self.sorted_cache.borrow_mut() = None;
    }

    pub fn get(&self, id: NodeId) -> Option<&RenderObject> {
        self.index.get(&id).and_then(|&idx| self.objects.get(idx))
    }

    pub fn get_mut(&mut self, id: NodeId) -> Option<&mut RenderObject> {
        self.index.get(&id).copied().and_then(|idx| self.objects.get_mut(idx))
    }

    pub fn root(&self) -> Option<NodeId> {
        self.root
    }

    pub fn objects(&self) -> &[RenderObject] {
        &self.objects
    }

    pub fn objects_mut(&mut self) -> &mut [RenderObject] {
        &mut self.objects
    }

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

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

    pub fn iter(&self) -> impl Iterator<Item = &RenderObject> {
        self.objects.iter()
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut RenderObject> {
        self.objects.iter_mut()
    }

    pub fn sorted_by_z_index(&self) -> Vec<usize> {
        let mut cache = self.sorted_cache.borrow_mut();
        if let Some(ref cached) = *cache {
            return cached.clone();
        }
        let mut indices: Vec<usize> = (0..self.objects.len()).collect();
        indices.sort_by_key(|&i| self.objects[i].z_index);
        *cache = Some(indices.clone());
        indices
    }

    pub fn clear(&mut self) {
        self.objects.clear();
        self.index.clear();
        self.root = None;
        *self.sorted_cache.borrow_mut() = None;
        *self.cached_commands.borrow_mut() = None;
    }

    /// Invalidate the cached commands (call when render tree changes).
    pub fn invalidate_cache(&self) {
        *self.cached_commands.borrow_mut() = None;
    }

    /// Collect render commands with caching.
    ///
    /// If generation and revision match the cached values, returns cached commands.
    /// Otherwise, rebuilds commands and updates cache.
    pub fn collect_commands_cached(&self, generation: u64, revision: u64) -> Vec<RenderCommand> {
        let cached_gen = self.cached_generation.borrow();
        let cached_rev = self.cached_revision.borrow();

        if *cached_gen == generation
            && *cached_rev == revision
            && let Some(ref commands) = *self.cached_commands.borrow()
        {
            crate::diag!(|d| d.inc_cache_hits());
            return commands.clone();
        }

        drop(cached_gen);
        drop(cached_rev);

        crate::diag!(|d| d.inc_cache_misses());
        let commands = self.collect_commands();
        *self.cached_commands.borrow_mut() = Some(commands.clone());
        *self.cached_generation.borrow_mut() = generation;
        *self.cached_revision.borrow_mut() = revision;
        commands
    }

    /// Collect render commands with proper scissor/opacity stacking.
    ///
    /// The pattern:
    /// 1. Push opacity if < 1.0
    /// 2. Push render command
    /// 3. Push scissor rect if overflow !== visible
    /// 4. Process children
    /// 5. Pop scissor rect
    /// 6. Pop opacity
    pub fn collect_commands(&self) -> Vec<RenderCommand> {
        let mut commands = Vec::with_capacity(self.objects.len() * 2);

        for obj in &self.objects {
            if !obj.is_visible() {
                continue;
            }

            let needs_opacity = obj.opacity < 1.0;
            let needs_scissor = obj.clip.is_some();

            if needs_opacity {
                commands.push(RenderCommand::push_opacity(obj.opacity));
            }

            commands.push(RenderCommand::render(obj.clone()));

            if let Some(clip) = &obj.clip {
                commands.push(RenderCommand::push_scissor(clip.x, clip.y, clip.width, clip.height));
            }

            if needs_scissor {
                commands.push(RenderCommand::pop_scissor());
            }

            if needs_opacity {
                commands.push(RenderCommand::pop_opacity());
            }
        }

        commands
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// === painter.rs ===
// ═══════════════════════════════════════════════════════════════════════════════

pub struct Painter {
    buffer: FrameBuffer,
    background_color: Color,
    opacity_stack: Vec<f32>,
    scissor_stack: Vec<ClipBounds>,
}

impl Default for Painter {
    fn default() -> Self {
        Self::new(0, 0)
    }
}

impl Painter {
    pub fn new(width: u16, height: u16) -> Self {
        Self {
            buffer: FrameBuffer::new(width, height),
            background_color: Color::Default,
            opacity_stack: Vec::with_capacity(8),
            scissor_stack: Vec::with_capacity(8),
        }
    }

    pub fn set_background_color(&mut self, color: Color) {
        self.background_color = color;
    }

    pub fn background_color(&self) -> Color {
        self.background_color
    }

    pub fn resize(&mut self, width: u16, height: u16) {
        self.buffer.resize(width, height);
    }

    pub fn buffer(&self) -> &FrameBuffer {
        &self.buffer
    }

    pub fn buffer_mut(&mut self) -> &mut FrameBuffer {
        &mut self.buffer
    }

    /// Get current effective opacity (product of all stacked values).
    pub fn current_opacity(&self) -> f32 {
        self.opacity_stack.last().copied().unwrap_or(1.0)
    }

    /// Push an opacity value onto the stack.
    pub fn push_opacity(&mut self, opacity: f32) {
        let current = self.current_opacity();
        let effective = (current * opacity).clamp(0.0, 1.0);
        self.opacity_stack.push(effective);
    }

    /// Pop an opacity value from the stack.
    pub fn pop_opacity(&mut self) {
        self.opacity_stack.pop();
    }

    /// Push a scissor rect onto the stack.
    /// Intersects with current scissor if any.
    pub fn push_scissor(&mut self, x: u16, y: u16, width: u16, height: u16) {
        let new_clip = ClipBounds::new(x, y, width, height);
        if let Some(current) = self.scissor_stack.last() {
            if let Some(intersected) = current.intersect(&new_clip) {
                self.scissor_stack.push(intersected);
            } else {
                self.scissor_stack.push(ClipBounds::new(0, 0, 0, 0));
            }
        } else {
            self.scissor_stack.push(new_clip);
        }
    }

    /// Pop a scissor rect from the stack.
    pub fn pop_scissor(&mut self) {
        self.scissor_stack.pop();
    }

    /// Get current scissor rect if any.
    pub fn current_scissor(&self) -> Option<&ClipBounds> {
        self.scissor_stack.last()
    }

    pub fn paint(&mut self, tree: &RenderTree, ctx: &PaintContext) {
        self.paint_with_clear(tree, ctx, true);
    }

    pub fn paint_with_clear(&mut self, tree: &RenderTree, ctx: &PaintContext, full_clear: bool) {
        if full_clear {
            self.buffer.clear_with_bg(self.background_color);
        }
        self.scissor_stack.clear();

        // Each entry is the flat-list index at which its scissor should be popped.
        // Entries are in DFS order so the innermost scope always has the smallest
        // pop index and sits at the back of the Vec.
        let mut scissor_ends: Vec<usize> = Vec::new();
        let objects = tree.objects();

        for (i, obj) in objects.iter().enumerate() {
            // Pop any scissors whose subtree has ended before this index.
            while scissor_ends.last().is_some_and(|&end| i >= end) {
                self.pop_scissor();
                scissor_ends.pop();
            }

            self.paint_object_with_scissor(obj, ctx);

            // Push scissor AFTER painting the node itself so its own background/
            // border paint is not clipped, but its children are.
            if let Some(clip) = &obj.clip {
                self.push_scissor(clip.x, clip.y, clip.width, clip.height);
                scissor_ends.push(i + obj.subtree_size + 1);
            }
        }

        // Pop any scissors that outlast the last node.
        for _ in &scissor_ends {
            self.pop_scissor();
        }
    }

    /// Paint from render commands with proper stacking.
    pub fn paint_commands(&mut self, commands: &[RenderCommand], ctx: &PaintContext) {
        self.buffer.clear_with_bg(self.background_color);
        self.opacity_stack.clear();
        self.scissor_stack.clear();

        for command in commands {
            match command {
                RenderCommand::Render { object } => {
                    self.paint_object_with_scissor(object, ctx);
                }
                RenderCommand::PushScissorRect { x, y, width, height } => {
                    self.push_scissor(*x, *y, *width, *height);
                }
                RenderCommand::PopScissorRect => {
                    self.pop_scissor();
                }
                RenderCommand::PushOpacity { opacity } => {
                    self.push_opacity(*opacity);
                }
                RenderCommand::PopOpacity => {
                    self.pop_opacity();
                }
            }
        }
    }

    fn paint_object_with_scissor(&mut self, obj: &RenderObject, ctx: &PaintContext) {
        if !obj.is_visible() {
            return;
        }

        let translated = obj.translated_bounds();
        let bounds = &translated;

        let effective_bounds = if let Some(scissor) = self.current_scissor() {
            if let Some(intersected) =
                scissor.intersect(&ClipBounds::new(bounds.x, bounds.y, bounds.width, bounds.height))
            {
                PaintBounds::new(intersected.x, intersected.y, intersected.width, intersected.height)
                    .with_padding(bounds.padding_left, bounds.padding_right, bounds.padding_top, bounds.padding_bottom)
                    .with_border(bounds.border_top, bounds.border_right, bounds.border_bottom, bounds.border_left)
            } else {
                return;
            }
        } else {
            translated
        };

        if !ctx.is_visible(&effective_bounds) {
            return;
        }

        if let Some(clipped) = ctx.clipped_bounds(&effective_bounds) {
            self.paint_background(obj, &clipped);
            self.paint_border(obj, &clipped);
            self.paint_text(obj, &clipped);
        }
    }

    fn paint_background(&mut self, obj: &RenderObject, bounds: &PaintBounds) {
        if !obj.flags.contains(PaintFlags::BACKGROUND) {
            return;
        }

        let bg = obj.style.bg.unwrap_or(Color::Default);
        if bg == Color::Default {
            return;
        }

        let cell = Cell::new(' ').with_bg(bg);
        self.buffer.fill_rect(bounds.x, bounds.y, bounds.width, bounds.height, cell);
    }

    fn paint_text(&mut self, obj: &RenderObject, bounds: &PaintBounds) {
        // If node has a border, the text is used as the border title, so don't draw it inside
        let has_border =
            bounds.border_top > 0 || bounds.border_right > 0 || bounds.border_bottom > 0 || bounds.border_left > 0;

        if has_border && obj.style.border_style != crate::tree::BorderStyle::None {
            return;
        }

        let text = match &obj.text {
            Some(t) => t.as_ref(),
            None => return,
        };

        let content = bounds.content_rect();
        let fg = obj.style.fg.unwrap_or(Color::Default);
        let bg = obj.style.bg.unwrap_or(Color::Default);
        let inherit_bg = matches!(obj.style.bg, None | Some(Color::Default));
        let attrs = style_to_attrs(&obj.style);

        if text.is_empty() {
            return;
        }

        let config = ViewportConfig {
            wrap: obj.text_wrap,
            align: obj.text_align,
            max_width: content.width,
            max_height: content.height,
            pad_left: content.x,
            pad_top: content.y,
            ..ViewportConfig::default()
        };

        let layout = layout_text(text, &config);

        for line in &layout.lines {
            let y = line.y;
            if y >= self.buffer.height() {
                break;
            }
            let mut col = line.x;
            let mut active_fg = fg;
            let mut active_bg = bg;
            let mut active_attrs = attrs;
            let mut ansi_bg_override = false;

            let line_str = line.text.as_str();
            let bytes = line_str.as_bytes();
            let len = bytes.len();
            let mut byte_idx = 0;

            while byte_idx < len {
                if bytes[byte_idx] == 0x1b {
                    byte_idx += 1;
                    if byte_idx < len && bytes[byte_idx] == b'[' {
                        byte_idx += 1;
                        let param_start = byte_idx;
                        while byte_idx < len && !(0x40..=0x7e).contains(&bytes[byte_idx]) {
                            byte_idx += 1;
                        }
                        if byte_idx < len {
                            let final_byte = bytes[byte_idx];
                            let param_slice = &line_str[param_start..byte_idx];
                            byte_idx += 1;
                            if final_byte == b'm' {
                                let params: Vec<u32> =
                                    param_slice.split(';').filter_map(|p| p.parse::<u32>().ok()).collect();
                                let sgr_attrs = crate::ansi::parse_sgr(&params);
                                for sgr in sgr_attrs {
                                    match sgr {
                                        crate::ansi::SgrAttribute::Reset => {
                                            active_fg = fg;
                                            active_bg = bg;
                                            active_attrs = attrs;
                                            ansi_bg_override = false;
                                        }
                                        crate::ansi::SgrAttribute::Bold => active_attrs |= CellAttributes::BOLD,
                                        crate::ansi::SgrAttribute::Dim => active_attrs |= CellAttributes::DIM,
                                        crate::ansi::SgrAttribute::Italic => active_attrs |= CellAttributes::ITALIC,
                                        crate::ansi::SgrAttribute::Underline => {
                                            active_attrs |= CellAttributes::UNDERLINE
                                        }
                                        crate::ansi::SgrAttribute::Inverse => active_attrs |= CellAttributes::INVERSE,
                                        crate::ansi::SgrAttribute::Hidden => active_attrs |= CellAttributes::HIDDEN,
                                        crate::ansi::SgrAttribute::Strikethrough => {
                                            active_attrs |= CellAttributes::STRIKETHROUGH
                                        }
                                        crate::ansi::SgrAttribute::Foreground(fg_val) => {
                                            active_fg = Color::from(fg_val);
                                        }
                                        crate::ansi::SgrAttribute::Background(bg_val) => {
                                            active_bg = Color::from(bg_val);
                                            ansi_bg_override = true;
                                        }
                                        _ => {}
                                    }
                                }
                            }
                        }
                    } else if byte_idx < len && bytes[byte_idx] == b']' {
                        byte_idx += 1;
                        while byte_idx < len {
                            if bytes[byte_idx] == 0x07 {
                                byte_idx += 1;
                                break;
                            }
                            if bytes[byte_idx] == 0x1b && byte_idx + 1 < len && bytes[byte_idx + 1] == b'\\' {
                                byte_idx += 2;
                                break;
                            }
                            byte_idx += 1;
                        }
                    }
                    continue;
                }

                let slice = &line_str[byte_idx..];
                let g = match unicode_segmentation::UnicodeSegmentation::graphemes(slice, true).next() {
                    Some(g) => g,
                    None => break,
                };
                byte_idx += g.len();

                if col >= content.x + content.width || col >= self.buffer.width() {
                    break;
                }

                let w = unicode_width::UnicodeWidthStr::width(g) as u16;
                if let Some(ch) = g.chars().next() {
                    let effective_bg =
                        if inherit_bg && !ansi_bg_override { self.buffer.get(col, y).bg } else { active_bg };
                    let cell = Cell::new(ch).with_fg(active_fg).with_bg(effective_bg).with_attrs(active_attrs);
                    self.buffer.set(col, y, cell);
                    if w == 2 && col + 1 < self.buffer.width() {
                        let effective_bg2 =
                            if inherit_bg && !ansi_bg_override { self.buffer.get(col + 1, y).bg } else { active_bg };
                        let space = Cell::new(' ').with_fg(active_fg).with_bg(effective_bg2).with_attrs(active_attrs);
                        self.buffer.set(col + 1, y, space);
                    }
                }
                col += w;
            }
        }
    }

    fn paint_border(&mut self, obj: &RenderObject, bounds: &PaintBounds) {
        let border_style = obj.style.border_style;
        if border_style == crate::tree::BorderStyle::None {
            return;
        }

        let has_border =
            bounds.border_top > 0 || bounds.border_right > 0 || bounds.border_bottom > 0 || bounds.border_left > 0;
        if !has_border {
            return;
        }

        let fg = obj.style.border_color.unwrap_or(obj.style.fg.unwrap_or(Color::Default));
        let bg = obj.style.bg.unwrap_or(Color::Default);
        let attrs = style_to_attrs(&obj.style);

        let (tl, tr, bl, br, horiz, vert) = match border_style {
            crate::tree::BorderStyle::Solid => ('', '', '', '', '', ''),
            crate::tree::BorderStyle::Double => ('', '', '', '', '', ''),
            crate::tree::BorderStyle::Dashed => ('', '', '', '', '', ''),
            crate::tree::BorderStyle::Dotted => ('', '', '', '', '', ''),
            crate::tree::BorderStyle::None => return,
        };

        let x = bounds.x;
        let y = bounds.y;
        let w = bounds.width;
        let h = bounds.height;

        // Draw top border
        if bounds.border_top > 0 {
            let title_chars: Vec<char> = obj.text.as_deref().unwrap_or("").chars().collect();
            let title_len = title_chars.len() as u16;
            let avail = w.saturating_sub(2);
            let draw_title = !title_chars.is_empty() && avail >= title_len;
            let title_start = if draw_title {
                match obj.text_align {
                    crate::text::TextAlign::Center => 1 + (avail.saturating_sub(title_len)) / 2,
                    crate::text::TextAlign::Right => 1 + avail.saturating_sub(title_len),
                    _ => 1,
                }
            } else {
                u16::MAX
            };

            for row in 0..bounds.border_top {
                for col in 0..w {
                    let ch = if row == 0 {
                        if col == 0 && bounds.border_left > 0 {
                            tl
                        } else if col == w - 1 && bounds.border_right > 0 {
                            tr
                        } else if col >= title_start && (col - title_start) < title_len {
                            title_chars[(col - title_start) as usize]
                        } else if bounds.border_top > 1 && row < bounds.border_top - 1 {
                            ' '
                        } else {
                            horiz
                        }
                    } else {
                        ' '
                    };

                    if col < self.buffer.width() && y + row < self.buffer.height() {
                        let cell = Cell::new(ch).with_fg(fg).with_bg(bg).with_attrs(attrs);
                        self.buffer.set(x + col, y + row, cell);
                    }
                }
            }
        }

        // Draw bottom border
        if bounds.border_bottom > 0 {
            for row in 0..bounds.border_bottom {
                for col in 0..w {
                    let ch = if row == bounds.border_bottom - 1 {
                        if col == 0 && bounds.border_left > 0 {
                            bl
                        } else if col == w - 1 && bounds.border_right > 0 {
                            br
                        } else {
                            horiz
                        }
                    } else {
                        ' '
                    };
                    let draw_y = y + h - 1 - (bounds.border_bottom - 1 - row);
                    if col < self.buffer.width() && draw_y < self.buffer.height() {
                        let cell = Cell::new(ch).with_fg(fg).with_bg(bg).with_attrs(attrs);
                        self.buffer.set(x + col, draw_y, cell);
                    }
                }
            }
        }

        // Draw left border
        if bounds.border_left > 0 {
            for row in 0..h {
                for col in 0..bounds.border_left {
                    let ch = if col == 0 {
                        if row == 0 && bounds.border_top > 0 {
                            tl
                        } else if row == h - 1 && bounds.border_bottom > 0 {
                            bl
                        } else {
                            vert
                        }
                    } else {
                        ' '
                    };
                    if x + col < self.buffer.width() && y + row < self.buffer.height() {
                        let cell = Cell::new(ch).with_fg(fg).with_bg(bg).with_attrs(attrs);
                        self.buffer.set(x + col, y + row, cell);
                    }
                }
            }
        }

        // Draw right border
        if bounds.border_right > 0 {
            for row in 0..h {
                for col in 0..bounds.border_right {
                    let ch = if col == bounds.border_right - 1 {
                        if row == 0 && bounds.border_top > 0 {
                            tr
                        } else if row == h - 1 && bounds.border_bottom > 0 {
                            br
                        } else {
                            vert
                        }
                    } else {
                        ' '
                    };
                    let draw_x = x + w - 1 - (bounds.border_right - 1 - col);
                    if draw_x < self.buffer.width() && y + row < self.buffer.height() {
                        let cell = Cell::new(ch).with_fg(fg).with_bg(bg).with_attrs(attrs);
                        self.buffer.set(draw_x, y + row, cell);
                    }
                }
            }
        }
    }

    pub fn swap(&mut self) {
        self.buffer.swap();
    }

    pub fn diff(&self) -> Vec<(u16, u16)> {
        self.buffer.diff()
    }
}

fn style_to_attrs(style: &ResolvedStyle) -> CellAttributes {
    let mut attrs = CellAttributes::empty();
    if style.bold {
        attrs |= CellAttributes::BOLD;
    }
    if style.italic {
        attrs |= CellAttributes::ITALIC;
    }
    if style.underline {
        attrs |= CellAttributes::UNDERLINE;
    }
    if style.dim {
        attrs |= CellAttributes::DIM;
    }
    if style.strikethrough {
        attrs |= CellAttributes::STRIKETHROUGH;
    }
    if style.inverse {
        attrs |= CellAttributes::INVERSE;
    }
    if style.hidden {
        attrs |= CellAttributes::HIDDEN;
    }
    attrs
}

// ═══════════════════════════════════════════════════════════════════════════════
// === pipeline.rs ===
// ═══════════════════════════════════════════════════════════════════════════════

/// Priority level for render pass ordering.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum PassPriority {
    /// Runs first — ideal for pre-processing (e.g. color adjustments).
    First = 0,
    /// Runs early in the pipeline.
    Early = 1,
    /// Default priority for most effects.
    Normal = 2,
    /// Runs late — ideal for overlay effects.
    Late = 3,
    /// Runs last — ideal for debug overlays, accessibility filters.
    Last = 4,
}

/// Context provided to each render pass on execution.
#[derive(Debug, Clone)]
pub struct RenderPassContext {
    pub width: u16,
    pub height: u16,
    pub delta_time: f32,
    pub frame_count: u64,
    pub generation: u64,
}

impl RenderPassContext {
    pub fn new(width: u16, height: u16) -> Self {
        Self { width, height, delta_time: 0.0, frame_count: 0, generation: 0 }
    }
}

/// A single render pass that transforms a framebuffer.
pub trait RenderPass: Send {
    fn name(&self) -> &str;

    fn execute(&mut self, buffer: &mut FrameBuffer, ctx: &RenderPassContext) -> PassResult;

    fn enabled(&self) -> bool;

    fn set_enabled(&mut self, enabled: bool);

    fn priority(&self) -> PassPriority;
}

/// An ordered pipeline of render passes.
pub struct RenderPipeline {
    passes: Vec<Box<dyn RenderPass>>,
    enabled: bool,
}

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

impl RenderPipeline {
    pub fn new() -> Self {
        Self { passes: Vec::new(), enabled: true }
    }

    pub fn add_pass(&mut self, pass: Box<dyn RenderPass>) {
        self.passes.push(pass);
        self.resort();
    }

    pub fn remove_pass(&mut self, name: &str) {
        self.passes.retain(|p| p.name() != name);
    }

    pub fn get_pass(&self, name: &str) -> Option<&dyn RenderPass> {
        self.passes.iter().find(|p| p.name() == name).map(|p| p.as_ref())
    }

    pub fn get_pass_mut(&mut self, name: &str) -> Option<&mut dyn RenderPass> {
        self.passes.iter_mut().find(|p| p.name() == name).map(|p| p.as_mut() as &mut dyn RenderPass)
    }

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

    pub fn set_enabled(&mut self, enabled: bool) {
        self.enabled = enabled;
    }

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

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

    pub fn passes(&self) -> &[Box<dyn RenderPass>] {
        &self.passes
    }

    /// Execute all enabled passes in priority order.
    ///
    /// Returns `PassResult::Modified` if ANY pass modified the buffer.
    /// Short-circuits only if a pass name matches the `stop_after` parameter.
    pub fn execute(&mut self, buffer: &mut FrameBuffer, ctx: &RenderPassContext) -> PassResult {
        if !self.enabled || self.passes.is_empty() {
            return PassResult::Unchanged;
        }

        let mut any_modified = false;
        for pass in &mut self.passes {
            if !pass.enabled() {
                continue;
            }
            let result = pass.execute(buffer, ctx);
            if result == PassResult::Modified {
                any_modified = true;
            }
        }

        if any_modified { PassResult::Modified } else { PassResult::Unchanged }
    }

    fn resort(&mut self) {
        self.passes.sort_by_key(|p| p.priority());
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// === renderer.rs ===
// ═══════════════════════════════════════════════════════════════════════════════

/// Result of executing a render pass.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PassResult {
    /// The pass did not change the buffer.
    Unchanged,
    /// The pass modified the buffer.
    Modified,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderFrame {
    pub output_data: Vec<u8>,
    pub dirty_regions: Vec<DirtyRegion>,
    pub width: u16,
    pub height: u16,
}

impl RenderFrame {
    pub fn new_empty(width: u16, height: u16) -> Self {
        Self { output_data: Vec::new(), dirty_regions: Vec::new(), width, height }
    }

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct CursorState {
    pub x: u16,
    pub y: u16,
    pub visible: bool,
}

/// Convert a NodeId to a u64 for hit grid storage.
fn node_id_to_u64(id: NodeId) -> u64 {
    // SAFETY: NodeId is slotmap::DefaultKey, a transparent newtype around a
    // 64-bit generational index. Both types have identical size and layout.
    unsafe { std::mem::transmute(id) }
}

pub struct Renderer {
    width: u16,
    height: u16,
    background_color: Color,
    render_offset: u16,
    screen_mode: ScreenMode,
    layout_sync: LayoutTreeSync,
    render_tree: RenderTree,
    painter: Painter,
    snapshot: FrameBuffer,
    dirty_diff: DirtyDiff,
    backend: Box<dyn RenderBackend>,
    scheduler: Scheduler,
    pipeline: RenderPipeline,
    needs_full_repaint: bool,
    generation: u64,
    last_change_count: u64,
    cursor_state: CursorState,
    hit_grid: HitGrid,
}

impl Default for Renderer {
    fn default() -> Self {
        Self::new(80, 24)
    }
}

impl Renderer {
    pub fn new(width: u16, height: u16) -> Self {
        info!(width, height, "Renderer::new() - creating renderer");
        let vw = width as u32;
        let vh = height as u32;
        Self {
            width,
            height,
            background_color: Color::Default,
            render_offset: 0,
            screen_mode: ScreenMode::AlternateScreen,
            layout_sync: LayoutTreeSync::new(),
            render_tree: RenderTree::new(),
            painter: Painter::new(width, height),
            snapshot: FrameBuffer::new(width, height),
            dirty_diff: DirtyDiff::new(),
            backend: Box::new(AnsiBackend::new()),
            scheduler: Scheduler::default(),
            pipeline: RenderPipeline::new(),
            needs_full_repaint: true,
            generation: 0,
            last_change_count: 0,
            cursor_state: CursorState::default(),
            hit_grid: HitGrid::new(vw, vh),
        }
    }

    pub fn with_backend(width: u16, height: u16, backend: Box<dyn RenderBackend>) -> Self {
        info!(width, height, "Renderer::with_backend() - creating renderer with custom backend");
        let vw = width as u32;
        let vh = height as u32;
        Self {
            width,
            height,
            background_color: Color::Default,
            render_offset: 0,
            screen_mode: ScreenMode::AlternateScreen,
            layout_sync: LayoutTreeSync::new(),
            render_tree: RenderTree::new(),
            painter: Painter::new(width, height),
            snapshot: FrameBuffer::new(width, height),
            dirty_diff: DirtyDiff::new(),
            backend,
            scheduler: Scheduler::default(),
            pipeline: RenderPipeline::new(),
            needs_full_repaint: true,
            generation: 0,
            last_change_count: 0,
            cursor_state: CursorState::default(),
            hit_grid: HitGrid::new(vw, vh),
        }
    }

    pub fn set_background_color(&mut self, color: Color) {
        self.background_color = color;
        self.painter.set_background_color(color);
        self.needs_full_repaint = true;
    }

    pub fn background_color(&self) -> Color {
        self.background_color
    }

    pub fn with_fps(fps: u32) -> Self {
        Self { scheduler: Scheduler::with_fps(fps), ..Self::new(80, 24) }
    }

    pub fn set_cursor_position(&mut self, x: u16, y: u16, visible: bool) {
        self.cursor_state = CursorState { x, y, visible };
    }

    pub fn cursor_state(&self) -> &CursorState {
        &self.cursor_state
    }

    pub fn screen_mode(&self) -> &ScreenMode {
        &self.screen_mode
    }

    pub fn set_screen_mode(&mut self, mode: ScreenMode) {
        self.screen_mode = mode;
        self.render_offset = mode.render_offset(self.height);
        self.needs_full_repaint = true;
        info!(?mode, offset = self.render_offset, "Renderer::set_screen_mode()");
    }

    pub fn render_offset(&self) -> u16 {
        self.render_offset
    }

    /// Returns the usable viewport height accounting for screen mode.
    pub fn viewport_height(&self) -> u16 {
        self.screen_mode.viewport_height(self.height)
    }

    /// Populate the hit grid from the current render tree.
    /// Each visible render object writes its NodeId to the grid.
    fn populate_hit_grid(&mut self) {
        self.hit_grid.clear_scissors();
        self.hit_grid.clear_next();
        for obj in self.render_tree.objects() {
            let handle = node_id_to_u64(obj.id);
            self.hit_grid.add(
                obj.bounds.x as i32,
                obj.bounds.y as i32,
                obj.bounds.width as u32,
                obj.bounds.height as u32,
                handle,
            );
        }
    }

    /// Write a renderable's bounds to nextHitGrid for the upcoming frame.
    pub fn hit_grid_add(&mut self, x: u16, y: u16, width: u16, height: u16, id: u64) {
        self.hit_grid.add(x as i32, y as i32, width as u32, height as u32, id);
    }

    /// Clear currentHitGrid for immediate rebuild.
    pub fn hit_grid_clear_current(&mut self) {
        self.hit_grid.clear_current();
    }

    /// Return whether the hit grid changed during the last render.
    pub fn hit_grid_dirty(&self) -> bool {
        self.hit_grid.is_dirty()
    }

    /// Return the renderable ID at screen position (x, y), or 0 if none.
    pub fn hit_grid_check(&self, x: u32, y: u32) -> u64 {
        self.hit_grid.check(x, y)
    }

    /// Push a scissor rect for hit grid clipping during direct rebuild.
    pub fn hit_grid_push_scissor(&mut self, x: i32, y: i32, width: u32, height: u32) {
        self.hit_grid.push_scissor(x, y, width, height);
    }

    /// Pop the current scissor rect.
    pub fn hit_grid_pop_scissor(&mut self) {
        self.hit_grid.pop_scissor();
    }

    /// Clear all hit grid scissor rects.
    pub fn hit_grid_clear_scissors(&mut self) {
        self.hit_grid.clear_scissors();
    }

    /// Write directly to currentHitGrid with scissor clipping (immediate, no render needed).
    pub fn hit_grid_add_current_clipped(&mut self, x: u16, y: u16, width: u16, height: u16, id: u64) {
        self.hit_grid.add_current(x as i32, y as i32, width as u32, height as u32, id);
    }

    pub fn hit_grid_dump(&self) -> String {
        let (w, h) = self.hit_grid.dimensions();
        let mut s = String::new();
        for y in 0..h {
            for x in 0..w {
                let id = self.hit_grid.check(x, y);
                let ch = if id == 0 { '.' } else { char::from_digit((id % 10) as u32, 10).unwrap_or('?') };
                s.push(ch);
            }
            s.push('\n');
        }
        s
    }

    pub fn resize(&mut self, width: u16, height: u16) {
        let old_w = self.width;
        let old_h = self.height;
        self.width = width;
        self.height = height;
        self.render_offset = self.screen_mode.render_offset(height);
        self.painter.resize(width, height);
        self.snapshot.resize(width, height);
        self.hit_grid.resize(width as u32, height as u32);
        self.needs_full_repaint = true;
        debug!(
            old_width = old_w,
            old_height = old_h,
            new_width = width,
            new_height = height,
            render_offset = self.render_offset,
            "Renderer::resize() - framebuffer resized"
        );
    }

    pub fn request_frame(&mut self) {
        self.scheduler.request_frame();
    }

    pub fn should_render(&self) -> FrameStatus {
        self.scheduler.status()
    }

    pub fn render(&mut self, arena: &mut NodeArena) -> RenderFrame {
        self.generation += 1;

        let change_count = arena.change_count();
        if !self.needs_full_repaint && change_count == self.last_change_count {
            debug!(generation = self.generation, "Renderer::render() - skipping frame (no changes)");
            return RenderFrame::new_empty(self.width, self.height);
        }
        self.last_change_count = change_count;

        debug!(
            generation = self.generation,
            node_count = arena.len(),
            needs_full_repaint = self.needs_full_repaint,
            "Renderer::render() - rendering frame"
        );

        self.layout_sync.sync_full(arena);

        let root_id = arena.root();
        for (id, _node) in arena.iter() {
            self.layout_sync.sync_children(arena, id);
        }
        let vp_height = self.viewport_height();
        let _ = self.layout_sync.compute(root_id, self.width, vp_height);
        crate::diag!(|d| d.inc_layout_computations());

        let vp = Viewport::new(0, 0, self.width, vp_height);
        build_render_tree_with_viewport(arena, self.layout_sync.results(), Some(&vp), &mut self.render_tree);

        let ctx = crate::taffy::PaintContext::new(self.width, vp_height);
        self.populate_hit_grid();
        self.painter.paint(&self.render_tree, &ctx);

        // Post-processing: execute render passes on the painter's framebuffer
        let pp_ctx = RenderPassContext {
            width: self.width,
            height: self.height,
            delta_time: (1.0 / 60.0),
            frame_count: self.generation,
            generation: self.generation,
        };
        let pp_result = self.pipeline.execute(self.painter.buffer_mut(), &pp_ctx);

        let dirty_regions = if pp_result == PassResult::Modified {
            self.dirty_diff.compute(self.painter.buffer(), &self.snapshot, self.generation);
            self.dirty_diff.regions().to_vec()
        } else if self.needs_full_repaint {
            self.dirty_diff.compute_full_repaint(self.width, self.height);
            self.needs_full_repaint = false;
            self.dirty_diff.regions().to_vec()
        } else {
            self.dirty_diff.compute(self.painter.buffer(), &self.snapshot, self.generation);
            self.dirty_diff.regions().to_vec()
        };

        self.backend.begin_frame(&self.screen_mode, self.width, self.height);
        self.backend.encode(self.painter.buffer(), &dirty_regions);
        self.backend.end_frame(&self.screen_mode);

        if self.cursor_state.visible {
            self.backend.set_cursor_position(self.cursor_state.x, self.cursor_state.y, true);
        }

        self.snapshot.copy_from(self.painter.buffer());

        // Swap hit grid: next (built during render) becomes current for hit testing
        self.hit_grid_clear_scissors();
        self.hit_grid.swap();

        self.scheduler.end_frame();

        arena.clear_dirty_flags();

        debug!(
            generation = self.generation,
            dirty_region_count = dirty_regions.len(),
            output_bytes = self.backend.finish().len(),
            "Renderer::render() - frame complete"
        );

        RenderFrame {
            output_data: self.backend.finish().to_vec(),
            dirty_regions,
            width: self.width,
            height: self.height,
        }
    }

    pub fn render_full(&mut self, arena: &mut NodeArena) -> RenderFrame {
        self.needs_full_repaint = true;
        self.render(arena)
    }

    pub fn set_backend(&mut self, backend: Box<dyn RenderBackend>) {
        self.backend = backend;
    }

    pub fn backend(&self) -> &dyn RenderBackend {
        self.backend.as_ref()
    }

    pub fn layout_sync(&self) -> &LayoutTreeSync {
        &self.layout_sync
    }

    pub fn render_tree(&self) -> &RenderTree {
        &self.render_tree
    }

    pub fn framebuffer(&self) -> &FrameBuffer {
        self.painter.buffer()
    }

    pub fn scheduler(&self) -> &Scheduler {
        &self.scheduler
    }

    pub fn dimensions(&self) -> (u16, u16) {
        (self.width, self.height)
    }

    pub fn pipeline(&self) -> &RenderPipeline {
        &self.pipeline
    }

    pub fn pipeline_mut(&mut self) -> &mut RenderPipeline {
        &mut self.pipeline
    }
}

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

    #[test]
    fn render_command_variants() {
        let obj = RenderObject::new(NodeId::default());
        let cmd1 = RenderCommand::render(obj);
        assert!(matches!(cmd1, RenderCommand::Render { .. }));

        let cmd2 = RenderCommand::push_scissor(0, 0, 10, 10);
        assert!(matches!(cmd2, RenderCommand::PushScissorRect { .. }));

        let cmd3 = RenderCommand::pop_scissor();
        assert!(matches!(cmd3, RenderCommand::PopScissorRect));

        let cmd4 = RenderCommand::push_opacity(0.5);
        assert!(matches!(cmd4, RenderCommand::PushOpacity { .. }));

        let cmd5 = RenderCommand::pop_opacity();
        assert!(matches!(cmd5, RenderCommand::PopOpacity));
    }

    #[test]
    fn painter_opacity_stack() {
        let mut painter = Painter::new(10, 10);

        assert_eq!(painter.current_opacity(), 1.0);

        painter.push_opacity(0.5);
        assert_eq!(painter.current_opacity(), 0.5);

        painter.push_opacity(0.5);
        assert_eq!(painter.current_opacity(), 0.25);

        painter.pop_opacity();
        assert_eq!(painter.current_opacity(), 0.5);

        painter.pop_opacity();
        assert_eq!(painter.current_opacity(), 1.0);
    }

    #[test]
    fn painter_scissor_stack() {
        let mut painter = Painter::new(20, 20);

        assert!(painter.current_scissor().is_none());

        painter.push_scissor(0, 0, 10, 10);
        let clip = painter.current_scissor().unwrap();
        assert_eq!(clip.x, 0);
        assert_eq!(clip.width, 10);

        painter.push_scissor(5, 5, 10, 10);
        let clip = painter.current_scissor().unwrap();
        assert_eq!(clip.x, 5);
        assert_eq!(clip.width, 5);

        painter.pop_scissor();
        let clip = painter.current_scissor().unwrap();
        assert_eq!(clip.x, 0);

        painter.pop_scissor();
        assert!(painter.current_scissor().is_none());
    }

    #[test]
    fn render_tree_collect_commands() {
        let mut tree = RenderTree::new();

        let mut obj1 = RenderObject::new(NodeId::default());
        obj1.opacity = 0.8;
        obj1.z_index = 1;
        tree.push(obj1);

        let mut obj2 = RenderObject::new(NodeId::default());
        obj2.opacity = 1.0;
        obj2.clip = Some(ClipBounds::new(0, 0, 10, 10));
        obj2.z_index = 0;
        tree.push(obj2);

        let commands = tree.collect_commands();
        assert!(!commands.is_empty());
    }

    #[test]
    fn render_tree_command_caching() {
        let mut tree = RenderTree::new();

        let mut obj = RenderObject::new(NodeId::default());
        obj.opacity = 0.8;
        tree.push(obj);

        let commands1 = tree.collect_commands_cached(1, 1);
        let commands2 = tree.collect_commands_cached(1, 1);
        assert_eq!(commands1.len(), commands2.len());

        let commands3 = tree.collect_commands_cached(2, 1);
        assert!(!commands3.is_empty());

        let commands4 = tree.collect_commands_cached(2, 2);
        assert!(!commands4.is_empty());
    }

    #[test]
    fn render_tree_invalidate_cache() {
        let mut tree = RenderTree::new();

        let obj = RenderObject::new(NodeId::default());
        tree.push(obj);

        let _ = tree.collect_commands_cached(1, 1);
        tree.invalidate_cache();

        let commands = tree.collect_commands_cached(1, 1);
        assert!(!commands.is_empty());
    }

    // ─── AnsiBackend Tests ────────────────────────────────────────

    #[test]
    fn ansi_backend_sync_sequences() {
        let mut backend = AnsiBackend::new();
        backend.begin_sync();
        let output = String::from_utf8_lossy(backend.finish());
        assert!(output.contains("?2026h"), "should enable sync: {output}");
    }

    #[test]
    fn ansi_backend_end_sync() {
        let mut backend = AnsiBackend::new();
        backend.end_sync();
        let output = String::from_utf8_lossy(backend.finish());
        assert!(output.contains("?2026l"), "should disable sync: {output}");
    }

    #[test]
    fn ansi_backend_alternate_screen_enter() {
        let mut backend = AnsiBackend::new();
        backend.enter_alternate_screen();
        let output = String::from_utf8_lossy(backend.finish());
        assert!(output.contains("?1049h"), "should enter alt screen: {output}");
    }

    #[test]
    fn ansi_backend_alternate_screen_exit() {
        let mut backend = AnsiBackend::new();
        backend.exit_alternate_screen();
        let output = String::from_utf8_lossy(backend.finish());
        assert!(output.contains("?1049l"), "should exit alt screen: {output}");
    }

    #[test]
    fn ansi_backend_scroll_region() {
        let mut backend = AnsiBackend::new();
        backend.set_scroll_region(5, 24);
        let output = String::from_utf8_lossy(backend.finish());
        assert!(output.contains("1;5r"), "scroll region should be 1;5r: {output}");
    }

    #[test]
    fn ansi_backend_reset_scroll_region() {
        let mut backend = AnsiBackend::new();
        backend.reset_scroll_region(24);
        let output = String::from_utf8_lossy(backend.finish());
        assert!(output.contains("1;24r"), "reset should be 1;24r: {output}");
    }

    #[test]
    fn ansi_backend_begin_frame_alternate_screen() {
        let mut backend = AnsiBackend::new();
        // previous_mode starts as AlternateScreen, so first call with the same mode
        // does not emit transition. Emit a transition from MainScreen instead.
        backend.begin_frame(&ScreenMode::AlternateScreen, 80, 24);
        let output = String::from_utf8_lossy(backend.finish());
        assert!(output.contains("?2026h"), "should begin sync");
    }

    #[test]
    fn ansi_backend_emits_osc8_hyperlink() {
        let mut fb = FrameBuffer::new(3, 1);
        let id = fb.alloc_link("https://example.com", None);
        fb.set(0, 0, Cell::new('A').with_link(id));
        fb.set(1, 0, Cell::new('B').with_link(id));
        fb.set(2, 0, Cell::new('C')); // no link

        let mut backend = AnsiBackend::new();
        backend.encode(&fb, &[DirtyRegion::new(0, 0, 3, 1)]);
        let output = String::from_utf8_lossy(backend.finish());

        // Opens the link before the linked run...
        assert!(output.contains("\x1b]8;;https://example.com\x1b\\"), "should open OSC 8: {output:?}");
        // ...and closes it (empty URI) before the unlinked cell.
        assert!(output.contains("\x1b]8;;\x1b\\"), "should close OSC 8: {output:?}");
    }

    #[test]
    fn ansi_backend_no_osc8_without_links() {
        let mut fb = FrameBuffer::new(2, 1);
        fb.set(0, 0, Cell::new('A'));
        fb.set(1, 0, Cell::new('B'));

        let mut backend = AnsiBackend::new();
        backend.encode(&fb, &[DirtyRegion::new(0, 0, 2, 1)]);
        let output = String::from_utf8_lossy(backend.finish());
        assert!(!output.contains("\x1b]8;"), "no OSC 8 when no links: {output:?}");
    }

    #[test]
    fn ansi_backend_split_footer_sets_scroll_region() {
        let mut backend = AnsiBackend::new();
        // previous_mode starts as AlternateScreen, so a SplitFooter is a change.
        backend.begin_frame(&ScreenMode::SplitFooter { height: 3 }, 80, 24);
        let output = String::from_utf8_lossy(backend.finish());
        // Footer starts at row 24-3 = 21; scroll region is DECSTBM 1;21r.
        assert!(output.contains("1;21r"), "should reserve footer scroll region: {output:?}");
    }

    #[test]
    fn ansi_backend_main_screen_resets_scroll_region() {
        let mut backend = AnsiBackend::new();
        // Transition away from the default alternate screen to main screen.
        backend.begin_frame(&ScreenMode::MainScreen, 80, 24);
        let output = String::from_utf8_lossy(backend.finish());
        assert!(output.contains("1;24r"), "main screen resets full scroll region: {output:?}");
    }

    #[test]
    fn ansi_backend_enter_alternate_screen() {
        let mut backend = AnsiBackend::new();
        // Simulate transition from main to alternate screen
        backend.begin_frame(&ScreenMode::MainScreen, 80, 24);
        backend.finish(); // flush first frame output
        backend.begin_frame(&ScreenMode::AlternateScreen, 80, 24);
        let output = String::from_utf8_lossy(backend.finish());
        assert!(output.contains("?1049h"), "should enter alt screen: {output}");
    }

    #[test]
    fn ansi_backend_begin_frame_split_footer() {
        let mut backend = AnsiBackend::new();
        backend.begin_frame(&ScreenMode::SplitFooter { height: 3 }, 80, 24);
        let output = String::from_utf8_lossy(backend.finish());
        assert!(output.contains("?2026h"), "should begin sync");
        // Should set scroll region leaving 3 rows for footer
        assert!(output.contains("1;21r"), "scroll region should end at row 21: {output}");
    }

    #[test]
    fn ansi_backend_end_frame_emits_sync_end() {
        let mut backend = AnsiBackend::new();
        backend.end_frame(&ScreenMode::AlternateScreen);
        let output = String::from_utf8_lossy(backend.finish());
        assert!(output.contains("?2026l"), "should end sync: {output}");
    }

    // ─── Renderer HitGrid Integration Tests ───────────────────────

    #[test]
    fn renderer_hit_grid_populate_and_check() {
        let mut renderer = Renderer::new(80, 24);
        let _vw = 80u32;
        let _vh = 24u32;

        // Add some renderable areas
        renderer.hit_grid_add(0, 0, 10, 10, 1001);
        renderer.hit_grid_add(10, 10, 10, 10, 1002);
        renderer.hit_grid_add_current_clipped(5, 5, 5, 5, 1003);

        // Check that next grid has the data
        // (swap needed since add writes to next buffer)
        let changed = renderer.hit_grid.swap();
        assert!(changed, "hit grid should be dirty after adding items");

        assert_eq!(renderer.hit_grid_check(0, 0), 1001);
        assert_eq!(renderer.hit_grid_check(5, 5), 1001);
        assert_eq!(renderer.hit_grid_check(9, 9), 1001);
        assert_eq!(renderer.hit_grid_check(10, 10), 1002);
        assert_eq!(renderer.hit_grid_check(19, 19), 1002);
        // Outside any registered area
        assert_eq!(renderer.hit_grid_check(20, 20), 0);
    }

    #[test]
    fn renderer_hit_grid_scissor_stack() {
        let mut renderer = Renderer::new(80, 40);

        renderer.hit_grid_push_scissor(10, 10, 20, 20);
        // This add should be clipped to the scissor rect
        renderer.hit_grid_add(0, 0, 80, 40, 42);
        renderer.hit_grid.swap();

        // Should only have data inside the scissor rect
        assert_eq!(renderer.hit_grid_check(10, 10), 42);
        assert_eq!(renderer.hit_grid_check(29, 29), 42);
        // Outside scissor
        assert_eq!(renderer.hit_grid_check(9, 9), 0);
        assert_eq!(renderer.hit_grid_check(30, 30), 0);

        renderer.hit_grid_pop_scissor();
    }

    #[test]
    fn renderer_hit_grid_clear_and_dirty() {
        let mut renderer = Renderer::new(80, 24);
        renderer.hit_grid_add(0, 0, 10, 10, 1);
        renderer.hit_grid.swap();
        assert!(renderer.hit_grid_dirty());

        renderer.hit_grid_clear_current();
        assert_eq!(renderer.hit_grid_check(0, 0), 0);
    }

    #[test]
    fn renderer_hit_grid_clear_scissors() {
        let mut renderer = Renderer::new(80, 24);
        renderer.hit_grid_push_scissor(5, 5, 10, 10);
        renderer.hit_grid_clear_scissors();
        // After clearing scissors, add should affect full screen
        renderer.hit_grid_add(0, 0, 80, 24, 1);
        renderer.hit_grid.swap();
        assert_eq!(renderer.hit_grid_check(0, 0), 1);
        assert_eq!(renderer.hit_grid_check(79, 23), 1);
    }

    #[test]
    fn renderer_hit_grid_dump() {
        let mut renderer = Renderer::new(80, 24);
        renderer.hit_grid_add(0, 0, 1, 1, 101);
        renderer.hit_grid.swap();
        let dump = renderer.hit_grid_dump();
        assert!(!dump.is_empty());
        // Should contain the ID we added (101 -> '1')
        assert!(dump.starts_with('1'), "first cell should be '1': {dump}");
    }
}