ftui-widgets 0.4.0

Widget library built on FrankenTUI render and layout.
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
//! Multi-line text editing widget.
//!
//! [`TextArea`] wraps [`Editor`] for text manipulation and
//! provides Frame-based rendering with viewport scrolling and cursor display.
//!
//! # Example
//! ```
//! use ftui_widgets::textarea::{TextArea, TextAreaState};
//!
//! let mut ta = TextArea::new();
//! ta.insert_text("Hello\nWorld");
//! assert_eq!(ta.line_count(), 2);
//! ```

use ftui_core::event::{Event, KeyCode, KeyEvent, KeyEventKind, Modifiers};
use ftui_core::geometry::Rect;
use ftui_render::frame::Frame;
use ftui_style::Style;
use ftui_text::editor::{Editor, Selection};
use ftui_text::wrap::display_width;
use ftui_text::{CursorNavigator, CursorPosition};
use unicode_segmentation::UnicodeSegmentation;

use crate::{StatefulWidget, Widget, apply_style, clear_text_area, draw_text_span};

/// Multi-line text editor widget.
#[derive(Debug, Clone)]
pub struct TextArea {
    editor: Editor,
    /// Placeholder text shown when empty.
    placeholder: String,
    /// Whether the widget has input focus.
    focused: bool,
    /// Show line numbers in gutter.
    show_line_numbers: bool,
    /// Base style.
    style: Style,
    /// Cursor line highlight style.
    cursor_line_style: Option<Style>,
    /// Selection highlight style.
    selection_style: Style,
    /// Placeholder style.
    placeholder_style: Style,
    /// Line number style.
    line_number_style: Style,
    /// Soft-wrap long lines.
    ///
    /// Visual wrapping preserves whitespace and breaks on word boundaries with
    /// a grapheme fallback for long segments.
    soft_wrap: bool,
    /// Maximum height in lines (0 = unlimited / fill area).
    max_height: usize,
    /// Viewport scroll anchor (logical_line_idx, visual_wrap_offset).
    ///
    /// In soft-wrap mode, this tracks the first visible visual line.
    /// In no-wrap mode, the second element is ignored (always 0).
    scroll_anchor: std::cell::Cell<(usize, usize)>,
    /// Horizontal scroll offset (visual columns).
    scroll_left: std::cell::Cell<usize>,
    /// Last viewport height for page movement and visibility checks.
    #[allow(dead_code)]
    last_viewport_height: std::cell::Cell<usize>,
    /// Last viewport width for visibility checks.
    last_viewport_width: std::cell::Cell<usize>,
}

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

/// Render state tracked across frames.
#[derive(Debug, Clone, Default)]
pub struct TextAreaState {
    /// Viewport height from last render.
    pub last_viewport_height: u16,
    /// Viewport width from last render.
    pub last_viewport_width: u16,
}

#[derive(Debug, Clone)]
struct WrappedSlice<'a> {
    text: &'a str,
    start_byte: usize,
    start_col: usize,
    width: usize,
}

impl TextArea {
    /// Create a new empty text area.
    #[must_use]
    pub fn new() -> Self {
        Self {
            editor: Editor::new(),
            placeholder: String::new(),
            focused: false,
            show_line_numbers: false,
            style: Style::default(),
            cursor_line_style: None,
            selection_style: Style::new().reverse(),
            placeholder_style: Style::new().dim(),
            line_number_style: Style::new().dim(),
            soft_wrap: false,
            max_height: 0,
            scroll_anchor: std::cell::Cell::new((usize::MAX, 0)), // sentinel
            scroll_left: std::cell::Cell::new(0),
            last_viewport_height: std::cell::Cell::new(0),
            last_viewport_width: std::cell::Cell::new(0),
        }
    }

    // ── Event Handling ─────────────────────────────────────────────

    /// Handle a terminal event.
    ///
    /// Returns `true` if the state changed.
    pub fn handle_event(&mut self, event: &Event) -> bool {
        match event {
            Event::Key(key)
                if key.kind == KeyEventKind::Press || key.kind == KeyEventKind::Repeat =>
            {
                self.handle_key(key)
            }
            Event::Paste(paste) => {
                self.insert_text(&paste.text);
                true
            }
            _ => false,
        }
    }

    fn handle_key(&mut self, key: &KeyEvent) -> bool {
        let ctrl = key.modifiers.contains(Modifiers::CTRL);
        let shift = key.modifiers.contains(Modifiers::SHIFT);
        let _alt = key.modifiers.contains(Modifiers::ALT);

        match key.code {
            KeyCode::Char(c) if !ctrl => {
                self.insert_char(c);
                true
            }
            KeyCode::Enter => {
                self.insert_newline();
                true
            }
            KeyCode::Backspace => {
                if ctrl {
                    self.delete_word_backward();
                } else {
                    self.delete_backward();
                }
                true
            }
            KeyCode::Delete => {
                if ctrl {
                    self.delete_word_forward();
                } else {
                    self.delete_forward();
                }
                true
            }
            KeyCode::Left => {
                if ctrl && shift {
                    self.select_word_left();
                } else if ctrl {
                    self.move_word_left();
                } else if shift {
                    self.select_left();
                } else {
                    self.move_left();
                }
                true
            }
            KeyCode::Right => {
                if ctrl && shift {
                    self.select_word_right();
                } else if ctrl {
                    self.move_word_right();
                } else if shift {
                    self.select_right();
                } else {
                    self.move_right();
                }
                true
            }
            KeyCode::Up => {
                if shift {
                    self.select_up();
                } else {
                    self.move_up();
                }
                true
            }
            KeyCode::Down => {
                if shift {
                    self.select_down();
                } else {
                    self.move_down();
                }
                true
            }
            KeyCode::Home => {
                self.move_to_line_start();
                true
            }
            KeyCode::End => {
                self.move_to_line_end();
                true
            }
            KeyCode::PageUp => {
                let page = self.last_viewport_height.get().max(1);
                if self.soft_wrap {
                    self.move_cursor_visual_up(page, shift);
                } else {
                    for _ in 0..page {
                        if shift {
                            self.editor.select_up();
                        } else {
                            self.editor.move_up();
                        }
                    }
                }
                self.ensure_cursor_visible();
                true
            }
            KeyCode::PageDown => {
                let page = self.last_viewport_height.get().max(1);
                if self.soft_wrap {
                    self.move_cursor_visual_down(page, shift);
                } else {
                    for _ in 0..page {
                        if shift {
                            self.editor.select_down();
                        } else {
                            self.editor.move_down();
                        }
                    }
                }
                self.ensure_cursor_visible();
                true
            }
            KeyCode::Char('a') if ctrl => {
                self.select_all();
                true
            }
            // Ctrl+K: Delete to end of line (common emacs/shell binding)
            KeyCode::Char('k') if ctrl => {
                self.delete_to_end_of_line();
                true
            }
            // Ctrl+Z: Undo
            KeyCode::Char('z') if ctrl => {
                self.undo();
                true
            }
            // Ctrl+Y: Redo
            KeyCode::Char('y') if ctrl => {
                self.redo();
                true
            }
            _ => false,
        }
    }

    // ── Builder methods ────────────────────────────────────────────

    /// Set initial text content (builder).
    #[must_use]
    pub fn with_text(mut self, text: &str) -> Self {
        self.editor = Editor::with_text(text);
        self.editor.move_to_document_start();
        self
    }

    /// Set placeholder text (builder).
    #[must_use]
    pub fn with_placeholder(mut self, text: impl Into<String>) -> Self {
        self.placeholder = text.into();
        self
    }

    /// Set focused state (builder).
    #[must_use]
    pub fn with_focus(mut self, focused: bool) -> Self {
        self.focused = focused;
        self
    }

    /// Enable line numbers (builder).
    #[must_use]
    pub fn with_line_numbers(mut self, show: bool) -> Self {
        self.show_line_numbers = show;
        self
    }

    /// Set base style (builder).
    #[must_use]
    pub fn with_style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Set cursor line highlight style (builder).
    #[must_use]
    pub fn with_cursor_line_style(mut self, style: Style) -> Self {
        self.cursor_line_style = Some(style);
        self
    }

    /// Set selection style (builder).
    #[must_use]
    pub fn with_selection_style(mut self, style: Style) -> Self {
        self.selection_style = style;
        self
    }

    /// Enable soft wrapping (builder).
    #[must_use]
    pub fn with_soft_wrap(mut self, wrap: bool) -> Self {
        self.soft_wrap = wrap;
        self
    }

    /// Set maximum height in lines (builder). 0 = fill available area.
    #[must_use]
    pub fn with_max_height(mut self, max: usize) -> Self {
        self.max_height = max;
        self
    }

    // ── State access ───────────────────────────────────────────────

    /// Get the full text content.
    #[must_use]
    pub fn text(&self) -> String {
        self.editor.text()
    }

    /// Set the full text content (resets cursor and undo history).
    pub fn set_text(&mut self, text: &str) {
        self.editor.set_text(text);
        self.scroll_anchor.set((0, 0));
        self.scroll_left.set(0);
    }

    /// Number of lines.
    #[must_use]
    pub fn line_count(&self) -> usize {
        self.editor.line_count()
    }

    /// Current cursor position.
    #[inline]
    #[must_use]
    pub fn cursor(&self) -> CursorPosition {
        self.editor.cursor()
    }

    /// Set cursor position (clamped to bounds). Clears selection.
    pub fn set_cursor_position(&mut self, pos: CursorPosition) {
        self.editor.set_cursor(pos);
        self.ensure_cursor_visible();
    }

    /// Whether the textarea is empty.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.editor.is_empty()
    }

    /// Current selection, if any.
    #[must_use = "use the returned selection (if any)"]
    pub fn selection(&self) -> Option<Selection> {
        self.editor.selection()
    }

    /// Get selected text.
    #[must_use = "use the returned selected text (if any)"]
    pub fn selected_text(&self) -> Option<String> {
        self.editor.selected_text()
    }

    /// Whether the widget has focus.
    #[must_use]
    pub fn is_focused(&self) -> bool {
        self.focused
    }

    /// Set focus state.
    pub fn set_focused(&mut self, focused: bool) {
        self.focused = focused;
    }

    /// Access the underlying editor.
    #[must_use]
    pub fn editor(&self) -> &Editor {
        &self.editor
    }

    /// Mutable access to the underlying editor.
    pub fn editor_mut(&mut self) -> &mut Editor {
        &mut self.editor
    }

    // ── Editing operations (delegated to Editor) ───────────────────

    /// Insert text at cursor.
    pub fn insert_text(&mut self, text: &str) {
        self.editor.insert_text(text);
        self.ensure_cursor_visible();
    }

    /// Insert a single character.
    pub fn insert_char(&mut self, ch: char) {
        self.editor.insert_char(ch);
        self.ensure_cursor_visible();
    }

    /// Insert a newline.
    pub fn insert_newline(&mut self) {
        self.editor.insert_newline();
        self.ensure_cursor_visible();
    }

    /// Delete backward (backspace).
    pub fn delete_backward(&mut self) {
        self.editor.delete_backward();
        self.ensure_cursor_visible();
    }

    /// Delete forward (delete key).
    pub fn delete_forward(&mut self) {
        self.editor.delete_forward();
        self.ensure_cursor_visible();
    }

    /// Delete word backward (Ctrl+Backspace).
    pub fn delete_word_backward(&mut self) {
        self.editor.delete_word_backward();
        self.ensure_cursor_visible();
    }

    /// Delete word forward (Ctrl+Delete).
    pub fn delete_word_forward(&mut self) {
        self.editor.delete_word_forward();
        self.ensure_cursor_visible();
    }

    /// Delete to end of line (Ctrl+K).
    pub fn delete_to_end_of_line(&mut self) {
        self.editor.delete_to_end_of_line();
        self.ensure_cursor_visible();
    }

    /// Undo last edit.
    pub fn undo(&mut self) {
        self.editor.undo();
        self.ensure_cursor_visible();
    }

    /// Redo last undo.
    pub fn redo(&mut self) {
        self.editor.redo();
        self.ensure_cursor_visible();
    }

    // ── Navigation ─────────────────────────────────────────────────

    /// Move cursor left.
    pub fn move_left(&mut self) {
        self.editor.move_left();
        self.ensure_cursor_visible();
    }

    /// Move cursor right.
    pub fn move_right(&mut self) {
        self.editor.move_right();
        self.ensure_cursor_visible();
    }

    /// Move cursor up.
    pub fn move_up(&mut self) {
        if self.soft_wrap {
            self.move_cursor_visual_up(1, false);
        } else {
            self.editor.move_up();
        }
        self.ensure_cursor_visible();
    }

    /// Move cursor down.
    pub fn move_down(&mut self) {
        if self.soft_wrap {
            self.move_cursor_visual_down(1, false);
        } else {
            self.editor.move_down();
        }
        self.ensure_cursor_visible();
    }

    /// Move cursor left by word.
    pub fn move_word_left(&mut self) {
        self.editor.move_word_left();
        self.ensure_cursor_visible();
    }

    /// Move cursor right by word.
    pub fn move_word_right(&mut self) {
        self.editor.move_word_right();
        self.ensure_cursor_visible();
    }

    /// Extend selection left by word.
    pub fn select_word_left(&mut self) {
        self.editor.select_word_left();
        self.ensure_cursor_visible();
    }

    /// Extend selection right by word.
    pub fn select_word_right(&mut self) {
        self.editor.select_word_right();
        self.ensure_cursor_visible();
    }

    /// Move to start of line.
    pub fn move_to_line_start(&mut self) {
        self.editor.move_to_line_start();
        self.ensure_cursor_visible();
    }

    /// Move to end of line.
    pub fn move_to_line_end(&mut self) {
        self.editor.move_to_line_end();
        self.ensure_cursor_visible();
    }

    /// Move to start of document.
    pub fn move_to_document_start(&mut self) {
        self.editor.move_to_document_start();
        self.ensure_cursor_visible();
    }

    /// Move cursor to end of document.
    pub fn move_to_document_end(&mut self) {
        self.editor.move_to_document_end();
        self.ensure_cursor_visible();
    }

    fn move_cursor_visual_down(&mut self, count: usize, extend_selection: bool) {
        let width = self.last_viewport_width.get();
        if width == 0 {
            for _ in 0..count {
                if extend_selection {
                    self.editor.select_down();
                } else {
                    self.editor.move_down();
                }
            }
            return;
        }

        let rope = self.editor.rope();
        let mut cursor = self.editor.cursor();
        let mut remaining = count;

        let line_text = rope
            .line(cursor.line)
            .unwrap_or(std::borrow::Cow::Borrowed(""));
        let line_text = line_text.trim_end_matches(['\n', '\r']);
        let (mut current_v_row, _) =
            Self::cursor_wrap_position(line_text, width, cursor.visual_col);

        // Calculate target screen X (relative to slice start) to preserve column
        let initial_slices = Self::wrap_line_slices(line_text, width);
        let initial_slice_start = initial_slices
            .get(current_v_row)
            .map(|s| s.start_col)
            .unwrap_or(0);
        let target_screen_x = cursor.visual_col.saturating_sub(initial_slice_start);

        while remaining > 0 {
            let line_text = rope
                .line(cursor.line)
                .unwrap_or(std::borrow::Cow::Borrowed(""));
            let line_text = line_text.trim_end_matches(['\n', '\r']);
            let wrap_count = Self::measure_wrap_count(line_text, width);

            let available_in_line = wrap_count.saturating_sub(1).saturating_sub(current_v_row);

            if remaining <= available_in_line {
                current_v_row += remaining;
                remaining = 0;
            } else {
                remaining -= available_in_line + 1;
                if cursor.line + 1 < self.editor.line_count() {
                    cursor.line += 1;
                    current_v_row = 0;
                } else {
                    current_v_row = wrap_count.saturating_sub(1);
                    remaining = 0;
                }
            }
        }

        let line_text = rope
            .line(cursor.line)
            .unwrap_or(std::borrow::Cow::Borrowed(""));
        let line_text = line_text.trim_end_matches(['\n', '\r']);
        let slices = Self::wrap_line_slices(line_text, width);

        if let Some(slice) = slices.get(current_v_row) {
            let target_in_slice = target_screen_x.min(slice.width);

            let mut g_idx = 0;
            let mut v_w = 0;
            for g in slice.text.graphemes(true) {
                let w = display_width(g);
                if v_w + w > target_in_slice {
                    break;
                }
                v_w += w;
                g_idx += 1;
            }

            let nav = CursorNavigator::new(rope);
            let line_start_byte = nav.to_byte_index(nav.from_line_grapheme(cursor.line, 0));
            let slice_byte_offset: usize = slice
                .text
                .graphemes(true)
                .take(g_idx)
                .map(|g| g.len())
                .sum();
            let final_byte = line_start_byte + slice.start_byte + slice_byte_offset;
            cursor = nav.from_byte_index(final_byte);
        }

        if extend_selection {
            self.editor.extend_selection_to(cursor);
        } else {
            self.editor.set_cursor(cursor);
        }
    }

    fn move_cursor_visual_up(&mut self, count: usize, extend_selection: bool) {
        let width = self.last_viewport_width.get();
        if width == 0 {
            for _ in 0..count {
                if extend_selection {
                    self.editor.select_up();
                } else {
                    self.editor.move_up();
                }
            }
            return;
        }

        let rope = self.editor.rope();
        let mut cursor = self.editor.cursor();
        let mut remaining = count;

        let line_text = rope
            .line(cursor.line)
            .unwrap_or(std::borrow::Cow::Borrowed(""));
        let line_text = line_text.trim_end_matches(['\n', '\r']);
        let (mut current_v_row, _) =
            Self::cursor_wrap_position(line_text, width, cursor.visual_col);

        // Calculate target screen X (relative to slice start) to preserve column
        let initial_slices = Self::wrap_line_slices(line_text, width);
        let initial_slice_start = initial_slices
            .get(current_v_row)
            .map(|s| s.start_col)
            .unwrap_or(0);
        let target_screen_x = cursor.visual_col.saturating_sub(initial_slice_start);

        while remaining > 0 {
            if remaining <= current_v_row {
                current_v_row -= remaining;
                remaining = 0;
            } else {
                remaining -= current_v_row + 1;
                if cursor.line > 0 {
                    cursor.line -= 1;
                    let line_text = rope
                        .line(cursor.line)
                        .unwrap_or(std::borrow::Cow::Borrowed(""));
                    let line_text = line_text.trim_end_matches(['\n', '\r']);
                    let wrap_count = Self::measure_wrap_count(line_text, width);
                    current_v_row = wrap_count.saturating_sub(1);
                } else {
                    current_v_row = 0;
                    remaining = 0;
                }
            }
        }

        let line_text = rope
            .line(cursor.line)
            .unwrap_or(std::borrow::Cow::Borrowed(""));
        let line_text = line_text.trim_end_matches(['\n', '\r']);
        let slices = Self::wrap_line_slices(line_text, width);

        if let Some(slice) = slices.get(current_v_row) {
            let target_in_slice = target_screen_x.min(slice.width);

            let mut g_idx = 0;
            let mut v_w = 0;
            for g in slice.text.graphemes(true) {
                let w = display_width(g);
                if v_w + w > target_in_slice {
                    break;
                }
                v_w += w;
                g_idx += 1;
            }

            let nav = CursorNavigator::new(rope);
            let line_start_byte = nav.to_byte_index(nav.from_line_grapheme(cursor.line, 0));
            let slice_byte_offset: usize = slice
                .text
                .graphemes(true)
                .take(g_idx)
                .map(|g| g.len())
                .sum();
            let final_byte = line_start_byte + slice.start_byte + slice_byte_offset;
            cursor = nav.from_byte_index(final_byte);
        }

        if extend_selection {
            self.editor.extend_selection_to(cursor);
        } else {
            self.editor.set_cursor(cursor);
        }
    }

    // ── Selection ──────────────────────────────────────────────────

    /// Extend selection left.
    pub fn select_left(&mut self) {
        self.editor.select_left();
        self.ensure_cursor_visible();
    }

    /// Extend selection right.
    pub fn select_right(&mut self) {
        self.editor.select_right();
        self.ensure_cursor_visible();
    }

    /// Extend selection up.
    pub fn select_up(&mut self) {
        if self.soft_wrap {
            self.move_cursor_visual_up(1, true);
        } else {
            self.editor.select_up();
        }
        self.ensure_cursor_visible();
    }

    /// Extend selection down.
    pub fn select_down(&mut self) {
        if self.soft_wrap {
            self.move_cursor_visual_down(1, true);
        } else {
            self.editor.select_down();
        }
        self.ensure_cursor_visible();
    }

    /// Select all.
    pub fn select_all(&mut self) {
        self.editor.select_all();
    }

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

    // ── Viewport management ────────────────────────────────────────

    /// Page up (move viewport and cursor up by viewport height).
    pub fn page_up(&mut self, state: &TextAreaState) {
        let page = state.last_viewport_height.max(1) as usize;
        let text_area_width = state
            .last_viewport_width
            .saturating_sub(self.gutter_width());
        self.last_viewport_height.set(page);
        self.last_viewport_width.set(text_area_width as usize);
        if self.soft_wrap {
            if text_area_width > 0 {
                self.move_cursor_visual_up(page, false);
            } else {
                for _ in 0..page {
                    self.editor.move_up();
                }
            }
        } else {
            for _ in 0..page {
                self.editor.move_up();
            }
        }
        self.ensure_cursor_visible();
    }

    /// Page down (move viewport and cursor down by viewport height).
    pub fn page_down(&mut self, state: &TextAreaState) {
        let page = state.last_viewport_height.max(1) as usize;
        let text_area_width = state
            .last_viewport_width
            .saturating_sub(self.gutter_width());
        self.last_viewport_height.set(page);
        self.last_viewport_width.set(text_area_width as usize);
        if self.soft_wrap {
            if text_area_width > 0 {
                self.move_cursor_visual_down(page, false);
            } else {
                for _ in 0..page {
                    self.editor.move_down();
                }
            }
        } else {
            for _ in 0..page {
                self.editor.move_down();
            }
        }
        self.ensure_cursor_visible();
    }

    /// Width of the line number gutter.
    fn gutter_width(&self) -> u16 {
        if !self.show_line_numbers {
            return 0;
        }
        let digits = {
            let mut count = self.line_count().max(1);
            let mut d: u16 = 0;
            while count > 0 {
                d += 1;
                count /= 10;
            }
            d
        };
        digits + 2 // digit width + space + separator
    }

    /// Count how many wrapped lines this text will occupy.
    ///
    /// This is a zero-allocation version of `wrap_line_slices` for layout calculations.
    fn measure_wrap_count(line_text: &str, max_width: usize) -> usize {
        if line_text.is_empty() {
            return 1;
        }

        let mut count = 0;
        let mut current_width = 0;
        let mut has_content = false;

        Self::run_wrapping_logic(line_text, max_width, |_, width, flush| {
            if flush {
                if width > 0 {
                    count += 1;
                }
                current_width = 0;
                has_content = false;
            } else {
                current_width = width;
                has_content = true;
            }
        });

        // If there's pending content or if we flushed but started a new empty line (which shouldn't happen with this logic usually,
        // but let's be safe), count the last line.
        // Actually run_wrapping_logic only flushes when a line is full.
        // We need to count the current line if it has content or if it's the only line.
        if has_content || count == 0 {
            count += 1;
        }

        count
    }

    /// Core wrapping logic that emits events for layout or slicing.
    ///
    /// The callback receives `(start_index, width, flush)`.
    /// - `flush == true`: The current line is full/done. `width` is the width of the flushed line.
    /// - `flush == false`: Update current line width.
    fn run_wrapping_logic<F>(line_text: &str, max_width: usize, mut callback: F)
    where
        F: FnMut(usize, usize, bool),
    {
        let mut current_width = 0;
        let mut byte_cursor = 0;

        for segment in line_text.split_word_bounds() {
            let seg_len = segment.len();
            let seg_width: usize = segment.graphemes(true).map(display_width).sum();

            if max_width > 0 && current_width + seg_width > max_width {
                // Flush current
                callback(byte_cursor, current_width, true);
                current_width = 0;
            }

            if max_width > 0 && seg_width > max_width {
                for grapheme in segment.graphemes(true) {
                    let g_width = display_width(grapheme);
                    let g_len = grapheme.len();

                    if max_width > 0 && current_width + g_width > max_width && current_width > 0 {
                        callback(byte_cursor, current_width, true);
                        current_width = 0;
                    }

                    current_width += g_width;
                    byte_cursor += g_len;
                    callback(byte_cursor, current_width, false);
                }
                continue;
            }

            current_width += seg_width;
            byte_cursor += seg_len;
            callback(byte_cursor, current_width, false);
        }
    }

    fn wrap_line_slices<'a>(line_text: &'a str, max_width: usize) -> Vec<WrappedSlice<'a>> {
        if line_text.is_empty() {
            return vec![WrappedSlice {
                text: "",
                start_byte: 0,
                start_col: 0,
                width: 0,
            }];
        }

        let mut slices = Vec::new();
        let mut current_width = 0;
        let mut slice_start_byte = 0;
        let mut slice_start_col = 0;
        let mut byte_cursor = 0;
        let mut col_cursor = 0;

        let push_current = |slices: &mut Vec<WrappedSlice<'a>>,
                            width: &mut usize,
                            start_byte: &mut usize,
                            start_col: &mut usize,
                            byte_cursor: usize,
                            col_cursor: usize| {
            if byte_cursor == *start_byte && *width == 0 {
                return;
            }
            slices.push(WrappedSlice {
                text: &line_text[*start_byte..byte_cursor],
                start_byte: *start_byte,
                start_col: *start_col,
                width: *width,
            });
            *start_byte = byte_cursor;
            *start_col = col_cursor;
            *width = 0;
        };

        for segment in line_text.split_word_bounds() {
            let seg_len = segment.len();
            let seg_width: usize = segment.graphemes(true).map(display_width).sum();

            if max_width > 0 && current_width + seg_width > max_width {
                push_current(
                    &mut slices,
                    &mut current_width,
                    &mut slice_start_byte,
                    &mut slice_start_col,
                    byte_cursor,
                    col_cursor,
                );
            }

            if max_width > 0 && seg_width > max_width {
                for grapheme in segment.graphemes(true) {
                    let g_width = display_width(grapheme);
                    let g_len = grapheme.len();

                    if max_width > 0 && current_width + g_width > max_width && current_width > 0 {
                        push_current(
                            &mut slices,
                            &mut current_width,
                            &mut slice_start_byte,
                            &mut slice_start_col,
                            byte_cursor,
                            col_cursor,
                        );
                    }

                    current_width += g_width;
                    byte_cursor += g_len;
                    col_cursor += g_width;
                }
                continue;
            }

            current_width += seg_width;
            byte_cursor += seg_len;
            col_cursor += seg_width;
        }

        if byte_cursor > slice_start_byte || current_width > 0 || slices.is_empty() {
            slices.push(WrappedSlice {
                text: &line_text[slice_start_byte..byte_cursor],
                start_byte: slice_start_byte,
                start_col: slice_start_col,
                width: current_width,
            });
        }

        slices
    }

    fn cursor_wrap_position(
        line_text: &str,
        max_width: usize,
        cursor_col: usize,
    ) -> (usize, usize) {
        let slices = Self::wrap_line_slices(line_text, max_width);
        if slices.is_empty() {
            return (0, 0);
        }

        for (idx, slice) in slices.iter().enumerate() {
            let end_col = slice.start_col.saturating_add(slice.width);
            // If cursor is at the wrap boundary (equal to end_col), we prefer the start
            // of the *next* slice (by skipping this one) unless this is the last slice.
            let is_last = idx == slices.len().saturating_sub(1);
            if cursor_col < end_col || (cursor_col == end_col && is_last) {
                let col_in_slice = cursor_col.saturating_sub(slice.start_col);
                return (idx, col_in_slice.min(slice.width));
            }
        }

        (0, 0)
    }

    /// Get the visual width of the character immediately before the cursor.
    fn get_prev_char_width(&self) -> usize {
        let cursor = self.editor.cursor();
        if cursor.grapheme == 0 {
            return 0;
        }
        let rope = self.editor.rope();
        let line = rope
            .line(cursor.line)
            .unwrap_or(std::borrow::Cow::Borrowed(""));

        line.graphemes(true)
            .nth(cursor.grapheme - 1)
            .map(display_width)
            .unwrap_or(0)
    }

    /// Ensure the cursor line and column are visible in the viewport.
    fn ensure_cursor_visible(&self) {
        let cursor = self.editor.cursor();

        let last_height = self.last_viewport_height.get();
        let vp_height = if last_height == 0 { 20 } else { last_height };

        let last_width = self.last_viewport_width.get();
        let vp_width = if last_width == 0 { 80 } else { last_width };

        if self.scroll_anchor.get().0 == usize::MAX {
            self.scroll_anchor.set((0, 0));
        }

        self.ensure_cursor_visible_internal(vp_height, vp_width, cursor);
    }

    fn ensure_cursor_visible_internal(
        &self,
        vp_height: usize,
        vp_width: usize,
        cursor: CursorPosition,
    ) {
        let (anchor_line, anchor_vrow) = self.scroll_anchor.get();

        if !self.soft_wrap {
            // Vertical scroll (logical lines)
            if cursor.line < anchor_line {
                self.scroll_anchor.set((cursor.line, 0));
            } else if vp_height > 0 && cursor.line >= anchor_line + vp_height {
                self.scroll_anchor
                    .set((cursor.line.saturating_sub(vp_height - 1), 0));
            }

            // Horizontal scroll
            let current_left = self.scroll_left.get();
            let visual_col = cursor.visual_col;

            if visual_col < current_left {
                self.scroll_left.set(visual_col);
            } else if vp_width > 0 && visual_col >= current_left + vp_width {
                let candidate_scroll = visual_col.saturating_sub(vp_width - 1);
                let prev_width = self.get_prev_char_width();
                let max_scroll_for_prev = visual_col.saturating_sub(prev_width);

                let new_scroll = if vp_width > prev_width {
                    candidate_scroll.min(max_scroll_for_prev)
                } else {
                    candidate_scroll
                };

                self.scroll_left.set(new_scroll);
            }
            return;
        }

        // Soft wrap logic
        let rope = self.editor.rope();

        // 1. Is cursor before anchor?
        if cursor.line < anchor_line {
            let line_text = rope
                .line(cursor.line)
                .unwrap_or(std::borrow::Cow::Borrowed(""));
            let line_text = line_text.trim_end_matches(['\n', '\r']);
            let (v_row, _) = Self::cursor_wrap_position(line_text, vp_width, cursor.visual_col);
            self.scroll_anchor.set((cursor.line, v_row));
            return;
        }

        if cursor.line == anchor_line {
            let line_text = rope
                .line(cursor.line)
                .unwrap_or(std::borrow::Cow::Borrowed(""));
            let line_text = line_text.trim_end_matches(['\n', '\r']);
            let (v_row, _) = Self::cursor_wrap_position(line_text, vp_width, cursor.visual_col);
            if v_row < anchor_vrow {
                self.scroll_anchor.set((cursor.line, v_row));
                return;
            }
        }

        // 2. Is cursor after viewport? Trace forward from anchor.
        let mut visual_rows_capacity = vp_height;
        let mut current_line = anchor_line;
        let mut current_v_start = anchor_vrow;

        loop {
            if current_line > cursor.line {
                // Reached past cursor line without exhausting capacity -> Visible.
                return;
            }

            let line_text = rope
                .line(current_line)
                .unwrap_or(std::borrow::Cow::Borrowed(""));
            let line_text = line_text.trim_end_matches(['\n', '\r']);
            let wrap_count = Self::measure_wrap_count(line_text, vp_width);

            if current_line == cursor.line {
                let (cursor_v_row, _) =
                    Self::cursor_wrap_position(line_text, vp_width, cursor.visual_col);
                if cursor_v_row >= current_v_start {
                    let displayed_row_index = cursor_v_row - current_v_start;
                    if displayed_row_index < visual_rows_capacity {
                        // Visible.
                        return;
                    } else {
                        // Not visible (below).
                        break;
                    }
                } else {
                    // Cursor is before the anchor start? Handled by step 1.
                    return;
                }
            }

            let rows_remaining_in_line = wrap_count.saturating_sub(current_v_start);
            if rows_remaining_in_line >= visual_rows_capacity {
                break;
            }

            visual_rows_capacity -= rows_remaining_in_line;
            current_line += 1;
            current_v_start = 0;

            if current_line >= self.editor.line_count() {
                break;
            }
        }

        // 3. Scroll Down (Backwards Scan)
        let mut needed = vp_height;
        let mut scan_line = cursor.line;

        // For the cursor line itself
        let line_text = rope
            .line(scan_line)
            .unwrap_or(std::borrow::Cow::Borrowed(""));
        let line_text = line_text.trim_end_matches(['\n', '\r']);
        let (cursor_v, _) = Self::cursor_wrap_position(line_text, vp_width, cursor.visual_col);

        let rows_above = cursor_v + 1;
        if rows_above >= needed {
            let new_v_start = cursor_v + 1 - needed;
            self.scroll_anchor.set((scan_line, new_v_start));
            return;
        }

        needed -= rows_above;

        // Scan previous lines
        while scan_line > 0 {
            scan_line -= 1;
            let line_text = rope
                .line(scan_line)
                .unwrap_or(std::borrow::Cow::Borrowed(""));
            let line_text = line_text.trim_end_matches(['\n', '\r']);
            let wrap_count = Self::measure_wrap_count(line_text, vp_width);

            if wrap_count >= needed {
                let new_v_start = wrap_count - needed;
                self.scroll_anchor.set((scan_line, new_v_start));
                return;
            }
            needed -= wrap_count;
        }

        // Reached top
        self.scroll_anchor.set((0, 0));
    }
}

impl Widget for TextArea {
    fn render(&self, area: Rect, frame: &mut Frame) {
        if area.width < 1 || area.height < 1 {
            return;
        }

        self.last_viewport_height.set(area.height as usize);

        let deg = frame.buffer.degradation;
        let base_style = if deg.apply_styling() {
            self.style
        } else {
            Style::default()
        };
        clear_text_area(frame, area, base_style);

        let gutter_w = self.gutter_width();
        let text_area_x = area.x.saturating_add(gutter_w);
        let text_area_w = area.width.saturating_sub(gutter_w) as usize;
        let vp_height = area.height as usize;

        self.last_viewport_width.set(text_area_w);

        let cursor = self.editor.cursor();

        self.ensure_cursor_visible();

        // Re-fetch potentially updated anchor
        let (scroll_top_line, scroll_top_vrow) = self.scroll_anchor.get();
        let scroll_left = self.scroll_left.get();

        let rope = self.editor.rope();
        let nav = CursorNavigator::new(rope);

        // Selection byte range for highlighting
        let sel_range = self.editor.selection().and_then(|sel| {
            if sel.is_empty() {
                None
            } else {
                let (a, b) = sel.byte_range(&nav);
                Some((a, b))
            }
        });

        // Show placeholder if empty
        if self.editor.is_empty() && !self.placeholder.is_empty() {
            let style = if deg.apply_styling() {
                self.placeholder_style
            } else {
                Style::default()
            };
            draw_text_span(
                frame,
                text_area_x,
                area.y,
                &self.placeholder,
                style,
                area.right(),
            );
            if self.focused {
                frame.set_cursor(Some((text_area_x, area.y)));
            }
            return;
        }

        if self.soft_wrap {
            self.scroll_left.set(0);

            // Pre-calculate cursor wrap position
            let cursor_line_text = rope
                .line(cursor.line)
                .unwrap_or(std::borrow::Cow::Borrowed(""));
            let cursor_line_text = cursor_line_text.trim_end_matches(['\n', '\r']);
            let (cursor_wrap_idx, cursor_col_in_wrap) =
                Self::cursor_wrap_position(cursor_line_text, text_area_w, cursor.visual_col);

            // Render wrapped lines starting from anchor
            let mut current_y = area.y;
            let bottom_y = area.bottom();
            let line_count = self.editor.line_count();

            for line_idx in scroll_top_line..line_count {
                if current_y >= bottom_y {
                    break;
                }

                let line_text = rope
                    .line(line_idx)
                    .unwrap_or(std::borrow::Cow::Borrowed(""));
                let line_text = line_text.trim_end_matches(['\n', '\r']);

                let line_start_byte = nav.to_byte_index(nav.from_line_grapheme(line_idx, 0));
                let slices = Self::wrap_line_slices(line_text, text_area_w);

                // If this is the start line, skip slices before anchor_vrow
                let start_slice = if line_idx == scroll_top_line {
                    scroll_top_vrow
                } else {
                    0
                };

                for (slice_idx, slice) in slices.iter().enumerate().skip(start_slice) {
                    if current_y >= bottom_y {
                        break;
                    }

                    // Line number gutter (only for first wrapped slice of the line)
                    if self.show_line_numbers && slice_idx == 0 {
                        let style = if deg.apply_styling() {
                            self.line_number_style
                        } else {
                            Style::default()
                        };
                        let num_str =
                            format!("{:>width$} ", line_idx + 1, width = (gutter_w - 2) as usize);
                        draw_text_span(frame, area.x, current_y, &num_str, style, text_area_x);
                    }

                    // Cursor line highlight
                    if line_idx == cursor.line
                        && slice_idx == cursor_wrap_idx
                        && let Some(cl_style) = self.cursor_line_style
                        && deg.apply_styling()
                    {
                        for cx in text_area_x..area.right() {
                            if let Some(cell) = frame.buffer.get_mut(cx, current_y) {
                                apply_style(cell, cl_style);
                            }
                        }
                    }

                    // Render graphemes inside the wrapped slice
                    let mut visual_x: usize = 0;
                    let mut grapheme_byte_offset = line_start_byte + slice.start_byte;

                    for g in slice.text.graphemes(true) {
                        let g_width = display_width(g);
                        let g_byte_len = g.len();

                        if visual_x >= text_area_w {
                            break;
                        }

                        let px = text_area_x + visual_x as u16;

                        // Determine style (selection highlight)
                        let mut g_style = base_style;
                        if let Some((sel_start, sel_end)) = sel_range
                            && grapheme_byte_offset >= sel_start
                            && grapheme_byte_offset < sel_end
                            && deg.apply_styling()
                        {
                            g_style = g_style.merge(&self.selection_style);
                        }

                        if g_width > 0 {
                            draw_text_span(frame, px, current_y, g, g_style, area.right());
                        }

                        visual_x += g_width;
                        grapheme_byte_offset += g_byte_len;
                    }

                    // Set cursor position if focused
                    if self.focused && line_idx == cursor.line && slice_idx == cursor_wrap_idx {
                        let cursor_screen_x = text_area_x.saturating_add(cursor_col_in_wrap as u16);
                        if cursor_screen_x < area.right() {
                            frame.set_cursor(Some((cursor_screen_x, current_y)));
                        }
                    }

                    current_y += 1;
                }
            }

            return;
        }

        // Render visible lines (no soft wrap)
        for row in 0..vp_height {
            let line_idx = scroll_top_line + row;
            let y = area.y.saturating_add(row as u16);

            if line_idx >= self.editor.line_count() {
                break;
            }

            // Line number gutter
            if self.show_line_numbers {
                let style = if deg.apply_styling() {
                    self.line_number_style
                } else {
                    Style::default()
                };
                let num_str = format!("{:>width$} ", line_idx + 1, width = (gutter_w - 2) as usize);
                draw_text_span(frame, area.x, y, &num_str, style, text_area_x);
            }

            // Cursor line highlight
            if line_idx == cursor.line
                && let Some(cl_style) = self.cursor_line_style
                && deg.apply_styling()
            {
                for cx in text_area_x..area.right() {
                    if let Some(cell) = frame.buffer.get_mut(cx, y) {
                        apply_style(cell, cl_style);
                    }
                }
            }

            // Get line text
            let line_text = rope
                .line(line_idx)
                .unwrap_or(std::borrow::Cow::Borrowed(""));
            let line_text = line_text.trim_end_matches(['\n', '\r']);

            // Calculate line byte offset for selection mapping
            let line_start_byte = nav.to_byte_index(nav.from_line_grapheme(line_idx, 0));

            // Render each grapheme
            let mut visual_x: usize = 0;
            let graphemes: Vec<&str> = line_text.graphemes(true).collect();
            let mut grapheme_byte_offset = line_start_byte;

            for g in &graphemes {
                let g_width = display_width(g);
                let g_byte_len = g.len();

                // Determine style (selection highlight)
                let mut g_style = base_style;
                if let Some((sel_start, sel_end)) = sel_range
                    && grapheme_byte_offset >= sel_start
                    && grapheme_byte_offset < sel_end
                    && deg.apply_styling()
                {
                    g_style = g_style.merge(&self.selection_style);
                }

                // Skip graphemes before horizontal scroll
                if visual_x + g_width <= scroll_left {
                    visual_x += g_width;
                    grapheme_byte_offset += g_byte_len;
                    continue;
                }

                // Handle partial overlap at left edge
                if visual_x < scroll_left {
                    // Calculate visible width of the partially scrolled grapheme
                    let end_x = visual_x + g_width;
                    let visible_width = end_x.saturating_sub(scroll_left);

                    // Render padding spaces for the visible portion to preserve background style
                    for i in 0..visible_width {
                        let screen_x = i; // Starts at 0 relative to text area
                        let px = text_area_x + screen_x as u16;
                        if px < area.right() {
                            draw_text_span(frame, px, y, " ", g_style, area.right());
                        }
                    }

                    visual_x += g_width;
                    grapheme_byte_offset += g_byte_len;
                    continue;
                }

                // Stop if past viewport
                let screen_x = visual_x.saturating_sub(scroll_left);
                if screen_x >= text_area_w {
                    break;
                }

                let px = text_area_x + screen_x as u16;

                // Write grapheme to buffer
                if g_width > 0 {
                    draw_text_span(frame, px, y, g, g_style, area.right());
                }

                visual_x += g_width;
                grapheme_byte_offset += g_byte_len;
            }
        }

        // Set cursor position if focused
        if self.focused {
            let cursor_row = cursor.line.saturating_sub(scroll_top_line);
            if cursor_row < vp_height {
                let cursor_screen_x = (cursor.visual_col.saturating_sub(scroll_left) as u16)
                    .saturating_add(text_area_x);
                let cursor_screen_y = area.y.saturating_add(cursor_row as u16);
                if cursor_screen_x < area.right() && cursor_screen_y < area.bottom() {
                    frame.set_cursor(Some((cursor_screen_x, cursor_screen_y)));
                }
            }
        }
    }

    fn is_essential(&self) -> bool {
        true
    }
}

impl StatefulWidget for TextArea {
    type State = TextAreaState;

    fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
        state.last_viewport_height = area.height;
        state.last_viewport_width = area.width;
        Widget::render(self, area, frame);
    }
}

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

    fn raw_row_text(frame: &Frame, y: u16, width: u16) -> String {
        (0..width)
            .map(|x| {
                frame
                    .buffer
                    .get(x, y)
                    .and_then(|cell| cell.content.as_char())
                    .unwrap_or(' ')
            })
            .collect()
    }

    #[test]
    fn new_textarea_is_empty() {
        let ta = TextArea::new();
        assert!(ta.is_empty());
        assert_eq!(ta.text(), "");
        assert_eq!(ta.line_count(), 1); // empty rope has 1 line
    }

    #[test]
    fn with_text_builder() {
        let ta = TextArea::new().with_text("hello\nworld");
        assert_eq!(ta.text(), "hello\nworld");
        assert_eq!(ta.line_count(), 2);
    }

    #[test]
    fn insert_text_and_newline() {
        let mut ta = TextArea::new();
        ta.insert_text("hello");
        ta.insert_newline();
        ta.insert_text("world");
        assert_eq!(ta.text(), "hello\nworld");
        assert_eq!(ta.line_count(), 2);
    }

    #[test]
    fn delete_backward_works() {
        let mut ta = TextArea::new().with_text("hello");
        ta.move_to_document_end();
        ta.delete_backward();
        assert_eq!(ta.text(), "hell");
    }

    #[test]
    fn cursor_movement() {
        let mut ta = TextArea::new().with_text("abc\ndef\nghi");
        ta.move_to_document_start();
        assert_eq!(ta.cursor().line, 0);
        assert_eq!(ta.cursor().grapheme, 0);

        ta.move_down();
        assert_eq!(ta.cursor().line, 1);

        ta.move_to_line_end();
        assert_eq!(ta.cursor().grapheme, 3);

        ta.move_to_document_end();
        assert_eq!(ta.cursor().line, 2);
    }

    #[test]
    fn undo_redo() {
        let mut ta = TextArea::new();
        ta.insert_text("abc");
        assert_eq!(ta.text(), "abc");
        ta.undo();
        assert_eq!(ta.text(), "");
        ta.redo();
        assert_eq!(ta.text(), "abc");
    }

    #[test]
    fn selection_and_delete() {
        let mut ta = TextArea::new().with_text("hello world");
        ta.move_to_document_start();
        for _ in 0..5 {
            ta.select_right();
        }
        assert_eq!(ta.selected_text(), Some("hello".to_string()));
        ta.delete_backward();
        assert_eq!(ta.text(), " world");
    }

    #[test]
    fn select_all() {
        let mut ta = TextArea::new().with_text("abc\ndef");
        ta.select_all();
        assert_eq!(ta.selected_text(), Some("abc\ndef".to_string()));
    }

    #[test]
    fn set_text_resets() {
        let mut ta = TextArea::new().with_text("old");
        ta.insert_text(" stuff");
        ta.set_text("new");
        assert_eq!(ta.text(), "new");
    }

    #[test]
    fn scroll_follows_cursor() {
        let mut ta = TextArea::new();
        // Insert many lines
        for i in 0..50 {
            ta.insert_text(&format!("line {}\n", i));
        }
        // Cursor should be at the bottom, scroll anchor adjusted.
        assert!(ta.scroll_anchor.get().0 > 0);
        assert!(ta.cursor().line >= 49);

        // Move to top
        ta.move_to_document_start();
        assert_eq!(ta.scroll_anchor.get().0, 0);
    }

    #[test]
    fn gutter_width_without_line_numbers() {
        let ta = TextArea::new();
        assert_eq!(ta.gutter_width(), 0);
    }

    #[test]
    fn gutter_width_with_line_numbers() {
        let mut ta = TextArea::new().with_line_numbers(true);
        ta.insert_text("a\nb\nc");
        assert_eq!(ta.gutter_width(), 3); // 1 digit + space + separator
    }

    #[test]
    fn gutter_width_many_lines() {
        let mut ta = TextArea::new().with_line_numbers(true);
        for i in 0..100 {
            ta.insert_text(&format!("line {}\n", i));
        }
        assert_eq!(ta.gutter_width(), 5); // 3 digits + space + separator
    }

    #[test]
    fn focus_state() {
        let mut ta = TextArea::new();
        assert!(!ta.is_focused());
        ta.set_focused(true);
        assert!(ta.is_focused());
    }

    #[test]
    fn word_movement() {
        let mut ta = TextArea::new().with_text("hello world foo");
        ta.move_to_document_start();
        ta.move_word_right();
        assert_eq!(ta.cursor().grapheme, 6);
        ta.move_word_left();
        assert_eq!(ta.cursor().grapheme, 0);
    }

    #[test]
    fn page_up_down() {
        let mut ta = TextArea::new();
        for i in 0..50 {
            ta.insert_text(&format!("line {}\n", i));
        }
        ta.move_to_document_start();
        let state = TextAreaState {
            last_viewport_height: 10,
            last_viewport_width: 80,
        };
        ta.page_down(&state);
        assert!(ta.cursor().line >= 10);
        ta.page_up(&state);
        assert_eq!(ta.cursor().line, 0);
    }

    #[test]
    fn insert_replaces_selection() {
        let mut ta = TextArea::new().with_text("hello world");
        ta.move_to_document_start();
        for _ in 0..5 {
            ta.select_right();
        }
        ta.insert_text("goodbye");
        assert_eq!(ta.text(), "goodbye world");
    }

    #[test]
    fn insert_single_char() {
        let mut ta = TextArea::new();
        ta.insert_char('X');
        assert_eq!(ta.text(), "X");
        assert_eq!(ta.cursor().grapheme, 1);
    }

    #[test]
    fn insert_multiline_text() {
        let mut ta = TextArea::new();
        ta.insert_text("line1\nline2\nline3");
        assert_eq!(ta.line_count(), 3);
        assert_eq!(ta.cursor().line, 2);
    }

    #[test]
    fn delete_forward_works() {
        let mut ta = TextArea::new().with_text("hello");
        ta.move_to_document_start();
        ta.delete_forward();
        assert_eq!(ta.text(), "ello");
    }

    #[test]
    fn delete_backward_at_line_start_joins_lines() {
        let mut ta = TextArea::new().with_text("abc\ndef");
        // Move to start of line 2
        ta.move_to_document_start();
        ta.move_down();
        ta.move_to_line_start();
        ta.delete_backward();
        assert_eq!(ta.text(), "abcdef");
        assert_eq!(ta.line_count(), 1);
    }

    #[test]
    fn cursor_horizontal_movement() {
        let mut ta = TextArea::new().with_text("abc");
        ta.move_to_document_start();
        ta.move_right();
        assert_eq!(ta.cursor().grapheme, 1);
        ta.move_right();
        assert_eq!(ta.cursor().grapheme, 2);
        ta.move_left();
        assert_eq!(ta.cursor().grapheme, 1);
    }

    #[test]
    fn cursor_vertical_maintains_column() {
        let mut ta = TextArea::new().with_text("abcde\nfg\nhijkl");
        ta.move_to_document_start();
        ta.move_to_line_end(); // col 5
        ta.move_down(); // line 1 only has 2 chars, should clamp
        assert_eq!(ta.cursor().line, 1);
        ta.move_down(); // line 2 has 5 chars, should restore col
        assert_eq!(ta.cursor().line, 2);
    }

    #[test]
    fn selection_shift_arrow() {
        let mut ta = TextArea::new().with_text("abcdef");
        ta.move_to_document_start();
        ta.select_right();
        ta.select_right();
        ta.select_right();
        assert_eq!(ta.selected_text(), Some("abc".to_string()));
    }

    #[test]
    fn selection_extends_up_down() {
        let mut ta = TextArea::new().with_text("line1\nline2\nline3");
        ta.move_to_document_start();
        ta.select_down();
        let sel = ta.selected_text().unwrap();
        assert!(sel.contains('\n'));
    }

    #[test]
    fn undo_chain() {
        let mut ta = TextArea::new();
        ta.insert_text("a");
        ta.insert_text("b");
        ta.insert_text("c");
        assert_eq!(ta.text(), "abc");
        ta.undo();
        ta.undo();
        ta.undo();
        assert_eq!(ta.text(), "");
    }

    #[test]
    fn redo_discarded_on_new_edit() {
        let mut ta = TextArea::new();
        ta.insert_text("abc");
        ta.undo();
        ta.insert_text("xyz");
        ta.redo(); // should be no-op
        assert_eq!(ta.text(), "xyz");
    }

    #[test]
    fn clear_selection() {
        let mut ta = TextArea::new().with_text("hello");
        ta.select_all();
        assert!(ta.selection().is_some());
        ta.clear_selection();
        assert!(ta.selection().is_none());
    }

    #[test]
    fn delete_word_backward() {
        let mut ta = TextArea::new().with_text("hello world");
        ta.move_to_document_end();
        ta.delete_word_backward();
        assert_eq!(ta.text(), "hello ");
    }

    #[test]
    fn delete_to_end_of_line() {
        let mut ta = TextArea::new().with_text("hello world");
        ta.move_to_document_start();
        ta.move_right(); // after 'h'
        ta.delete_to_end_of_line();
        assert_eq!(ta.text(), "h");
    }

    #[test]
    fn placeholder_builder() {
        let ta = TextArea::new().with_placeholder("Enter text...");
        assert!(ta.is_empty());
        assert_eq!(ta.placeholder, "Enter text...");
    }

    #[test]
    fn soft_wrap_builder() {
        let ta = TextArea::new().with_soft_wrap(true);
        assert!(ta.soft_wrap);
    }

    #[test]
    fn soft_wrap_renders_wrapped_lines() {
        use crate::Widget;
        use ftui_render::grapheme_pool::GraphemePool;

        let ta = TextArea::new().with_soft_wrap(true).with_text("abcdef");
        let area = Rect::new(0, 0, 3, 2);
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(3, 2, &mut pool);
        Widget::render(&ta, area, &mut frame);

        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('a'));
        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('c'));
        assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('d'));
        assert_eq!(frame.buffer.get(2, 1).unwrap().content.as_char(), Some('f'));
    }

    #[test]
    fn max_height_builder() {
        let ta = TextArea::new().with_max_height(10);
        assert_eq!(ta.max_height, 10);
    }

    #[test]
    fn editor_access() {
        let mut ta = TextArea::new().with_text("test");
        assert_eq!(ta.editor().text(), "test");
        ta.editor_mut().insert_char('!');
        assert!(ta.text().contains('!'));
    }

    #[test]
    fn move_to_line_start_and_end() {
        let mut ta = TextArea::new().with_text("hello world");
        ta.move_to_document_start();
        ta.move_to_line_end();
        assert_eq!(ta.cursor().grapheme, 11);
        ta.move_to_line_start();
        assert_eq!(ta.cursor().grapheme, 0);
    }

    #[test]
    fn render_empty_with_placeholder() {
        use ftui_render::grapheme_pool::GraphemePool;
        let ta = TextArea::new()
            .with_placeholder("Type here")
            .with_focus(true);
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(20, 5, &mut pool);
        let area = Rect::new(0, 0, 20, 5);
        Widget::render(&ta, area, &mut frame);
        // Placeholder should be rendered
        let cell = frame.buffer.get(0, 0).unwrap();
        assert_eq!(cell.content.as_char(), Some('T'));
        // Cursor should be set
        assert!(frame.cursor_position.is_some());
    }

    #[test]
    fn render_with_content() {
        use ftui_render::grapheme_pool::GraphemePool;
        let ta = TextArea::new().with_text("abc\ndef").with_focus(true);
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(20, 5, &mut pool);
        let area = Rect::new(0, 0, 20, 5);
        Widget::render(&ta, area, &mut frame);
        let cell = frame.buffer.get(0, 0).unwrap();
        assert_eq!(cell.content.as_char(), Some('a'));
    }

    #[test]
    fn render_shorter_text_clears_stale_suffix_and_extra_lines() {
        use ftui_render::grapheme_pool::GraphemePool;

        let area = Rect::new(0, 0, 8, 3);
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(8, 3, &mut pool);

        Widget::render(
            &TextArea::new().with_text("abcdef\nghijkl"),
            area,
            &mut frame,
        );
        Widget::render(&TextArea::new().with_text("hi"), area, &mut frame);

        assert_eq!(raw_row_text(&frame, 0, 8), "hi      ");
        assert_eq!(raw_row_text(&frame, 1, 8), "        ");
        assert_eq!(raw_row_text(&frame, 2, 8), "        ");
    }

    #[test]
    fn render_line_numbers_without_styling() {
        use ftui_render::budget::DegradationLevel;
        use ftui_render::grapheme_pool::GraphemePool;

        let ta = TextArea::new().with_text("a\nb").with_line_numbers(true);
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(8, 2, &mut pool);
        frame.set_degradation(DegradationLevel::NoStyling);

        Widget::render(&ta, Rect::new(0, 0, 8, 2), &mut frame);

        let cell = frame.buffer.get(0, 0).unwrap();
        assert_eq!(cell.content.as_char(), Some('1'));
    }

    #[test]
    fn stateful_render_updates_viewport_state() {
        use ftui_render::grapheme_pool::GraphemePool;

        let ta = TextArea::new();
        let mut state = TextAreaState::default();
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 3, &mut pool);
        let area = Rect::new(0, 0, 10, 3);

        StatefulWidget::render(&ta, area, &mut frame, &mut state);

        assert_eq!(state.last_viewport_height, 3);
        assert_eq!(state.last_viewport_width, 10);
    }

    #[test]
    fn render_zero_area_no_panic() {
        let ta = TextArea::new().with_text("test");
        use ftui_render::grapheme_pool::GraphemePool;
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 10, &mut pool);
        Widget::render(&ta, Rect::new(0, 0, 0, 0), &mut frame);
    }

    #[test]
    fn is_essential() {
        let ta = TextArea::new();
        assert!(Widget::is_essential(&ta));
    }

    #[test]
    fn default_impl() {
        let ta = TextArea::default();
        assert!(ta.is_empty());
    }

    #[test]
    fn insert_newline_splits_line() {
        let mut ta = TextArea::new().with_text("abcdef");
        ta.move_to_document_start();
        ta.move_right();
        ta.move_right();
        ta.move_right();
        ta.insert_newline();
        assert_eq!(ta.line_count(), 2);
        assert_eq!(ta.cursor().line, 1);
    }

    #[test]
    fn unicode_grapheme_cluster() {
        let mut ta = TextArea::new();
        ta.insert_text("café");
        // 'é' is a single grapheme even if composed
        assert_eq!(ta.text(), "café");
    }

    mod proptests {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #[test]
            fn insert_delete_inverse(text in "[a-zA-Z0-9 ]{1,50}") {
                let mut ta = TextArea::new();
                ta.insert_text(&text);
                // Delete all characters backwards
                for _ in 0..text.len() {
                    ta.delete_backward();
                }
                prop_assert!(ta.is_empty() || ta.text().is_empty());
            }

            #[test]
            fn undo_redo_inverse(text in "[a-zA-Z0-9]{1,30}") {
                let mut ta = TextArea::new();
                ta.insert_text(&text);
                let after_insert = ta.text();
                ta.undo();
                ta.redo();
                prop_assert_eq!(ta.text(), after_insert);
            }

            #[test]
            fn cursor_always_valid(ops in proptest::collection::vec(0u8..10, 1..20)) {
                let mut ta = TextArea::new().with_text("abc\ndef\nghi\njkl");
                for op in ops {
                    match op {
                        0 => ta.move_left(),
                        1 => ta.move_right(),
                        2 => ta.move_up(),
                        3 => ta.move_down(),
                        4 => ta.move_to_line_start(),
                        5 => ta.move_to_line_end(),
                        6 => ta.move_to_document_start(),
                        7 => ta.move_to_document_end(),
                        8 => ta.move_word_left(),
                        _ => ta.move_word_right(),
                    }
                    let cursor = ta.cursor();
                    prop_assert!(cursor.line < ta.line_count(),
                        "cursor line {} >= line_count {}", cursor.line, ta.line_count());
                }
            }

            #[test]
            fn selection_ordered(n in 1usize..20) {
                let mut ta = TextArea::new().with_text("hello world foo bar");
                ta.move_to_document_start();
                for _ in 0..n {
                    ta.select_right();
                }
                if let Some(sel) = ta.selection() {
                    // When selecting right from start, anchor should be at/before head
                    prop_assert!(sel.anchor.line <= sel.head.line
                        || (sel.anchor.line == sel.head.line
                            && sel.anchor.grapheme <= sel.head.grapheme));
                }
            }
        }
    }
}