opentui_rust 0.2.1

High-performance terminal UI rendering engine with alpha blending and diffed buffers
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
//! Text buffer view with viewport and wrapping.
//!
//! # Grapheme Handling
//!
//! When rendering text that may contain multi-codepoint graphemes (emoji, ZWJ sequences,
//! combining characters), use [`TextBufferView::render_to_with_pool`] to preserve the
//! grapheme content. The simpler [`TextBufferView::render_to`] method creates placeholder
//! cells that preserve display width but lose the actual grapheme string.
//!
//! See the method documentation for details on when to use each variant.

// Complex rendering logic naturally has long functions
#![allow(clippy::too_many_lines)]
// Closures with method references are more readable in context
#![allow(clippy::redundant_closure_for_method_calls)]
// if-let-else is clearer than map_or_else for mutable pool reborrowing
#![allow(clippy::option_if_let_else)]

use crate::buffer::OptimizedBuffer;
use crate::cell::{Cell, CellContent, GraphemeId};
use crate::color::Rgba;
use crate::style::Style;
use crate::text::TextBuffer;
use crate::unicode::{display_width_char_with_method, display_width_with_method};
use std::cell::RefCell;

/// Text wrapping mode.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WrapMode {
    /// No wrapping - lines extend beyond viewport.
    #[default]
    None,
    /// Wrap at character boundaries.
    Char,
    /// Wrap at word boundaries.
    Word,
}

/// Viewport configuration.
#[derive(Clone, Copy, Debug, Default)]
pub struct Viewport {
    pub x: u32,
    pub y: u32,
    pub width: u32,
    pub height: u32,
}

impl Viewport {
    /// Create a new viewport.
    #[must_use]
    pub fn new(x: u32, y: u32, width: u32, height: u32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }
}

/// Selection range.
#[derive(Clone, Copy, Debug, Default)]
pub struct Selection {
    pub start: usize,
    pub end: usize,
    pub style: Style,
}

impl Selection {
    /// Create a new selection.
    #[must_use]
    pub fn new(start: usize, end: usize, style: Style) -> Self {
        Self { start, end, style }
    }

    /// Check if empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.start == self.end
    }

    /// Get normalized (start <= end) selection.
    #[must_use]
    pub fn normalized(&self) -> Self {
        if self.start <= self.end {
            *self
        } else {
            Self {
                start: self.end,
                end: self.start,
                style: self.style,
            }
        }
    }

    /// Check if position is within selection.
    #[must_use]
    pub fn contains(&self, pos: usize) -> bool {
        let norm = self.normalized();
        pos >= norm.start && pos < norm.end
    }
}

/// Local (viewport) selection based on screen coordinates.
#[derive(Clone, Copy, Debug, Default)]
pub struct LocalSelection {
    pub anchor_x: u32,
    pub anchor_y: u32,
    pub focus_x: u32,
    pub focus_y: u32,
    pub style: Style,
}

impl LocalSelection {
    /// Create a new local selection.
    #[must_use]
    pub fn new(anchor_x: u32, anchor_y: u32, focus_x: u32, focus_y: u32, style: Style) -> Self {
        Self {
            anchor_x,
            anchor_y,
            focus_x,
            focus_y,
            style,
        }
    }

    /// Normalize selection rectangle.
    #[must_use]
    pub fn normalized(&self) -> (u32, u32, u32, u32) {
        let min_x = self.anchor_x.min(self.focus_x);
        let max_x = self.anchor_x.max(self.focus_x);
        let min_y = self.anchor_y.min(self.focus_y);
        let max_y = self.anchor_y.max(self.focus_y);
        (min_x, min_y, max_x, max_y)
    }
}

/// View into a text buffer with viewport and rendering options.
pub struct TextBufferView<'a> {
    buffer: &'a TextBuffer,
    viewport: Viewport,
    wrap_mode: WrapMode,
    wrap_width: Option<u32>,
    scroll_x: u32,
    scroll_y: u32,
    selection: Option<Selection>,
    local_selection: Option<LocalSelection>,
    tab_indicator: Option<char>,
    tab_indicator_color: Rgba,
    truncate: bool,
    line_cache: RefCell<Option<LineCache>>,
}

#[derive(Clone, Debug)]
struct VirtualLine {
    source_line: usize,
    byte_start: usize,
    byte_end: usize,
    width: usize,
    is_wrap: bool,
}

/// Cached line layout information for wrapped text.
#[derive(Clone, Debug, Default)]
pub struct LineInfo {
    /// Byte offset where each virtual line starts.
    pub starts: Vec<usize>,
    /// Byte offset where each virtual line ends (exclusive).
    pub ends: Vec<usize>,
    /// Display width of each virtual line.
    pub widths: Vec<usize>,
    /// Source line index for each virtual line.
    pub sources: Vec<usize>,
    /// Whether the line is a wrapped continuation.
    pub wraps: Vec<bool>,
    /// Maximum line width across all virtual lines.
    pub max_width: usize,
}

impl LineInfo {
    /// Get the number of virtual lines.
    #[must_use]
    pub fn virtual_line_count(&self) -> usize {
        self.starts.len()
    }

    /// Map a source (logical) line to its first virtual line index.
    ///
    /// Returns the index of the first virtual line that corresponds to
    /// the given source line, or `None` if the source line doesn't exist.
    #[must_use]
    pub fn source_to_virtual(&self, source_line: usize) -> Option<usize> {
        self.sources.iter().position(|&s| s == source_line)
    }

    /// Map a virtual line index to its source (logical) line.
    ///
    /// Returns the source line index for the given virtual line,
    /// or `None` if the virtual line index is out of bounds.
    #[must_use]
    pub fn virtual_to_source(&self, virtual_line: usize) -> Option<usize> {
        self.sources.get(virtual_line).copied()
    }

    /// Get the byte range for a virtual line.
    ///
    /// Returns `(byte_start, byte_end)` for the given virtual line index,
    /// or `None` if the index is out of bounds.
    #[must_use]
    pub fn virtual_line_byte_range(&self, virtual_line: usize) -> Option<(usize, usize)> {
        let start = *self.starts.get(virtual_line)?;
        let end = *self.ends.get(virtual_line)?;
        Some((start, end))
    }

    /// Get the display width of a virtual line.
    #[must_use]
    pub fn virtual_line_width(&self, virtual_line: usize) -> Option<usize> {
        self.widths.get(virtual_line).copied()
    }

    /// Check if a virtual line is a wrapped continuation.
    #[must_use]
    pub fn is_continuation(&self, virtual_line: usize) -> Option<bool> {
        self.wraps.get(virtual_line).copied()
    }

    /// Count virtual lines for a given source line.
    #[must_use]
    pub fn virtual_lines_for_source(&self, source_line: usize) -> usize {
        self.sources.iter().filter(|&&s| s == source_line).count()
    }

    /// Get the maximum source line index.
    #[must_use]
    pub fn max_source_line(&self) -> Option<usize> {
        self.sources.iter().max().copied()
    }
}

/// Measurement result for a given viewport size.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TextMeasure {
    pub line_count: usize,
    pub max_width: usize,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct LineCacheKey {
    wrap_mode: WrapMode,
    wrap_width_override: Option<u32>,
    viewport_width: u32,
    tab_width: u8,
    width_method: crate::unicode::WidthMethod,
    buffer_revision: u64,
}

#[derive(Clone, Debug)]
struct LineCache {
    key: LineCacheKey,
    virtual_lines: Vec<VirtualLine>,
    info: LineInfo,
}

impl<'a> TextBufferView<'a> {
    /// Create a new view of a text buffer.
    #[must_use]
    pub fn new(buffer: &'a TextBuffer) -> Self {
        Self {
            buffer,
            viewport: Viewport::default(),
            wrap_mode: WrapMode::None,
            wrap_width: None,
            scroll_x: 0,
            scroll_y: 0,
            selection: None,
            local_selection: None,
            tab_indicator: None,
            tab_indicator_color: Rgba::WHITE,
            truncate: false,
            line_cache: RefCell::new(None),
        }
    }

    /// Set the viewport.
    #[must_use]
    pub fn viewport(mut self, x: u32, y: u32, width: u32, height: u32) -> Self {
        self.viewport = Viewport::new(x, y, width, height);
        self.clear_line_cache();
        self
    }

    /// Set the wrap mode.
    #[must_use]
    pub fn wrap_mode(mut self, mode: WrapMode) -> Self {
        self.wrap_mode = mode;
        self.clear_line_cache();
        self
    }

    /// Set explicit wrap width (overrides viewport width when wrapping).
    #[must_use]
    pub fn wrap_width(mut self, width: u32) -> Self {
        self.wrap_width = Some(width);
        self.clear_line_cache();
        self
    }

    /// Set scroll position.
    #[must_use]
    pub fn scroll(mut self, x: u32, y: u32) -> Self {
        self.scroll_x = x;
        self.scroll_y = y;
        self
    }

    /// Set tab indicator character and color.
    #[must_use]
    pub fn tab_indicator(mut self, ch: char, color: Rgba) -> Self {
        self.tab_indicator = Some(ch);
        self.tab_indicator_color = color;
        self
    }

    /// Enable or disable truncation.
    #[must_use]
    pub fn truncate(mut self, enabled: bool) -> Self {
        self.truncate = enabled;
        self
    }

    /// Set selection.
    pub fn set_selection(&mut self, start: usize, end: usize, style: Style) {
        self.selection = Some(Selection::new(start, end, style));
    }

    /// Clear selection.
    pub fn clear_selection(&mut self) {
        self.selection = None;
    }

    /// Set a local (viewport) selection.
    pub fn set_local_selection(
        &mut self,
        anchor_x: u32,
        anchor_y: u32,
        focus_x: u32,
        focus_y: u32,
        style: Style,
    ) {
        self.local_selection = Some(LocalSelection::new(
            anchor_x, anchor_y, focus_x, focus_y, style,
        ));
    }

    /// Clear local selection.
    pub fn clear_local_selection(&mut self) {
        self.local_selection = None;
    }

    fn clear_line_cache(&self) {
        self.line_cache.replace(None);
    }

    /// Get selected text if any.
    #[must_use]
    pub fn selected_text(&self) -> Option<String> {
        let sel = self.selection.as_ref()?.normalized();
        if sel.is_empty() {
            return None;
        }

        let max = self.buffer.len_chars();
        let start = sel.start.min(max);
        let end = sel.end.min(max);
        if start >= end {
            return None;
        }
        Some(self.buffer.rope().slice(start..end).to_string())
    }

    fn effective_wrap_width(&self) -> Option<usize> {
        if self.wrap_mode == WrapMode::None || self.viewport.width == 0 {
            return None;
        }
        let width = self.wrap_width.unwrap_or(self.viewport.width).max(1);
        Some(width as usize)
    }

    fn effective_wrap_width_for(&self, width: Option<u32>) -> Option<usize> {
        if self.wrap_mode == WrapMode::None {
            return None;
        }
        let base_width = width.unwrap_or(self.viewport.width);
        if base_width == 0 {
            return None;
        }
        let width = self.wrap_width.unwrap_or(base_width).max(1);
        Some(width as usize)
    }

    fn line_cache_key(&self) -> LineCacheKey {
        LineCacheKey {
            wrap_mode: self.wrap_mode,
            wrap_width_override: self.wrap_width,
            viewport_width: self.viewport.width,
            tab_width: self.buffer.tab_width(),
            width_method: self.buffer.width_method(),
            buffer_revision: self.buffer.revision(),
        }
    }

    fn line_cache(&self) -> std::cell::Ref<'_, LineCache> {
        let key = self.line_cache_key();
        let needs_refresh = self
            .line_cache
            .borrow()
            .as_ref()
            .is_none_or(|cache| cache.key != key);

        if needs_refresh {
            let virtual_lines = self.build_virtual_lines_for(self.effective_wrap_width());
            let info = Self::line_info_from_virtual_lines(&virtual_lines);
            *self.line_cache.borrow_mut() = Some(LineCache {
                key,
                virtual_lines,
                info,
            });
        }

        std::cell::Ref::map(self.line_cache.borrow(), |cache| {
            cache.as_ref().expect("line cache should exist")
        })
    }

    fn line_info_from_virtual_lines(virtual_lines: &[VirtualLine]) -> LineInfo {
        let mut info = LineInfo::default();
        for line in virtual_lines {
            info.starts.push(line.byte_start);
            info.ends.push(line.byte_end);
            info.widths.push(line.width);
            info.sources.push(line.source_line);
            info.wraps.push(line.is_wrap);
            info.max_width = info.max_width.max(line.width);
        }
        info
    }

    fn build_virtual_lines_for(&self, wrap_width: Option<usize>) -> Vec<VirtualLine> {
        use unicode_segmentation::UnicodeSegmentation;

        let mut lines = Vec::new();
        let method = self.buffer.width_method();
        let tab_width = self.buffer.tab_width().max(1) as usize;

        for line_idx in 0..self.buffer.len_lines() {
            let Some(line) = self.buffer.line(line_idx) else {
                continue;
            };
            let line = line.trim_end_matches('\n').trim_end_matches('\r');

            let line_start_char = self.buffer.rope().line_to_char(line_idx);
            let line_start_byte = self.buffer.rope().char_to_byte(line_start_char);

            if line.is_empty() {
                lines.push(VirtualLine {
                    source_line: line_idx,
                    byte_start: line_start_byte,
                    byte_end: line_start_byte,
                    width: 0,
                    is_wrap: false,
                });
                continue;
            }

            let Some(wrap_width) = wrap_width else {
                let width = display_width_with_method(line, method);
                lines.push(VirtualLine {
                    source_line: line_idx,
                    byte_start: line_start_byte,
                    byte_end: line_start_byte + line.len(),
                    width,
                    is_wrap: false,
                });
                continue;
            };

            let graphemes: Vec<(usize, &str)> = line.grapheme_indices(true).collect();
            let mut start_byte = 0usize;
            let mut current_width = 0usize;
            let mut last_break: Option<(usize, usize, usize)> = None; // (break_byte, width, index)
            let mut i = 0usize;

            while i < graphemes.len() {
                let (byte_idx, grapheme) = graphemes[i];
                if byte_idx < start_byte {
                    i += 1;
                    continue;
                }

                let g_width = if grapheme == "\t" {
                    let offset = current_width % tab_width;
                    tab_width - offset
                } else {
                    display_width_with_method(grapheme, method)
                };

                let is_ws = grapheme.chars().all(|c| c.is_whitespace());
                if self.wrap_mode == WrapMode::Word && is_ws {
                    last_break = Some((byte_idx + grapheme.len(), current_width + g_width, i + 1));
                }

                if current_width + g_width > wrap_width && current_width > 0 {
                    let (break_byte, break_width, break_index) = if self.wrap_mode == WrapMode::Word
                    {
                        last_break.unwrap_or((byte_idx, current_width, i))
                    } else {
                        (byte_idx, current_width, i)
                    };

                    lines.push(VirtualLine {
                        source_line: line_idx,
                        byte_start: line_start_byte + start_byte,
                        byte_end: line_start_byte + break_byte,
                        width: break_width,
                        is_wrap: start_byte > 0,
                    });

                    start_byte = break_byte;
                    current_width = 0;
                    last_break = None;
                    i = break_index;

                    if self.wrap_mode == WrapMode::Word {
                        while i < graphemes.len() {
                            let (b, g) = graphemes[i];
                            if b < start_byte {
                                i += 1;
                                continue;
                            }
                            if g.chars().all(|c| c.is_whitespace()) {
                                start_byte = b + g.len();
                                i += 1;
                            } else {
                                break;
                            }
                        }
                    }

                    continue;
                }

                current_width += g_width;
                i += 1;
            }

            if start_byte <= line.len() {
                lines.push(VirtualLine {
                    source_line: line_idx,
                    byte_start: line_start_byte + start_byte,
                    byte_end: line_start_byte + line.len(),
                    width: current_width,
                    is_wrap: start_byte > 0,
                });
            }
        }

        lines
    }

    /// Compute visual (wrapped) position for a character offset.
    #[must_use]
    pub fn visual_position_for_offset(&self, char_offset: usize) -> (u32, u32) {
        use unicode_segmentation::UnicodeSegmentation;

        let rope = self.buffer.rope();
        let byte_offset = rope.char_to_byte(char_offset);
        let cache = self.line_cache();
        let method = self.buffer.width_method();
        let tab_width = self.buffer.tab_width().max(1) as usize;

        for (row, vline) in cache.virtual_lines.iter().enumerate() {
            let is_last_line = row == cache.virtual_lines.len() - 1;
            if byte_offset < vline.byte_start {
                return (row as u32, 0);
            }
            // Check if cursor is within this line or at its end
            // When byte_offset == byte_end (cursor at newline position), match this line
            // if it's the last line OR the next line is on a different source line
            if byte_offset > vline.byte_end {
                if !is_last_line {
                    continue;
                }
            } else if byte_offset == vline.byte_end && !is_last_line {
                let next_vline = &cache.virtual_lines[row + 1];
                if next_vline.source_line == vline.source_line {
                    // Next line is a wrap continuation of same source line, skip
                    continue;
                }
                // Next line is a new source line, cursor at end belongs here
            }

            let char_start = rope.byte_to_char(vline.byte_start);
            let char_end = rope.byte_to_char(byte_offset);
            let text = rope.slice(char_start..char_end).to_string();

            let mut width = 0usize;
            for grapheme in text.graphemes(true) {
                if grapheme == "\t" {
                    let offset = width % tab_width;
                    width += tab_width - offset;
                } else {
                    width += display_width_with_method(grapheme, method);
                }
            }

            return (row as u32, width as u32);
        }

        (0, 0)
    }

    /// Calculate the number of virtual lines (accounting for wrapping).
    #[must_use]
    pub fn virtual_line_count(&self) -> usize {
        self.line_cache().virtual_lines.len()
    }

    /// Get line layout information for the current view.
    #[must_use]
    pub fn line_info(&self) -> LineInfo {
        self.line_cache().info.clone()
    }

    /// Measure line count and max width for a given viewport size.
    #[must_use]
    pub fn measure_for_dimensions(&self, width: u32, _height: u32) -> TextMeasure {
        let wrap_width = self.effective_wrap_width_for(Some(width.max(1)));
        let virtual_lines = self.build_virtual_lines_for(wrap_width);
        let info = Self::line_info_from_virtual_lines(&virtual_lines);
        TextMeasure {
            line_count: virtual_lines.len(),
            max_width: info.max_width,
        }
    }

    /// Render the view to an output buffer.
    ///
    /// # Grapheme Handling
    ///
    /// Multi-codepoint graphemes (emoji, ZWJ sequences, characters with combining marks)
    /// are rendered as **placeholders** with only their display width preserved. The actual
    /// grapheme content is lost because no [`GraphemePool`] is provided for interning.
    ///
    /// Use [`render_to_with_pool`] instead when:
    /// - Rendering emoji or complex Unicode characters
    /// - The output buffer will be converted to ANSI sequences for terminal display
    /// - You need to recover the original grapheme strings later
    ///
    /// [`GraphemePool`]: crate::grapheme_pool::GraphemePool
    /// [`render_to_with_pool`]: Self::render_to_with_pool
    pub fn render_to(&self, output: &mut OptimizedBuffer, dest_x: i32, dest_y: i32) {
        self.render_impl(output, dest_x, dest_y, None);
    }

    /// Render the view to an output buffer, interning complex graphemes in the pool.
    ///
    /// # When to Use This Method
    ///
    /// Use this method instead of [`render_to`] when your text contains:
    /// - Emoji (e.g., 👨‍👩‍👧, 🎉)
    /// - Characters with combining marks (e.g., é composed as e + ́)
    /// - ZWJ (Zero-Width Joiner) sequences
    /// - Any multi-codepoint grapheme clusters
    ///
    /// The provided [`GraphemePool`] interns these complex graphemes, allowing them
    /// to be recovered later when generating ANSI output for terminal display.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use opentui_rust::grapheme_pool::GraphemePool;
    ///
    /// let mut pool = GraphemePool::new();
    /// let mut output = OptimizedBuffer::new(80, 24);
    /// view.render_to_with_pool(&mut output, &mut pool, 0, 0);
    /// // Graphemes in output cells can now be resolved via pool.get(id)
    /// ```
    ///
    /// [`render_to`]: Self::render_to
    /// [`GraphemePool`]: crate::grapheme_pool::GraphemePool
    pub fn render_to_with_pool(
        &self,
        output: &mut OptimizedBuffer,
        pool: &mut crate::grapheme_pool::GraphemePool,
        dest_x: i32,
        dest_y: i32,
    ) {
        self.render_impl(output, dest_x, dest_y, Some(pool));
    }

    fn render_impl(
        &self,
        output: &mut OptimizedBuffer,
        dest_x: i32,
        dest_y: i32,
        mut pool: Option<&mut crate::grapheme_pool::GraphemePool>,
    ) {
        let cache = self.line_cache();
        let virtual_lines = &cache.virtual_lines;
        let start_line = self.scroll_y as usize;
        let end_line = (start_line + self.viewport.height as usize).min(virtual_lines.len());

        for (row_offset, vline_idx) in (start_line..end_line).enumerate() {
            let vline = &virtual_lines[vline_idx];
            let dest_row = dest_y + row_offset as i32;
            if dest_row < 0 {
                continue;
            }
            // We need to re-borrow pool for each iteration if it exists
            // Since Option<&mut T> is not Copy, we need a way to pass it.
            // But we can't easily clone mutable ref.
            // However, render_virtual_line works on one line.
            // We can pass `as_deref_mut`? No, that consumes the option if we are not careful.
            // Actually, we can just pass `pool.as_deref_mut()` to re-borrow.
            self.render_virtual_line(
                output,
                dest_x,
                dest_row as u32,
                vline,
                row_offset as u32,
                pool.as_deref_mut(),
            );
        }
    }

    fn render_virtual_line(
        &self,
        output: &mut OptimizedBuffer,
        dest_x: i32,
        dest_y: u32,
        vline: &VirtualLine,
        view_row: u32,
        mut pool: Option<&mut crate::grapheme_pool::GraphemePool>,
    ) {
        use unicode_segmentation::UnicodeSegmentation;

        let rope = self.buffer.rope();
        let char_start = rope.byte_to_char(vline.byte_start);
        let char_end = rope.byte_to_char(vline.byte_end);
        let line = rope.slice(char_start..char_end).to_string();

        let mut col = 0u32;
        let method = self.buffer.width_method();

        let selection = self.selection.as_ref().map(Selection::normalized);
        let local_sel = self.local_selection;

        let max_col = self.scroll_x + self.viewport.width;

        let mut global_char_offset = char_start;
        for grapheme in line.graphemes(true) {
            // Optimization: Stop if we've gone past the viewport
            if col >= max_col {
                break;
            }

            if grapheme == "\t" {
                let tab_width = self.buffer.tab_width().max(1) as u32;
                let spaces_to_next = tab_width - (col % tab_width);
                // Get the actual style at this position (preserves syntax highlighting)
                let byte_offset = rope.char_to_byte(global_char_offset);
                let base_style = self.buffer.style_at(byte_offset);

                for space_idx in 0..spaces_to_next {
                    // Optimization: Skip if before scroll position
                    if col < self.scroll_x {
                        col += 1;
                        continue;
                    }
                    // Stop if we hit the edge (tab might straddle the edge)
                    if col >= max_col {
                        break;
                    }

                    let screen_col = (col as i32 - self.scroll_x as i32) + dest_x;
                    if screen_col >= 0 {
                        if space_idx == 0 {
                            if let Some(indicator) = self.tab_indicator {
                                // Tab indicator gets special foreground but preserves background
                                let style = base_style.with_fg(self.tab_indicator_color);
                                output.set(screen_col as u32, dest_y, Cell::new(indicator, style));
                            } else {
                                output.set(screen_col as u32, dest_y, Cell::new(' ', base_style));
                            }
                        } else {
                            output.set(screen_col as u32, dest_y, Cell::new(' ', base_style));
                        }

                        if let Some(sel) = selection {
                            if sel.contains(global_char_offset) {
                                if let Some(cell) = output.get_mut(screen_col as u32, dest_y) {
                                    cell.apply_style(sel.style);
                                }
                            }
                        }
                        if let Some(local) = local_sel {
                            let (min_x, min_y, max_x, max_y) = local.normalized();
                            let view_col = (screen_col - dest_x) as u32;
                            if view_col >= min_x
                                && view_col <= max_x
                                && view_row >= min_y
                                && view_row <= max_y
                            {
                                if let Some(cell) = output.get_mut(screen_col as u32, dest_y) {
                                    cell.apply_style(local.style);
                                }
                            }
                        }
                    }
                    col += 1;
                }
                global_char_offset += 1;
                continue;
            }

            let byte_offset = rope.char_to_byte(global_char_offset);
            let style = self.buffer.style_at(byte_offset);
            let (content, width) = if grapheme.chars().count() == 1 {
                let ch = grapheme.chars().next().unwrap();
                let w = display_width_char_with_method(ch, method);
                (CellContent::Char(ch), w)
            } else {
                let w = display_width_with_method(grapheme, method);
                if let Some(pool) = &mut pool {
                    let id = pool.intern(grapheme);
                    (CellContent::Grapheme(id), w)
                } else {
                    (CellContent::Grapheme(GraphemeId::placeholder(w as u8)), w)
                }
            };
            let mut main_cell = Cell {
                content,
                fg: style.fg.unwrap_or(Rgba::WHITE),
                bg: style.bg.unwrap_or(Rgba::TRANSPARENT),
                attributes: style.attributes,
            };

            // Optimization: Skip if completely before scroll position
            if col + (width as u32) <= self.scroll_x {
                col += width as u32;
                global_char_offset += grapheme.chars().count();
                continue;
            }

            // Apply global selection style once
            if let Some(sel) = selection {
                if sel.contains(global_char_offset) {
                    main_cell.apply_style(sel.style);
                }
            }

            // Draw parts (main + continuations)
            // Use i32 to allow negative screen coordinates (off-left) without panic
            let start_screen_col = (col as i32 - self.scroll_x as i32) + dest_x;

            for i in 0..width {
                let screen_col = start_screen_col + i as i32;

                // Check visibility for this specific column
                if screen_col >= 0 {
                    let mut cell = if i == 0 {
                        main_cell
                    } else {
                        // Continuation cell - ensure it carries background/style
                        let mut c = Cell::continuation(main_cell.bg);
                        c.fg = main_cell.fg;
                        c.attributes = main_cell.attributes;
                        c
                    };

                    // Apply local selection per-column
                    if let Some(local) = local_sel {
                        let (min_x, min_y, max_x, max_y) = local.normalized();
                        let view_col = (screen_col - dest_x) as u32;
                        if view_col >= min_x
                            && view_col <= max_x
                            && view_row >= min_y
                            && view_row <= max_y
                        {
                            cell.apply_style(local.style);
                        }
                    }

                    output.set(screen_col as u32, dest_y, cell);
                }
            }

            col += width as u32;
            global_char_offset += grapheme.chars().count();
        }

        if self.truncate && self.wrap_mode == WrapMode::None {
            let max_cols = self.viewport.width as i32;
            if vline.width as i32 > max_cols && max_cols > 0 {
                let ellipsis_col = dest_x + (max_cols - 1);
                if ellipsis_col >= 0 {
                    output.set(
                        ellipsis_col as u32,
                        dest_y,
                        Cell::new('', self.buffer.default_style()),
                    );
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::uninlined_format_args)]
    use super::*;

    #[test]
    fn test_view_basic() {
        let buffer = TextBuffer::with_text("Hello\nWorld");
        let view = TextBufferView::new(&buffer).viewport(0, 0, 80, 24);
        assert_eq!(view.virtual_line_count(), 2);
    }

    #[test]
    fn test_selection() {
        let buffer = TextBuffer::with_text("Hello, World!");
        let mut view = TextBufferView::new(&buffer);
        view.set_selection(0, 5, Style::NONE);
        assert_eq!(view.selected_text(), Some("Hello".to_string()));
    }

    #[test]
    fn test_wrap_char_count() {
        let buffer = TextBuffer::with_text("abcdefghijklmnopqrstuvwxyz");
        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 5, 10)
            .wrap_mode(WrapMode::Char);
        assert!(view.virtual_line_count() >= 5);
    }

    #[test]
    fn test_line_info_basic_wrap() {
        let buffer = TextBuffer::with_text("abcd");
        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 2, 10)
            .wrap_mode(WrapMode::Char);

        let info = view.line_info();
        assert_eq!(info.starts, vec![0, 2]);
        assert_eq!(info.ends, vec![2, 4]);
        assert_eq!(info.widths, vec![2, 2]);
        assert_eq!(info.sources, vec![0, 0]);
        assert_eq!(info.wraps, vec![false, true]);
        assert_eq!(info.max_width, 2);
    }

    #[test]
    fn test_virtual_line_byte_range_last_line() {
        eprintln!(
            "[TEST] test_virtual_line_byte_range_last_line: Verifying byte range for last line"
        );

        let buffer = TextBuffer::with_text("Hello World");
        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 80, 24)
            .wrap_mode(WrapMode::None);

        let info = view.line_info();
        eprintln!("[TEST] Virtual line count: {}", info.virtual_line_count());

        // Test the byte range for the last (and only) virtual line
        let range = info.virtual_line_byte_range(0);
        eprintln!("[TEST] Byte range for line 0: {range:?}");

        assert_eq!(
            range,
            Some((0, 11)),
            "Last line should have correct byte range (0, 11)"
        );

        // Verify the content matches
        let text = &buffer.to_string()[0..11];
        eprintln!("[TEST] Text in range: {text:?}");
        assert_eq!(text, "Hello World");

        eprintln!("[TEST] PASS: Last line byte range is correct");
    }

    #[test]
    fn test_virtual_line_byte_range_wrapped() {
        eprintln!(
            "[TEST] test_virtual_line_byte_range_wrapped: Verifying byte ranges with wrapping"
        );

        let buffer = TextBuffer::with_text("abcdefgh");
        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 3, 10)
            .wrap_mode(WrapMode::Char);

        let info = view.line_info();
        eprintln!("[TEST] Virtual line count: {}", info.virtual_line_count());

        // Should wrap to 3 lines: "abc", "def", "gh"
        assert_eq!(info.virtual_line_count(), 3);

        let range0 = info.virtual_line_byte_range(0);
        let range1 = info.virtual_line_byte_range(1);
        let range2 = info.virtual_line_byte_range(2);

        eprintln!("[TEST] Line 0 range: {range0:?}");
        eprintln!("[TEST] Line 1 range: {range1:?}");
        eprintln!("[TEST] Line 2 range: {range2:?}");

        assert_eq!(range0, Some((0, 3)), "First line: bytes 0-3");
        assert_eq!(range1, Some((3, 6)), "Second line: bytes 3-6");
        assert_eq!(range2, Some((6, 8)), "Last line: bytes 6-8 (not 6-6!)");

        eprintln!("[TEST] PASS: Wrapped line byte ranges are correct");
    }

    #[test]
    fn test_measure_for_dimensions() {
        let buffer = TextBuffer::with_text("abc\ndefgh");
        let view = TextBufferView::new(&buffer).wrap_mode(WrapMode::Char);
        let measure = view.measure_for_dimensions(3, 10);
        assert_eq!(
            measure,
            TextMeasure {
                line_count: 3,
                max_width: 3
            }
        );
    }

    #[test]
    fn test_measure_no_wrap() {
        eprintln!("[TEST] test_measure_no_wrap: Measuring without wrapping");

        let buffer = TextBuffer::with_text("short\nmedium text\nvery long line of text here");
        eprintln!("[TEST] Buffer lines: 'short', 'medium text', 'very long line of text here'");

        let view = TextBufferView::new(&buffer).wrap_mode(WrapMode::None);
        let measure = view.measure_for_dimensions(10, 10);

        eprintln!("[TEST] With WrapMode::None, width=10:");
        eprintln!("[TEST]   line_count = {}", measure.line_count);
        eprintln!("[TEST]   max_width = {}", measure.max_width);

        // Without wrapping, should have exactly 3 lines
        assert_eq!(
            measure.line_count, 3,
            "Should have 3 source lines without wrapping"
        );
        // Max width should be the longest line: "very long line of text here" = 27 chars
        assert_eq!(
            measure.max_width, 27,
            "Max width should be longest line (27 chars)"
        );

        eprintln!("[TEST] PASS: No-wrap measurement correct");
    }

    #[test]
    fn test_measure_with_char_wrap() {
        eprintln!("[TEST] test_measure_with_char_wrap: Measuring with character wrapping");

        let buffer = TextBuffer::with_text("abcdefghij");
        eprintln!("[TEST] Buffer: 'abcdefghij' (10 chars)");

        let view = TextBufferView::new(&buffer).wrap_mode(WrapMode::Char);

        // Wrap at width 3
        let measure = view.measure_for_dimensions(3, 10);
        eprintln!("[TEST] With width=3, char wrap:");
        eprintln!(
            "[TEST]   line_count = {} (expected 4: 'abc', 'def', 'ghi', 'j')",
            measure.line_count
        );
        eprintln!("[TEST]   max_width = {}", measure.max_width);

        assert_eq!(measure.line_count, 4, "10 chars / 3 = 4 wrapped lines");
        assert_eq!(measure.max_width, 3, "Max width capped at wrap width");

        // Wrap at width 5
        let measure2 = view.measure_for_dimensions(5, 10);
        eprintln!("[TEST] With width=5:");
        eprintln!(
            "[TEST]   line_count = {} (expected 2: 'abcde', 'fghij')",
            measure2.line_count
        );

        assert_eq!(measure2.line_count, 2, "10 chars / 5 = 2 wrapped lines");
        assert_eq!(measure2.max_width, 5, "Max width capped at wrap width");

        eprintln!("[TEST] PASS: Char wrap measurement correct");
    }

    #[test]
    fn test_measure_with_word_wrap() {
        eprintln!("[TEST] test_measure_with_word_wrap: Measuring with word wrapping");

        let buffer = TextBuffer::with_text("hello world test");
        eprintln!("[TEST] Buffer: 'hello world test' (16 chars)");

        let view = TextBufferView::new(&buffer).wrap_mode(WrapMode::Word);

        // Wrap at width 12 - "hello world" fits (11), "test" on next line
        let measure = view.measure_for_dimensions(12, 10);
        eprintln!("[TEST] With width=12, word wrap:");
        eprintln!("[TEST]   line_count = {}", measure.line_count);
        eprintln!("[TEST]   max_width = {}", measure.max_width);

        assert_eq!(measure.line_count, 2, "Should wrap to 2 lines at width 12");
        assert!(
            measure.max_width <= 12,
            "Max width should not exceed wrap width"
        );

        // Wrap at width 6 - each word should be on its own line
        let measure2 = view.measure_for_dimensions(6, 10);
        eprintln!("[TEST] With width=6:");
        eprintln!("[TEST]   line_count = {}", measure2.line_count);

        assert_eq!(measure2.line_count, 3, "Should wrap to 3 lines at width 6");

        eprintln!("[TEST] PASS: Word wrap measurement correct");
    }

    #[test]
    fn test_measure_empty_buffer() {
        eprintln!("[TEST] test_measure_empty_buffer: Measuring empty buffer");

        let buffer = TextBuffer::new();
        eprintln!("[TEST] Empty buffer created");

        let view = TextBufferView::new(&buffer).wrap_mode(WrapMode::Char);
        let measure = view.measure_for_dimensions(80, 24);

        eprintln!("[TEST] Measure results:");
        eprintln!("[TEST]   line_count = {}", measure.line_count);
        eprintln!("[TEST]   max_width = {}", measure.max_width);

        // Empty buffer should have 0 or 1 line depending on implementation
        assert!(
            measure.line_count <= 1,
            "Empty buffer should have 0 or 1 line"
        );
        assert_eq!(measure.max_width, 0, "Empty buffer should have max_width 0");

        eprintln!("[TEST] PASS: Empty buffer measurement correct");
    }

    #[test]
    fn test_measure_single_long_line() {
        eprintln!("[TEST] test_measure_single_long_line: Measuring single long line");

        // Create a 100-character line
        let long_line = "x".repeat(100);
        let buffer = TextBuffer::with_text(&long_line);
        eprintln!("[TEST] Single line of 100 'x' characters");

        let view = TextBufferView::new(&buffer).wrap_mode(WrapMode::Char);

        // Wrap at width 20
        let measure = view.measure_for_dimensions(20, 10);
        eprintln!("[TEST] With width=20:");
        eprintln!("[TEST]   line_count = {} (expected 5)", measure.line_count);
        eprintln!("[TEST]   max_width = {}", measure.max_width);

        assert_eq!(measure.line_count, 5, "100 chars / 20 = 5 wrapped lines");
        assert_eq!(measure.max_width, 20, "Max width should be 20");

        // Wrap at width 33
        let measure2 = view.measure_for_dimensions(33, 10);
        eprintln!("[TEST] With width=33:");
        eprintln!(
            "[TEST]   line_count = {} (expected 4: 33+33+33+1)",
            measure2.line_count
        );

        assert_eq!(measure2.line_count, 4, "100 chars / 33 = 4 wrapped lines");

        eprintln!("[TEST] PASS: Single long line measurement correct");
    }

    #[test]
    fn test_measure_cjk_content() {
        eprintln!("[TEST] test_measure_cjk_content: Measuring CJK wide characters");

        // CJK characters are typically 2 columns wide
        let buffer = TextBuffer::with_text("你好世界"); // 4 CJK chars = 8 display columns
        eprintln!("[TEST] Buffer: '你好世界' (4 CJK chars, ~8 display columns)");

        let view = TextBufferView::new(&buffer).wrap_mode(WrapMode::Char);

        // With width 4, each CJK char is 2 wide, so 2 chars per line
        let measure = view.measure_for_dimensions(4, 10);
        eprintln!("[TEST] With width=4:");
        eprintln!("[TEST]   line_count = {}", measure.line_count);
        eprintln!("[TEST]   max_width = {}", measure.max_width);

        // Should wrap to 2 lines: "你好" (4 cols) and "世界" (4 cols)
        assert_eq!(
            measure.line_count, 2,
            "4 CJK chars at width 4 should be 2 lines"
        );
        assert_eq!(measure.max_width, 4, "Max width should be 4");

        // With width 8, all 4 chars should fit on one line
        let measure2 = view.measure_for_dimensions(8, 10);
        eprintln!("[TEST] With width=8:");
        eprintln!("[TEST]   line_count = {}", measure2.line_count);

        assert_eq!(
            measure2.line_count, 1,
            "All CJK chars should fit at width 8"
        );

        eprintln!("[TEST] PASS: CJK content measurement correct");
    }

    #[test]
    fn test_measure_updates_after_edit() {
        eprintln!("[TEST] test_measure_updates_after_edit: Verifying measurement updates");

        let mut buffer = TextBuffer::with_text("short");
        eprintln!("[TEST] Initial buffer: 'short'");

        let view = TextBufferView::new(&buffer).wrap_mode(WrapMode::Char);
        let measure1 = view.measure_for_dimensions(10, 10);
        eprintln!(
            "[TEST] Initial measure: line_count={}, max_width={}",
            measure1.line_count, measure1.max_width
        );

        assert_eq!(measure1.line_count, 1);
        assert_eq!(measure1.max_width, 5);

        // Modify the buffer
        buffer.set_text("this is a much longer line now");
        eprintln!("[TEST] Updated buffer: 'this is a much longer line now'");

        // Create new view with updated buffer
        let view2 = TextBufferView::new(&buffer).wrap_mode(WrapMode::Char);
        let measure2 = view2.measure_for_dimensions(10, 10);
        eprintln!(
            "[TEST] Updated measure: line_count={}, max_width={}",
            measure2.line_count, measure2.max_width
        );

        // "this is a much longer line now" = 30 chars, at width 10 = 3 lines
        assert_eq!(
            measure2.line_count, 3,
            "30 chars at width 10 should be 3 lines"
        );
        assert_eq!(measure2.max_width, 10);

        eprintln!("[TEST] PASS: Measurement updates correctly after edit");
    }

    #[test]
    fn test_measure_consistency_with_render() {
        use crate::buffer::OptimizedBuffer;

        eprintln!("[TEST] test_measure_consistency_with_render: Comparing measure with render");

        let buffer = TextBuffer::with_text("line1\nline2 is longer\nshort");
        eprintln!("[TEST] Buffer with 3 lines of varying length");

        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 8, 10)
            .wrap_mode(WrapMode::Char);

        let measure = view.measure_for_dimensions(8, 10);
        eprintln!(
            "[TEST] Measure: line_count={}, max_width={}",
            measure.line_count, measure.max_width
        );

        // Now render and count actual lines
        let mut output = OptimizedBuffer::new(8, 10);
        view.render_to(&mut output, 0, 0);

        // Count rendered lines by checking for non-default content
        let virtual_count = view.virtual_line_count();
        eprintln!("[TEST] virtual_line_count() = {virtual_count}");

        // Measure should match virtual line count
        assert_eq!(
            measure.line_count, virtual_count,
            "measure_for_dimensions line_count should match virtual_line_count"
        );

        eprintln!("[TEST] PASS: Measurement consistent with render");
    }

    #[test]
    fn test_tab_rendering_preserves_style() {
        use crate::buffer::OptimizedBuffer;
        use crate::cell::CellContent;
        use crate::color::Rgba;
        use crate::text::segment::StyledChunk;

        eprintln!("[TEST] test_tab_rendering_preserves_style: Verifying TAB gets syntax style");

        // Create buffer with styled text containing a tab
        let mut buffer = TextBuffer::new();
        buffer.set_styled_text(&[
            StyledChunk::new("hello", Style::fg(Rgba::RED)),
            StyledChunk::new("\t", Style::fg(Rgba::GREEN)), // Tab with green style
            StyledChunk::new("world", Style::fg(Rgba::BLUE)),
        ]);
        eprintln!("[TEST] Buffer text: {:?}", buffer.to_string());

        let view = TextBufferView::new(&buffer).viewport(0, 0, 80, 24);

        // Render to buffer
        let mut output = OptimizedBuffer::new(80, 24);
        view.render_to(&mut output, 0, 0);

        // Check the cell at position where tab starts (after "hello")
        // Tab at position 5 should have the green style (from the styled chunk)
        let cell_at_tab = output.get(5, 0);
        eprintln!("[TEST] Cell at tab position (5,0): {cell_at_tab:?}");

        // The tab should render as space(s) but preserve the GREEN style
        assert!(cell_at_tab.is_some(), "Cell at tab position should exist");
        let cell = cell_at_tab.unwrap();
        // The foreground should be GREEN since that's the style at the tab position
        eprintln!("[TEST] Tab cell foreground: {:?}", cell.fg);
        // Note: without tab_indicator set, the cell is a space with the style from style_at
        assert!(
            matches!(cell.content, CellContent::Char(' ')),
            "Tab should render as space by default"
        );
        assert_eq!(
            cell.fg,
            Rgba::GREEN,
            "Tab should preserve syntax highlighting (GREEN)"
        );

        // Verify "world" has blue style
        let cell_at_world = output.get(8, 0); // Tab expands to position 8
        eprintln!("[TEST] Cell at 'world' start (8,0): {cell_at_world:?}");
        if let Some(cell) = cell_at_world {
            assert!(matches!(cell.content, CellContent::Char('w')));
            assert_eq!(cell.fg, Rgba::BLUE);
        }

        eprintln!("[TEST] SUCCESS: Tab rendering preserves syntax highlighting");
    }

    #[test]
    fn test_tab_indicator_with_style() {
        use crate::buffer::OptimizedBuffer;
        use crate::cell::CellContent;
        use crate::color::Rgba;
        use crate::text::segment::StyledChunk;

        eprintln!("[TEST] test_tab_indicator_with_style: Tab indicator overrides fg, preserves bg");

        // Define test colors
        let magenta = Rgba::rgb(1.0, 0.0, 1.0); // Magenta: full red + blue
        let yellow = Rgba::rgb(1.0, 1.0, 0.0); // Yellow: full red + green

        // Create buffer with styled text containing a tab with background
        let mut buffer = TextBuffer::new();
        let bg_style = Style::NONE.with_bg(magenta).with_fg(Rgba::GREEN);
        buffer.set_styled_text(&[
            StyledChunk::new("x", Style::NONE),
            StyledChunk::new("\t", bg_style), // Tab with magenta background
            StyledChunk::new("y", Style::NONE),
        ]);
        eprintln!("[TEST] Buffer text: {:?}", buffer.to_string());

        // Set tab indicator
        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 80, 24)
            .tab_indicator('', yellow);

        let mut output = OptimizedBuffer::new(80, 24);
        view.render_to(&mut output, 0, 0);

        // Tab indicator at position 1
        let cell = output.get(1, 0).expect("Cell should exist");
        eprintln!(
            "[TEST] Tab indicator cell: content={:?}, fg={:?}, bg={:?}",
            cell.content, cell.fg, cell.bg
        );

        assert!(
            matches!(cell.content, CellContent::Char('')),
            "Tab indicator should be arrow"
        );
        assert_eq!(cell.fg, yellow, "Tab indicator should have yellow fg");
        // Background is preserved from the style
        assert_eq!(
            cell.bg, magenta,
            "Tab should preserve background from syntax"
        );

        eprintln!("[TEST] SUCCESS: Tab indicator correctly overrides fg while preserving bg");
    }

    #[test]
    fn test_tab_expands_correctly() {
        use crate::buffer::OptimizedBuffer;
        use crate::cell::CellContent;

        eprintln!("[TEST] test_tab_expands_correctly: Verifying tab expansion width");

        let buffer = TextBuffer::with_text("ab\tcd");
        let view = TextBufferView::new(&buffer).viewport(0, 0, 80, 24);

        let mut output = OptimizedBuffer::new(80, 24);
        view.render_to(&mut output, 0, 0);

        // Default tab width is 4
        // "ab" at positions 0,1
        // TAB at positions 2,3 (expands to fill to next multiple of 4)
        // "cd" at positions 4,5
        eprintln!("[TEST] Checking character positions after tab expansion");

        let cell_a = output.get(0, 0).expect("Cell should exist");
        assert!(matches!(cell_a.content, CellContent::Char('a')));
        eprintln!("[TEST] Position 0: {:?}", cell_a.content);

        let cell_b = output.get(1, 0).expect("Cell should exist");
        assert!(matches!(cell_b.content, CellContent::Char('b')));
        eprintln!("[TEST] Position 1: {:?}", cell_b.content);

        // Tab expansion fills 2,3
        let cell_tab = output.get(2, 0).expect("Cell should exist");
        assert!(
            matches!(cell_tab.content, CellContent::Char(' ')),
            "Tab should expand to space"
        );
        eprintln!("[TEST] Position 2: {:?} (tab space)", cell_tab.content);

        let cell_tab2 = output.get(3, 0).expect("Cell should exist");
        assert!(
            matches!(cell_tab2.content, CellContent::Char(' ')),
            "Tab should expand to space"
        );
        eprintln!("[TEST] Position 3: {:?} (tab space)", cell_tab2.content);

        // After tab
        let cell_c = output.get(4, 0).expect("Cell should exist");
        assert!(matches!(cell_c.content, CellContent::Char('c')));
        eprintln!("[TEST] Position 4: {:?}", cell_c.content);

        let cell_d = output.get(5, 0).expect("Cell should exist");
        assert!(matches!(cell_d.content, CellContent::Char('d')));
        eprintln!("[TEST] Position 5: {:?}", cell_d.content);

        eprintln!("[TEST] SUCCESS: Tab expansion width is correct");
    }

    #[test]
    fn test_tab_selection_highlights_all_columns() {
        use crate::buffer::OptimizedBuffer;
        use crate::cell::CellContent;
        use crate::color::Rgba;

        eprintln!(
            "[TEST] test_tab_selection_highlights_all_columns: Verifying all tab columns get selection style (bd-nyo9)"
        );

        // Create text with a tab: "ab\tcd"
        // With tab width 4, "ab" at 0-1, tab expands to 2-3, "cd" at 4-5
        let buffer = TextBuffer::with_text("ab\tcd");
        let selection_bg = Rgba::rgb(0.0, 0.0, 1.0); // Blue selection
        let selection_style = Style::NONE.with_bg(selection_bg);

        let mut view = TextBufferView::new(&buffer).viewport(0, 0, 80, 24);

        // Select just the tab character (character offset 2)
        view.set_selection(2, 3, selection_style);

        let mut output = OptimizedBuffer::new(80, 24);
        view.render_to(&mut output, 0, 0);

        eprintln!("[TEST] Checking all tab columns have selection style");

        // Tab expands to positions 2 and 3 (fill to next multiple of 4)
        // Both should have the selection background
        for pos in 2..4 {
            let cell = output.get(pos, 0).expect("Cell should exist");
            eprintln!(
                "[TEST] Position {}: content={:?}, bg={:?}",
                pos, cell.content, cell.bg
            );
            assert!(
                matches!(cell.content, CellContent::Char(' ')),
                "Position {} should be space from tab expansion",
                pos
            );
            assert_eq!(
                cell.bg, selection_bg,
                "Position {} should have selection background (all tab columns should be highlighted)",
                pos
            );
        }

        // Characters before and after tab should NOT have selection
        let cell_b = output.get(1, 0).expect("Cell should exist");
        assert_ne!(
            cell_b.bg, selection_bg,
            "Character before tab should not be selected"
        );

        let cell_c = output.get(4, 0).expect("Cell should exist");
        assert_ne!(
            cell_c.bg, selection_bg,
            "Character after tab should not be selected"
        );

        eprintln!("[TEST] SUCCESS: All tab columns correctly show selection style");
    }

    // ================== LineInfo Comprehensive Tests ==================

    #[test]
    fn test_line_cache_no_wrap() {
        eprintln!("[TEST] test_line_cache_no_wrap: Testing line cache without wrapping");

        let buffer = TextBuffer::with_text("Hello World\nSecond Line\nThird");
        eprintln!("[TEST] Input text: {:?}", buffer.to_string());
        eprintln!("[TEST] Logical line count: {}", buffer.len_lines());

        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 80, 24)
            .wrap_mode(WrapMode::None);

        let info = view.line_info();
        eprintln!("[TEST] LineInfo results:");
        eprintln!("[TEST]   virtual_line_count: {}", info.virtual_line_count());
        eprintln!("[TEST]   max_width: {}", info.max_width);

        for i in 0..info.virtual_line_count() {
            eprintln!(
                "[TEST]   Line {}: start={} width={} source={} wrap={}",
                i, info.starts[i], info.widths[i], info.sources[i], info.wraps[i]
            );
        }

        assert_eq!(info.virtual_line_count(), 3, "Should have 3 virtual lines");
        assert_eq!(
            info.sources,
            vec![0, 1, 2],
            "Each virtual line maps to its source"
        );
        assert_eq!(info.wraps, vec![false, false, false], "No wrapping");
        assert_eq!(info.max_width, 11, "Max width should be 'Hello World' = 11");

        eprintln!("[TEST] PASS: No-wrap mode produces correct line info");
    }

    #[test]
    fn test_line_cache_char_wrap_exact() {
        eprintln!("[TEST] test_line_cache_char_wrap_exact: Testing char wrap at exact boundary");

        let buffer = TextBuffer::with_text("abcdef");
        eprintln!(
            "[TEST] Input: {:?}, length: {}",
            buffer.to_string(),
            buffer.len_chars()
        );

        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 3, 10)
            .wrap_mode(WrapMode::Char);

        let info = view.line_info();
        eprintln!("[TEST] Wrap width: 3, LineInfo:");
        for i in 0..info.virtual_line_count() {
            eprintln!(
                "[TEST]   Line {}: start={} width={} source={} wrap={}",
                i, info.starts[i], info.widths[i], info.sources[i], info.wraps[i]
            );
        }

        assert_eq!(info.virtual_line_count(), 2, "6 chars / 3 width = 2 lines");
        assert_eq!(info.widths, vec![3, 3], "Each line has width 3");
        assert_eq!(info.wraps, vec![false, true], "Second line is continuation");

        eprintln!("[TEST] PASS: Char wrap at exact boundary works");
    }

    #[test]
    fn test_line_cache_char_wrap_overflow() {
        eprintln!("[TEST] test_line_cache_char_wrap_overflow: Testing char wrap with overflow");

        let buffer = TextBuffer::with_text("abcdefgh");
        eprintln!(
            "[TEST] Input: {:?}, length: {}",
            buffer.to_string(),
            buffer.len_chars()
        );

        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 3, 10)
            .wrap_mode(WrapMode::Char);

        let info = view.line_info();
        eprintln!("[TEST] Wrap width: 3, LineInfo:");
        for i in 0..info.virtual_line_count() {
            eprintln!(
                "[TEST]   Line {}: start={} width={} source={} wrap={}",
                i, info.starts[i], info.widths[i], info.sources[i], info.wraps[i]
            );
        }

        assert_eq!(info.virtual_line_count(), 3, "8 chars / 3 width = 3 lines");
        assert_eq!(info.widths, vec![3, 3, 2], "Last line has 2 chars");

        eprintln!("[TEST] PASS: Char wrap overflow works correctly");
    }

    #[test]
    fn test_line_cache_word_wrap_simple() {
        eprintln!("[TEST] test_line_cache_word_wrap_simple: Testing word wrap");

        let buffer = TextBuffer::with_text("Hello world test");
        eprintln!("[TEST] Input: {:?}", buffer.to_string());
        eprintln!("[TEST] Wrap width: 10");

        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 10, 10)
            .wrap_mode(WrapMode::Word);

        let info = view.line_info();
        eprintln!("[TEST] LineInfo:");
        for i in 0..info.virtual_line_count() {
            eprintln!(
                "[TEST]   Line {}: start={} width={} source={} wrap={}",
                i, info.starts[i], info.widths[i], info.sources[i], info.wraps[i]
            );
        }

        // "Hello " (6) + "world" would exceed 10, so wrap at "Hello "
        // Then "world " (6) + "test" (4) = 10, fits
        assert!(
            info.virtual_line_count() >= 2,
            "Should wrap into at least 2 lines"
        );

        eprintln!("[TEST] PASS: Word wrap breaks at word boundaries");
    }

    #[test]
    fn test_line_cache_word_wrap_long_word() {
        eprintln!("[TEST] test_line_cache_word_wrap_long_word: Testing word wrap with long word");

        let buffer = TextBuffer::with_text("supercalifragilisticexpialidocious");
        eprintln!(
            "[TEST] Input: {:?}, length: {}",
            buffer.to_string(),
            buffer.len_chars()
        );

        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 10, 10)
            .wrap_mode(WrapMode::Word);

        let info = view.line_info();
        eprintln!("[TEST] Wrap width: 10, LineInfo:");
        for i in 0..info.virtual_line_count() {
            eprintln!(
                "[TEST]   Line {}: start={} width={} source={} wrap={}",
                i, info.starts[i], info.widths[i], info.sources[i], info.wraps[i]
            );
        }

        // Long word without spaces should still break at char boundaries
        assert!(
            info.virtual_line_count() >= 3,
            "Long word should split across lines"
        );

        eprintln!("[TEST] PASS: Long word breaks at character boundaries when no spaces");
    }

    #[test]
    fn test_line_cache_multiple_lines() {
        eprintln!("[TEST] test_line_cache_multiple_lines: Testing multiple logical lines");

        let buffer = TextBuffer::with_text("Short\nThis is longer\nEnd");
        eprintln!("[TEST] Input with 3 logical lines:");
        for (i, line) in buffer.to_string().lines().enumerate() {
            eprintln!("[TEST]   Line {i}: {line:?}");
        }

        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 10, 10)
            .wrap_mode(WrapMode::Word);

        let info = view.line_info();
        eprintln!("[TEST] LineInfo (wrap_width=10):");
        for i in 0..info.virtual_line_count() {
            eprintln!(
                "[TEST]   Virtual {}: start={} width={} source={} wrap={}",
                i, info.starts[i], info.widths[i], info.sources[i], info.wraps[i]
            );
        }

        // "This is longer" should wrap
        assert!(info.virtual_line_count() > 3, "Middle line should wrap");
        assert_eq!(info.sources[0], 0, "First virtual line from source 0");

        eprintln!("[TEST] PASS: Multiple lines with wrapping handled correctly");
    }

    #[test]
    fn test_line_cache_empty_lines() {
        eprintln!("[TEST] test_line_cache_empty_lines: Testing empty lines");

        let buffer = TextBuffer::with_text("Line1\n\nLine3");
        eprintln!("[TEST] Input: {:?}", buffer.to_string());

        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 80, 24)
            .wrap_mode(WrapMode::None);

        let info = view.line_info();
        eprintln!("[TEST] LineInfo:");
        for i in 0..info.virtual_line_count() {
            eprintln!(
                "[TEST]   Line {}: start={} width={} source={} wrap={}",
                i, info.starts[i], info.widths[i], info.sources[i], info.wraps[i]
            );
        }

        assert_eq!(
            info.virtual_line_count(),
            3,
            "Should have 3 lines including empty"
        );
        assert_eq!(info.widths[1], 0, "Empty line has width 0");

        eprintln!("[TEST] PASS: Empty lines handled correctly");
    }

    #[test]
    fn test_line_cache_utf8_width() {
        eprintln!("[TEST] test_line_cache_utf8_width: Testing UTF-8 character widths");

        let buffer = TextBuffer::with_text("Hëllo");
        eprintln!(
            "[TEST] Input: {:?}, byte len: {}",
            buffer.to_string(),
            buffer.to_string().len()
        );

        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 80, 24)
            .wrap_mode(WrapMode::None);

        let info = view.line_info();
        eprintln!("[TEST] LineInfo:");
        eprintln!("[TEST]   width: {}", info.widths[0]);

        assert_eq!(info.widths[0], 5, "UTF-8 'ë' should have display width 1");

        eprintln!("[TEST] PASS: UTF-8 characters have correct display width");
    }

    #[test]
    fn test_line_cache_cjk_characters() {
        eprintln!("[TEST] test_line_cache_cjk_characters: Testing CJK character widths");

        // CJK characters are typically 2 columns wide
        let buffer = TextBuffer::with_text("Hi中文Ok");
        eprintln!("[TEST] Input: {:?}", buffer.to_string());
        eprintln!("[TEST] Expected widths: H=1, i=1, 中=2, 文=2, O=1, k=1 = 8 total");

        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 80, 24)
            .wrap_mode(WrapMode::None);

        let info = view.line_info();
        eprintln!("[TEST] Computed width: {}", info.widths[0]);

        assert_eq!(info.widths[0], 8, "CJK chars should be 2 columns each");

        eprintln!("[TEST] PASS: CJK characters have width 2");
    }

    #[test]
    fn test_line_cache_cjk_wrap() {
        eprintln!("[TEST] test_line_cache_cjk_wrap: Testing CJK wrapping doesn't break mid-char");

        let buffer = TextBuffer::with_text("AB中文CD");
        eprintln!("[TEST] Input: {:?}", buffer.to_string());
        eprintln!("[TEST] Widths: A=1, B=1, 中=2, 文=2, C=1, D=1 = 8");

        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 5, 10)
            .wrap_mode(WrapMode::Char);

        let info = view.line_info();
        eprintln!("[TEST] Wrap width: 5, LineInfo:");
        for i in 0..info.virtual_line_count() {
            eprintln!("[TEST]   Line {}: width={}", i, info.widths[i]);
        }

        // Verify no line has an odd-width ending that would split a CJK char
        for (i, &width) in info.widths.iter().enumerate() {
            eprintln!("[TEST] Verifying line {i} width {width} <= 5");
            assert!(width <= 5, "Line {i} width {width} exceeds wrap width 5");
        }

        eprintln!("[TEST] PASS: CJK characters not broken mid-character");
    }

    #[test]
    fn test_line_cache_emoji_grapheme_clusters() {
        eprintln!("[TEST] test_line_cache_emoji_grapheme_clusters: Testing multi-codepoint emoji");

        // ZWJ family emoji (👨‍👩‍👧) is multiple codepoints but displays as width 2
        // Each emoji: 👨 (U+1F468) + ZWJ (U+200D) + 👩 (U+1F469) + ZWJ + 👧 (U+1F467)
        let buffer = TextBuffer::with_text("Hi👨\u{200D}👩\u{200D}👧Ok");
        eprintln!("[TEST] Input: 'Hi' + family emoji + 'Ok'");
        eprintln!("[TEST] Expected widths: H=1, i=1, family=2, O=1, k=1 = 6 total");

        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 80, 24)
            .wrap_mode(WrapMode::None);

        let info = view.line_info();
        eprintln!("[TEST] Computed width: {}", info.widths[0]);

        // The family emoji should render as width 2
        assert_eq!(info.widths[0], 6, "Family emoji should be 2 columns");

        eprintln!("[TEST] PASS: Multi-codepoint emoji width correct");
    }

    #[test]
    fn test_line_cache_emoji_wrap() {
        eprintln!(
            "[TEST] test_line_cache_emoji_wrap: Testing emoji wrapping doesn't break mid-grapheme"
        );

        // Text: "AB" + family emoji + "CD" = 2 + 2 + 2 = 6 display columns
        let buffer = TextBuffer::with_text("AB👨\u{200D}👩\u{200D}👧CD");
        eprintln!("[TEST] Input: 'AB' + family emoji + 'CD'");
        eprintln!("[TEST] Widths: A=1, B=1, family=2, C=1, D=1 = 6 total");

        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 3, 10)
            .wrap_mode(WrapMode::Char);

        let info = view.line_info();
        eprintln!("[TEST] Wrap width: 3, LineInfo:");
        for i in 0..info.virtual_line_count() {
            eprintln!("[TEST]   Line {}: width={}", i, info.widths[i]);
        }

        // With width 3:
        // Line 0: "AB" (2 cols) - emoji doesn't fit, wraps
        // Line 1: family emoji (2 cols) - fits
        // Line 2: "CD" (2 cols)
        // Verify no line exceeds wrap width
        for (i, &width) in info.widths.iter().enumerate() {
            eprintln!("[TEST] Verifying line {i} width {width} <= 3");
            assert!(width <= 3, "Line {i} width {width} exceeds wrap width 3");
        }

        eprintln!("[TEST] PASS: Emoji grapheme clusters not broken mid-grapheme");
    }

    #[test]
    fn test_line_cache_invalidation_content() {
        eprintln!("[TEST] test_line_cache_invalidation_content: Testing cache invalidation");

        let buffer = TextBuffer::with_text("Hello");
        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 80, 24)
            .wrap_mode(WrapMode::None);

        let info1 = view.line_info();
        eprintln!(
            "[TEST] Initial info: lines={}, max_width={}",
            info1.virtual_line_count(),
            info1.max_width
        );

        // Create new buffer with different content
        let buffer2 = TextBuffer::with_text("Hello World Extended");
        let view2 = TextBufferView::new(&buffer2)
            .viewport(0, 0, 80, 24)
            .wrap_mode(WrapMode::None);

        let info2 = view2.line_info();
        eprintln!(
            "[TEST] New info: lines={}, max_width={}",
            info2.virtual_line_count(),
            info2.max_width
        );

        assert_ne!(
            info1.max_width, info2.max_width,
            "Different content should have different width"
        );

        eprintln!("[TEST] PASS: Cache correctly reflects content changes");
    }

    #[test]
    fn test_line_cache_invalidation_wrap_mode() {
        eprintln!("[TEST] test_line_cache_invalidation_wrap_mode: Testing wrap mode change");

        let buffer = TextBuffer::with_text("Hello World Test Line");

        let view_none = TextBufferView::new(&buffer)
            .viewport(0, 0, 10, 10)
            .wrap_mode(WrapMode::None);
        let info_none = view_none.line_info();
        eprintln!(
            "[TEST] WrapMode::None: lines={}",
            info_none.virtual_line_count()
        );

        let view_char = TextBufferView::new(&buffer)
            .viewport(0, 0, 10, 10)
            .wrap_mode(WrapMode::Char);
        let info_char = view_char.line_info();
        eprintln!(
            "[TEST] WrapMode::Char: lines={}",
            info_char.virtual_line_count()
        );

        assert_ne!(
            info_none.virtual_line_count(),
            info_char.virtual_line_count(),
            "Different wrap modes should produce different line counts"
        );

        eprintln!("[TEST] PASS: Wrap mode change produces different results");
    }

    #[test]
    fn test_source_to_virtual_mapping() {
        eprintln!("[TEST] test_source_to_virtual_mapping: Testing source -> virtual mapping");

        let buffer = TextBuffer::with_text("Short\nThis is a longer line that wraps\nEnd");
        eprintln!("[TEST] Input with 3 logical lines");

        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 15, 10)
            .wrap_mode(WrapMode::Word);

        let info = view.line_info();
        eprintln!("[TEST] Virtual lines:");
        for i in 0..info.virtual_line_count() {
            eprintln!("[TEST]   Virtual {}: source={}", i, info.sources[i]);
        }

        // Test source_to_virtual
        for src in 0..=2 {
            let virt = info.source_to_virtual(src);
            eprintln!("[TEST] source_to_virtual({src}) = {virt:?}");
            assert!(virt.is_some(), "Source {src} should map to a virtual line");
        }

        // Test virtual_to_source
        for virt in 0..info.virtual_line_count() {
            let src = info.virtual_to_source(virt);
            eprintln!("[TEST] virtual_to_source({virt}) = {src:?}");
            assert!(src.is_some(), "Virtual {virt} should map to a source line");
        }

        // Test round-trip: source -> virtual -> source
        for src in 0..=2 {
            if let Some(virt) = info.source_to_virtual(src) {
                let back = info.virtual_to_source(virt).unwrap();
                eprintln!("[TEST] Round-trip: {src} -> {virt} -> {back}");
                assert_eq!(back, src, "Round-trip should preserve source line");
            }
        }

        eprintln!("[TEST] PASS: Source/virtual mappings are correct");
    }

    #[test]
    fn test_virtual_to_source_mapping() {
        eprintln!("[TEST] test_virtual_to_source_mapping: Testing virtual -> source mapping");

        let buffer = TextBuffer::with_text("Line one\nLine two\nLine three");
        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 5, 10)
            .wrap_mode(WrapMode::Char);

        let info = view.line_info();
        eprintln!("[TEST] {} virtual lines", info.virtual_line_count());

        for virt in 0..info.virtual_line_count() {
            let src = info.virtual_to_source(virt);
            let is_cont = info.is_continuation(virt);
            eprintln!("[TEST] Virtual {virt} -> source {src:?}, is_continuation: {is_cont:?}");
        }

        // Verify out-of-bounds returns None
        let oob = info.virtual_to_source(1000);
        assert!(oob.is_none(), "Out of bounds should return None");

        eprintln!("[TEST] PASS: Virtual to source mapping works");
    }

    #[test]
    fn test_line_info_helper_methods() {
        eprintln!("[TEST] test_line_info_helper_methods: Testing LineInfo helper methods");

        let buffer = TextBuffer::with_text("Hello\nWorld");
        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 80, 24)
            .wrap_mode(WrapMode::None);

        let info = view.line_info();

        eprintln!("[TEST] virtual_line_count: {}", info.virtual_line_count());
        assert_eq!(info.virtual_line_count(), 2);

        eprintln!("[TEST] max_source_line: {:?}", info.max_source_line());
        assert_eq!(info.max_source_line(), Some(1));

        eprintln!(
            "[TEST] virtual_lines_for_source(0): {}",
            info.virtual_lines_for_source(0)
        );
        assert_eq!(info.virtual_lines_for_source(0), 1);

        eprintln!(
            "[TEST] virtual_line_width(0): {:?}",
            info.virtual_line_width(0)
        );
        assert_eq!(info.virtual_line_width(0), Some(5));

        eprintln!("[TEST] is_continuation(0): {:?}", info.is_continuation(0));
        assert_eq!(info.is_continuation(0), Some(false));

        eprintln!("[TEST] PASS: Helper methods work correctly");
    }

    #[test]
    fn test_line_cache_performance() {
        use std::fmt::Write as _;
        use std::time::Instant;

        eprintln!("[PERF] test_line_cache_performance: Testing cache performance");

        // Generate 10K lines of text
        let mut text = String::new();
        for i in 0..10_000 {
            let _ = writeln!(
                text,
                "Line {i} with some content that might wrap when narrow"
            );
        }

        let buffer = TextBuffer::with_text(&text);
        eprintln!(
            "[PERF] Buffer size: {} bytes, {} lines",
            text.len(),
            buffer.len_lines()
        );

        let view = TextBufferView::new(&buffer)
            .viewport(0, 0, 80, 100)
            .wrap_mode(WrapMode::Word);

        let start = Instant::now();
        let info = view.line_info();
        let elapsed = start.elapsed();

        eprintln!("[PERF] Cache computation time: {elapsed:?}");
        eprintln!("[PERF] Virtual lines: {}", info.virtual_line_count());
        eprintln!("[PERF] Max width: {}", info.max_width);
        let lines_per_ms = 10_000.0 / elapsed.as_secs_f64() / 1000.0;
        eprintln!("[PERF] Lines per millisecond: {lines_per_ms:.0}");

        // Allow up to 150ms for CI/slow/loaded machines, but log if over 10ms
        if elapsed.as_millis() > 10 {
            eprintln!("[PERF] WARNING: Took {elapsed:?}, expected <10ms");
        }
        assert!(
            elapsed.as_millis() < 150,
            "Cache computation took {elapsed:?}, should be <150ms"
        );

        eprintln!("[PERF] PASS: 10K lines processed efficiently");
    }

    #[test]
    fn test_render_emoji_with_pool() {
        use crate::buffer::OptimizedBuffer;
        use crate::cell::CellContent;
        use crate::grapheme_pool::GraphemePool;

        let buffer = TextBuffer::with_text("👨‍👩‍👧");
        let view = TextBufferView::new(&buffer).viewport(0, 0, 10, 1);
        let mut output = OptimizedBuffer::new(10, 1);
        let mut pool = GraphemePool::new();

        view.render_to_with_pool(&mut output, &mut pool, 0, 0);

        let cell = output.get(0, 0).unwrap();
        if let CellContent::Grapheme(id) = cell.content {
            // Confirm it's NOT a placeholder (pool_id > 0)
            assert!(
                id.pool_id() > 0,
                "Expected valid pool ID for interned grapheme"
            );
            assert_eq!(id.width(), 2, "Width should be 2");

            // Verify content is preserved in pool
            assert_eq!(pool.get(id), Some("👨‍👩‍👧"));
        } else {
            assert!(
                matches!(cell.content, CellContent::Grapheme(_)),
                "Expected Grapheme content"
            );
        }
    }
}