ftui-widgets 0.10.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
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
//! 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 std::ops::Range;
use std::sync::Arc;
use std::time::Duration;
use web_time::Instant;

use ftui_core::event::{
    Event, KeyCode, KeyEvent, KeyEventKind, Modifiers, MouseButton, MouseEvent, MouseEventKind,
};
use ftui_core::geometry::Rect;
use ftui_core::gesture::GestureConfig;
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.
/// A per-line syntax style provider for [`TextArea::with_highlighter`].
///
/// Called once per visible logical line per render with `(line_index,
/// line_text)`, where `line_text` has no trailing newline. It returns byte
/// ranges into `line_text` paired with a [`Style`] to merge over the base
/// style (before the selection style, so selection still wins). Ranges may
/// overlap — a later range wins for a byte it covers. Ranges that fall outside
/// the line or that do not sit on grapheme boundaries are ignored; an empty
/// vector means "no highlight". The hook lives entirely in `ftui-widgets` and
/// knows nothing about any tokenizer.
pub type LineHighlighter = Arc<dyn Fn(usize, &str) -> Vec<(Range<usize>, Style)> + Send + Sync>;

#[derive(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>,
    /// Optional per-line syntax style provider (see [`LineHighlighter`]).
    highlighter: Option<LineHighlighter>,
    /// Origin for event timestamps; explicit replay timestamps bypass this clock.
    undo_clock: Instant,
    /// Area of the last render, for mapping mouse positions to text.
    last_area: std::cell::Cell<Rect>,
    /// The previous left press, for double and triple clicks.
    last_click: Option<LastClick>,
    /// A left press inside the area started a drag selection.
    mouse_selecting: bool,
}

/// A left press, remembered to count multi-clicks.
#[derive(Debug, Clone, Copy)]
struct LastClick {
    at_ms: u64,
    x: u16,
    y: u16,
    /// 1, 2 or 3: single, double or triple.
    count: u8,
}

impl std::fmt::Debug for TextArea {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TextArea")
            .field("editor", &self.editor)
            .field("placeholder", &self.placeholder)
            .field("focused", &self.focused)
            .field("show_line_numbers", &self.show_line_numbers)
            .field("style", &self.style)
            .field("cursor_line_style", &self.cursor_line_style)
            .field("selection_style", &self.selection_style)
            .field("placeholder_style", &self.placeholder_style)
            .field("line_number_style", &self.line_number_style)
            .field("soft_wrap", &self.soft_wrap)
            .field("max_height", &self.max_height)
            .field("scroll_anchor", &self.scroll_anchor)
            .field("scroll_left", &self.scroll_left)
            .field("last_viewport_height", &self.last_viewport_height)
            .field("last_viewport_width", &self.last_viewport_width)
            .field("highlighter", &self.highlighter.as_ref().map(|_| "<fn>"))
            .field("last_area", &self.last_area)
            .field("last_click", &self.last_click)
            .field("mouse_selecting", &self.mouse_selecting)
            .finish()
    }
}

/// The style of the last range in `spans` that covers `byte`, or `None`.
///
/// Ranges are byte ranges into a single line; a later range wins on overlap.
/// Never panics: offsets outside every range simply return `None`.
fn style_at(spans: &[(Range<usize>, Style)], byte: usize) -> Option<Style> {
    spans
        .iter()
        .rev()
        .find(|(range, _)| range.contains(&byte))
        .map(|(_, style)| *style)
}

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),
            highlighter: None,
            undo_clock: Instant::now(),
            last_area: std::cell::Cell::new(Rect::default()),
            last_click: None,
            mouse_selecting: false,
        }
    }

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

    /// Handle a terminal event.
    ///
    /// Returns `true` if the state changed.
    pub fn handle_event(&mut self, event: &Event) -> bool {
        let now_ms = u64::try_from(self.undo_clock.elapsed().as_millis()).unwrap_or(u64::MAX);
        self.handle_event_at(event, now_ms)
    }

    /// Handle an event with a caller-supplied monotonic millisecond timestamp.
    /// Use this instead of [`Self::handle_event`] for deterministic replay.
    /// Switching to an earlier clock value starts a new undo group.
    pub fn handle_event_at(&mut self, event: &Event, now_ms: u64) -> bool {
        self.editor.tick(now_ms);
        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
            }
            Event::Focus(false) => {
                self.editor.break_undo_group();
                false
            }
            Event::Mouse(mouse) => self.handle_mouse(mouse, now_ms),
            _ => false,
        }
    }

    /// Left press places the cursor, a second press selects the word under
    /// it (Unicode word boundaries) and a third the line. Presses count as
    /// one multi-click within [`GestureConfig`]'s window and tolerance (300
    /// ms, 1 cell), so timing matches the runtime's gesture recognizer.
    /// Dragging after a single press extends the selection. Presses outside
    /// the area last rendered are ignored, and so is a drag that started
    /// outside it, so a host can forward every mouse event.
    fn handle_mouse(&mut self, mouse: &MouseEvent, now_ms: u64) -> bool {
        match mouse.kind {
            MouseEventKind::Down(MouseButton::Left) => {
                let Some(pos) = self.position_at(mouse.x, mouse.y) else {
                    self.mouse_selecting = false;
                    return false;
                };
                let config = GestureConfig::default();
                let window =
                    u64::try_from(config.multi_click_timeout.as_millis()).unwrap_or(u64::MAX);
                let count = match self.last_click {
                    Some(last)
                        if now_ms >= last.at_ms
                            && now_ms - last.at_ms <= window
                            && last.x.abs_diff(mouse.x) <= config.click_tolerance
                            && last.y.abs_diff(mouse.y) <= config.click_tolerance =>
                    {
                        last.count % 3 + 1
                    }
                    _ => 1,
                };
                self.last_click = Some(LastClick {
                    at_ms: now_ms,
                    x: mouse.x,
                    y: mouse.y,
                    count,
                });
                self.mouse_selecting = count == 1;
                match count {
                    1 => self.editor.set_cursor(pos),
                    2 => self.select_word_at(pos),
                    _ => self.select_line_at(pos),
                }
                true
            }
            MouseEventKind::Drag(MouseButton::Left) if self.mouse_selecting => {
                let area = self.last_area.get();
                if area.is_empty() {
                    return false;
                }
                let x = mouse.x.clamp(area.x, area.right() - 1);
                let y = mouse.y.clamp(area.y, area.bottom() - 1);
                let pos = self.position_in_area(area, x, y);
                self.editor.extend_selection_to(pos);
                true
            }
            MouseEventKind::Up(MouseButton::Left) => {
                self.mouse_selecting = false;
                false
            }
            _ => false,
        }
    }

    /// The text position under a cell of the last rendered area, or `None`
    /// outside it (or before the first render).
    fn position_at(&self, x: u16, y: u16) -> Option<CursorPosition> {
        let area = self.last_area.get();
        (!area.is_empty() && area.contains(x, y)).then(|| self.position_in_area(area, x, y))
    }

    /// Invert the render's layout: rows from the scroll anchor (wrapped
    /// slices when soft-wrapping), columns past the gutter plus the
    /// horizontal scroll. Below the text maps to the last line; the gutter
    /// maps to column 0.
    fn position_in_area(&self, area: Rect, x: u16, y: u16) -> CursorPosition {
        let col = usize::from(x.saturating_sub(area.x.saturating_add(self.gutter_width())));
        let row = usize::from(y.saturating_sub(area.y));
        let rope = self.editor.rope();
        let nav = CursorNavigator::new(rope);
        let (top_line, top_vrow) = self.scroll_anchor.get();
        let top_line = if top_line == usize::MAX { 0 } else { top_line };
        let line_count = self.editor.line_count();

        if !self.soft_wrap {
            return nav.from_visual_col(top_line + row, self.scroll_left.get() + col);
        }

        let width = self.last_viewport_width.get();
        let mut remaining = row;
        for line_idx in top_line..line_count {
            let line_text = rope
                .line(line_idx)
                .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);
            let skip = if line_idx == top_line { top_vrow } else { 0 };
            let visible = slices.len().saturating_sub(skip);
            if remaining < visible {
                let index = skip + remaining;
                let slice = &slices[index];
                // Past the end of a slice that wraps, stay on that row
                // rather than landing at the start of the next one.
                let max = if index + 1 < slices.len() {
                    slice.width.saturating_sub(1)
                } else {
                    slice.width
                };
                return nav.from_visual_col(line_idx, slice.start_col + col.min(max));
            }
            remaining -= visible;
        }
        nav.from_visual_col(line_count.saturating_sub(1), usize::MAX)
    }

    /// Select the Unicode word segment (UAX #29) under `pos`: a word, a run
    /// of spaces, or one punctuation mark.
    fn select_word_at(&mut self, pos: CursorPosition) {
        let rope = self.editor.rope();
        let nav = CursorNavigator::new(rope);
        let line_text = rope
            .line(pos.line)
            .unwrap_or(std::borrow::Cow::Borrowed(""));
        let line_text = line_text.trim_end_matches(['\n', '\r']);
        let line_start = nav.to_byte_index(nav.from_line_grapheme(pos.line, 0));
        let offset = nav.to_byte_index(pos) - line_start;
        let segment = line_text
            .split_word_bound_indices()
            .find(|(start, word)| offset < start + word.len())
            .or_else(|| line_text.split_word_bound_indices().next_back());
        let Some((start, word)) = segment else {
            self.editor.set_cursor(pos);
            return;
        };
        let from = nav.from_byte_index(line_start + start);
        let to = nav.from_byte_index(line_start + start + word.len());
        self.editor.set_cursor(from);
        self.editor.extend_selection_to(to);
    }

    /// Select the whole logical line under `pos`, without its newline.
    fn select_line_at(&mut self, pos: CursorPosition) {
        let nav = CursorNavigator::new(self.editor.rope());
        let from = nav.from_line_grapheme(pos.line, 0);
        let to = nav.from_line_grapheme(pos.line, usize::MAX);
        self.editor.set_cursor(from);
        self.editor.extend_selection_to(to);
    }

    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);
        // Command/Windows-key chords belong to the host, not the buffer. Only
        // CTRL used to be excluded, so on macOS every Cmd+<letter> shortcut
        // typed its letter: Cmd+V inserted a literal "v" next to the paste.
        let cmd = key.modifiers.contains(Modifiers::SUPER);

        match key.code {
            KeyCode::Char(c) if !ctrl && !cmd => {
                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 ctrl && shift {
                    self.select_paragraph_up();
                } else if ctrl {
                    self.move_paragraph_up();
                } else if shift {
                    self.select_up();
                } else {
                    self.move_up();
                }
                true
            }
            KeyCode::Down => {
                if ctrl && shift {
                    self.select_paragraph_down();
                } else if ctrl {
                    self.move_paragraph_down();
                } else 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.set_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
    }

    /// Install a per-line syntax style provider (builder). See
    /// [`LineHighlighter`].
    #[must_use]
    pub fn with_highlighter(mut self, highlighter: LineHighlighter) -> Self {
        self.highlighter = Some(highlighter);
        self
    }

    /// Set or clear the per-line syntax style provider.
    pub fn set_highlighter(&mut self, highlighter: Option<LineHighlighter>) {
        self.highlighter = highlighter;
    }

    /// Whether a syntax highlighter is installed.
    #[must_use]
    pub fn has_highlighter(&self) -> bool {
        self.highlighter.is_some()
    }

    /// The highlight spans for one line, or empty when there is no highlighter
    /// or styling is disabled. Ranges that don't sit on grapheme boundaries of
    /// `line_text` are dropped so partial-grapheme styling can't occur.
    fn line_spans(
        &self,
        line_idx: usize,
        line_text: &str,
        styling: bool,
    ) -> Vec<(Range<usize>, Style)> {
        if !styling {
            return Vec::new();
        }
        let Some(highlighter) = self.highlighter.as_ref() else {
            return Vec::new();
        };
        highlighter(line_idx, line_text)
            .into_iter()
            .filter(|(range, _)| {
                range.start < range.end
                    && range.end <= line_text.len()
                    && line_text.is_char_boundary(range.start)
                    && line_text.is_char_boundary(range.end)
            })
            .collect()
    }

    /// 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) {
        if !focused {
            self.editor.break_undo_group();
        }
        self.focused = focused;
    }

    /// Set the idle interval for typing/deletion undo groups (default 500 ms).
    /// Zero disables coalescing.
    pub fn set_undo_coalesce_idle(&mut self, idle: Duration) {
        self.editor.set_coalesce_idle(idle);
    }

    /// Number of available undo steps.
    #[must_use]
    pub fn undo_group_count(&self) -> usize {
        self.editor.undo_group_count()
    }

    /// Number of available redo steps.
    #[must_use]
    pub fn redo_group_count(&self) -> usize {
        self.editor.redo_group_count()
    }

    /// Number of primitive edits retained in the undo history.
    #[must_use]
    pub fn undo_op_count(&self) -> usize {
        self.editor.undo_op_count()
    }

    /// 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 the preceding blank-line paragraph boundary (Ctrl+Up).
    /// See [`CursorNavigator::move_paragraph_up`] for whitespace rules and examples.
    pub fn move_paragraph_up(&mut self) {
        self.editor.move_paragraph_up();
        self.ensure_cursor_visible();
    }

    /// Move to the following blank-line paragraph boundary (Ctrl+Down).
    /// See [`CursorNavigator::move_paragraph_down`] for whitespace rules and examples.
    pub fn move_paragraph_down(&mut self) {
        self.editor.move_paragraph_down();
        self.ensure_cursor_visible();
    }

    /// Extend selection to the preceding paragraph boundary (Ctrl+Shift+Up).
    /// See [`CursorNavigator::move_paragraph_up`] for whitespace rules and examples.
    pub fn select_paragraph_up(&mut self) {
        self.editor.select_paragraph_up();
        self.ensure_cursor_visible();
    }

    /// Extend selection to the following paragraph boundary (Ctrl+Shift+Down).
    /// See [`CursorNavigator::move_paragraph_down`] for whitespace rules and examples.
    pub fn select_paragraph_down(&mut self) {
        self.editor.select_paragraph_down();
        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;
        }

        if frame.a11y_enabled() {
            frame.push_a11y_nodes(ftui_a11y::Accessible::accessibility_nodes(self, area));
        }

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

        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));
                // Syntax highlight spans for the whole logical line, computed
                // once and reused across every wrapped slice.
                let hl_spans = self.line_spans(line_idx, line_text, deg.apply_styling());
                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;

                        // Syntax highlight first, then selection over it.
                        let mut g_style = base_style;
                        if let Some(hl) = style_at(
                            &hl_spans,
                            grapheme_byte_offset.saturating_sub(line_start_byte),
                        ) {
                            g_style = g_style.patch(&hl);
                        }
                        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.patch(&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));
            let hl_spans = self.line_spans(line_idx, line_text, deg.apply_styling());

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

                // Syntax highlight first, then selection over it.
                let mut g_style = base_style;
                if let Some(hl) = style_at(
                    &hl_spans,
                    grapheme_byte_offset.saturating_sub(line_start_byte),
                ) {
                    g_style = g_style.patch(&hl);
                }
                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.patch(&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 ftui_a11y::Accessible for TextArea {
    fn accessibility_nodes(&self, area: Rect) -> Vec<ftui_a11y::node::A11yNodeInfo> {
        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};

        if area.is_empty() {
            return Vec::new();
        }
        let text = self.text();
        let name = if text.is_empty() {
            self.placeholder.clone()
        } else {
            text
        };
        vec![
            A11yNodeInfo::new(crate::a11y_node_id(area), A11yRole::TextInput, area)
                .with_name(name)
                .with_description("multi-line text input")
                .with_state(A11yState {
                    focused: self.focused,
                    ..A11yState::default()
                }),
        ]
    }
}

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::*;

    mod mouse {
        use super::*;
        use ftui_render::grapheme_pool::GraphemePool;

        fn rendered(ta: &TextArea, area: Rect) {
            let mut pool = GraphemePool::new();
            let mut frame = Frame::new(area.right(), area.bottom(), &mut pool);
            Widget::render(ta, area, &mut frame);
        }

        fn press(ta: &mut TextArea, x: u16, y: u16, at_ms: u64) -> bool {
            let down = MouseEvent::new(MouseEventKind::Down(MouseButton::Left), x, y);
            let changed = ta.handle_event_at(&Event::Mouse(down), at_ms);
            let up = MouseEvent::new(MouseEventKind::Up(MouseButton::Left), x, y);
            ta.handle_event_at(&Event::Mouse(up), at_ms);
            changed
        }

        const AREA: Rect = Rect::new(2, 1, 30, 5);

        #[test]
        fn click_places_the_cursor_under_the_pointer() {
            let mut ta = TextArea::new().with_text("hello world\nsecond line");
            rendered(&ta, AREA);
            assert!(press(&mut ta, AREA.x + 7, AREA.y + 1, 0));
            assert_eq!((ta.cursor().line, ta.cursor().grapheme), (1, 7));
            assert_eq!(ta.selection(), None);
            // Past the end of a line lands at its end.
            press(&mut ta, AREA.x + 25, AREA.y, 1000);
            assert_eq!((ta.cursor().line, ta.cursor().grapheme), (0, 11));
        }

        #[test]
        fn textarea_double_click_selects_word() {
            let mut ta = TextArea::new().with_text("hello brave world");
            rendered(&ta, AREA);
            press(&mut ta, AREA.x + 8, AREA.y, 0);
            press(&mut ta, AREA.x + 8, AREA.y, 200);
            assert_eq!(ta.selected_text().as_deref(), Some("brave"));
        }

        #[test]
        fn textarea_triple_click_selects_line() {
            let mut ta = TextArea::new().with_text("first line\nhello brave world\nlast");
            rendered(&ta, AREA);
            for at in [0, 150, 300] {
                press(&mut ta, AREA.x + 3, AREA.y + 1, at);
            }
            assert_eq!(ta.selected_text().as_deref(), Some("hello brave world"));
        }

        #[test]
        fn slow_or_distant_second_press_is_a_new_click() {
            let mut ta = TextArea::new().with_text("hello brave world");
            rendered(&ta, AREA);
            press(&mut ta, AREA.x + 8, AREA.y, 0);
            press(&mut ta, AREA.x + 8, AREA.y, 301);
            assert_eq!(ta.selection(), None, "outside the 300 ms window");
            press(&mut ta, AREA.x + 14, AREA.y, 400);
            assert_eq!(ta.selection(), None, "more than one cell away");
            assert_eq!(ta.cursor().grapheme, 14);
        }

        #[test]
        fn drag_extends_the_selection_from_the_press() {
            let mut ta = TextArea::new().with_text("hello brave world\nnext");
            rendered(&ta, AREA);
            let down = MouseEvent::new(MouseEventKind::Down(MouseButton::Left), AREA.x + 6, AREA.y);
            ta.handle_event_at(&Event::Mouse(down), 0);
            let drag = MouseEvent::new(
                MouseEventKind::Drag(MouseButton::Left),
                AREA.x + 2,
                AREA.y + 1,
            );
            assert!(ta.handle_event_at(&Event::Mouse(drag), 10));
            assert_eq!(ta.selected_text().as_deref(), Some("brave world\nne"));
        }

        #[test]
        fn events_outside_the_area_are_ignored() {
            let mut ta = TextArea::new().with_text("hello");
            // Before any render there is no area to hit.
            assert!(!press(&mut ta, 0, 0, 0));
            rendered(&ta, AREA);
            let before = ta.cursor();
            assert!(!press(&mut ta, AREA.x - 1, AREA.y, 1000));
            assert!(!press(&mut ta, AREA.x, AREA.bottom(), 2000));
            let drag = MouseEvent::new(MouseEventKind::Drag(MouseButton::Left), AREA.x + 2, AREA.y);
            assert!(
                !ta.handle_event_at(&Event::Mouse(drag), 3000),
                "no drag without a press inside"
            );
            assert_eq!(ta.cursor(), before);
        }

        #[test]
        fn click_accounts_for_gutter_and_vertical_scroll() {
            let text: String = (0..20).map(|i| format!("line{i}\n")).collect();
            let mut ta = TextArea::new().with_text(&text).with_line_numbers(true);
            ta.set_cursor_position(CursorPosition::new(19, 0, 0));
            rendered(&ta, AREA);
            let (top, _) = ta.scroll_anchor.get();
            assert!(top > 0, "the cursor at line 19 scrolled the view");
            let gutter = ta.gutter_width();
            press(&mut ta, AREA.x + gutter + 4, AREA.y + 2, 0);
            assert_eq!((ta.cursor().line, ta.cursor().grapheme), (top + 2, 4));
            // A click in the gutter lands at column 0.
            press(&mut ta, AREA.x, AREA.y, 1000);
            assert_eq!((ta.cursor().line, ta.cursor().grapheme), (top, 0));
        }

        #[test]
        fn click_on_a_wrapped_row_maps_into_its_slice() {
            // Ten columns wide: "aaaa bbbb " fits the first row, "cccc" wraps.
            let mut ta = TextArea::new()
                .with_text("aaaa bbbb cccc")
                .with_soft_wrap(true);
            let area = Rect::new(0, 0, 10, 3);
            rendered(&ta, area);
            press(&mut ta, 2, 1, 0);
            assert_eq!((ta.cursor().line, ta.cursor().grapheme), (0, 12));
            // Past the end of a row that wraps stays on that row.
            press(&mut ta, 9, 0, 1000);
            assert_eq!(ta.cursor().grapheme, 9);
        }

        fn key(ta: &mut TextArea, code: KeyCode, modifiers: Modifiers) {
            ta.handle_event(&Event::Key(KeyEvent {
                code,
                modifiers,
                kind: KeyEventKind::Press,
            }));
        }

        fn drawn_cursor(ta: &TextArea, area: Rect) -> (Option<(u16, u16)>, Vec<String>) {
            let mut pool = GraphemePool::new();
            let mut frame = Frame::new(area.right(), area.bottom(), &mut pool);
            Widget::render(ta, area, &mut frame);
            let row: Vec<String> = (area.x..area.right())
                .map(|x| {
                    let cell = frame.buffer.get(x, area.y).unwrap();
                    cell.content
                        .as_char()
                        .map(String::from)
                        .or_else(|| {
                            cell.content
                                .grapheme_id()
                                .and_then(|id| frame.pool.get(id).map(str::to_string))
                        })
                        .unwrap_or_default()
                })
                .collect();
            (frame.cursor_position, row)
        }

        /// #102 (3): TextArea draws text in logical order, so keys, the drawn
        /// caret, clicks, delete and undo must all use the same logical
        /// layout, with whole grapheme clusters (default features include
        /// `bidi`).
        #[test]
        fn rtl_and_clusters_render_navigate_click_delete_consistently() {
            let text = "a\u{0301} \u{05D0}\u{05D1}";
            for wrap in [false, true] {
                let mut ta = TextArea::new()
                    .with_text(text)
                    .with_soft_wrap(wrap)
                    .with_focus(true);
                let (_, row) = drawn_cursor(&ta, AREA);
                assert_eq!(
                    &row[..4],
                    ["a\u{0301}", " ", "\u{05D0}", "\u{05D1}"],
                    "wrap={wrap}"
                );

                key(&mut ta, KeyCode::Home, Modifiers::NONE);
                assert_eq!(ta.cursor().grapheme, 0);
                key(&mut ta, KeyCode::Right, Modifiers::NONE);
                key(&mut ta, KeyCode::Right, Modifiers::NONE);
                assert_eq!(ta.cursor().grapheme, 2, "wrap={wrap}");
                let (cursor, _) = drawn_cursor(&ta, AREA);
                assert_eq!(
                    cursor,
                    Some((AREA.x + 2, AREA.y)),
                    "wrap={wrap}: caret before the alef"
                );

                key(&mut ta, KeyCode::End, Modifiers::NONE);
                assert_eq!(ta.cursor().grapheme, 4);
                let (cursor, _) = drawn_cursor(&ta, AREA);
                assert_eq!(cursor, Some((AREA.x + 4, AREA.y)), "wrap={wrap}");

                // Clicking between the alef and bet lands between them.
                press(&mut ta, AREA.x + 3, AREA.y, 0);
                assert_eq!(ta.cursor().grapheme, 3, "wrap={wrap}");
                key(&mut ta, KeyCode::Backspace, Modifiers::NONE);
                assert_eq!(ta.text(), "a\u{0301} \u{05D1}", "wrap={wrap}");
                ta.undo();
                assert_eq!(ta.text(), text, "wrap={wrap}");

                // Backspace after the combining cluster removes it whole.
                press(&mut ta, AREA.x + 1, AREA.y, 5000);
                assert_eq!(ta.cursor().grapheme, 1, "wrap={wrap}");
                key(&mut ta, KeyCode::Backspace, Modifiers::NONE);
                assert_eq!(ta.text(), " \u{05D0}\u{05D1}", "wrap={wrap}");
            }
        }
    }

    #[test]
    fn undo_groups_keyboard_clock_paste_and_focus() {
        let key = |c| {
            Event::Key(KeyEvent {
                code: KeyCode::Char(c),
                modifiers: Modifiers::NONE,
                kind: KeyEventKind::Press,
            })
        };
        let mut ta = TextArea::new();
        for (tick, c) in "hello world".chars().enumerate() {
            ta.handle_event_at(&key(c), tick as u64);
        }
        assert_eq!(ta.undo_group_count(), 2);
        assert_eq!(ta.undo_op_count(), 11);
        ta.handle_event_at(
            &Event::Key(KeyEvent {
                code: KeyCode::Char('z'),
                modifiers: Modifiers::CTRL,
                kind: KeyEventKind::Press,
            }),
            11,
        );
        assert_eq!(ta.text(), "hello ");
        ta.redo();
        ta.handle_event_at(&key('x'), 600);
        assert_eq!(ta.undo_group_count(), 3);
        ta.handle_event_at(
            &Event::Paste(ftui_core::event::PasteEvent::bracketed("p")),
            601,
        );
        ta.handle_event_at(&key('y'), 602);
        assert_eq!(ta.undo_group_count(), 5);
        ta.handle_event_at(&Event::Focus(false), 603);
        ta.handle_event_at(&key('z'), 604);
        assert_eq!(ta.undo_group_count(), 6);
        ta.set_focused(false);
        ta.handle_event_at(&key('q'), 605);
        assert_eq!(ta.undo_group_count(), 7);
        // Exercise the normal event entrypoint without a wall-clock deadline.
        let mut live = TextArea::new();
        live.set_undo_coalesce_idle(Duration::MAX);
        live.handle_event(&key('a'));
        live.handle_event(&key('b'));
        assert_eq!(live.undo_group_count(), 1);
        live.undo();
        assert_eq!(live.text(), "");
    }

    #[test]
    fn selection_edit_keyboard_undo_redo_restores_cursor() {
        for edit in [KeyCode::Char('X'), KeyCode::Backspace, KeyCode::Delete] {
            let mut ta = TextArea::new().with_text("界e\u{301}\nsecond");
            let key = |code, modifiers| {
                Event::Key(KeyEvent {
                    code,
                    modifiers,
                    kind: KeyEventKind::Press,
                })
            };
            ta.handle_event(&key(KeyCode::Char('a'), Modifiers::CTRL));
            let original_cursor = ta.cursor();
            assert_eq!(original_cursor, CursorPosition::new(1, 6, 6));
            ta.handle_event(&key(edit, Modifiers::empty()));
            let expected = if edit == KeyCode::Char('X') { "X" } else { "" };
            assert_eq!(ta.text(), expected);
            let edited_cursor = ta.cursor();
            ta.handle_event(&key(KeyCode::Char('z'), Modifiers::CTRL));
            assert_eq!(ta.text(), "界e\u{301}\nsecond");
            assert_eq!(ta.cursor(), original_cursor);
            ta.handle_event(&key(KeyCode::Char('y'), Modifiers::CTRL));
            assert_eq!(ta.text(), expected);
            assert_eq!(ta.cursor(), edited_cursor);
        }
    }

    #[test]
    fn paragraph_keys_move_select_and_preserve_line_navigation() {
        for soft_wrap in [false, true] {
            let mut ta = TextArea::new()
                .with_text("first\ncontinued\n\nsecond\n\nlast")
                .with_soft_wrap(soft_wrap);
            ta.move_to_document_start();
            let key = |code, modifiers, kind| {
                Event::Key(KeyEvent {
                    code,
                    modifiers,
                    kind,
                })
            };
            assert!(ta.handle_event(&key(KeyCode::Down, Modifiers::CTRL, KeyEventKind::Press)));
            assert_eq!(ta.cursor(), CursorPosition::new(2, 0, 0));
            assert!(ta.handle_event(&key(
                KeyCode::Down,
                Modifiers::CTRL | Modifiers::SHIFT,
                KeyEventKind::Repeat
            )));
            assert_eq!(ta.cursor(), CursorPosition::new(4, 0, 0));
            assert_eq!(ta.selected_text().as_deref(), Some("\nsecond\n"));
            let anchor = ta.selection().unwrap().anchor;
            ta.handle_event(&key(
                KeyCode::Up,
                Modifiers::CTRL | Modifiers::SHIFT,
                KeyEventKind::Press,
            ));
            assert_eq!(ta.selection().unwrap().anchor, anchor);
            assert_eq!(ta.cursor(), anchor);
            assert!(!ta.handle_event(&key(KeyCode::Up, Modifiers::CTRL, KeyEventKind::Release)));
            assert_eq!(ta.cursor(), anchor);
            ta.handle_event(&key(KeyCode::Up, Modifiers::CTRL, KeyEventKind::Press));
            assert_eq!(ta.cursor(), CursorPosition::default());
            assert!(ta.selection().is_none());
            ta.handle_event(&key(KeyCode::Down, Modifiers::empty(), KeyEventKind::Press));
            assert_eq!(ta.cursor().line, 1);
            ta.handle_event(&key(KeyCode::Up, Modifiers::SHIFT, KeyEventKind::Press));
            assert_eq!(ta.cursor().line, 0);
            assert_eq!(ta.selected_text().as_deref(), Some("first\n"));
        }
    }

    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 accessibility_preserves_multiline_content_and_focus() {
        use ftui_a11y::Accessible;
        use ftui_a11y::node::A11yRole;

        let area = Rect::new(3, 4, 20, 2);
        let mut textarea = TextArea::new().with_text("first é\nsecond 日");
        let initial = textarea.accessibility_nodes(area);
        assert_eq!(initial.len(), 1);
        assert_eq!(initial[0].role, A11yRole::TextInput);
        assert_eq!(initial[0].name.as_deref(), Some("first é\nsecond 日"));
        assert!(!initial[0].state.focused);
        textarea.set_focused(true);
        let focused = textarea.accessibility_nodes(area);
        assert!(focused[0].state.focused);
        assert_eq!(focused[0].id, initial[0].id);
        assert_eq!(focused[0].bounds, area);
        assert!(
            textarea
                .accessibility_nodes(Rect::new(0, 0, 0, 2))
                .is_empty()
        );
        let empty = TextArea::new().with_placeholder("Write a message");
        assert_eq!(
            empty.accessibility_nodes(area)[0].name.as_deref(),
            Some("Write a message")
        );
    }

    #[test]
    fn render_collects_textarea_accessibility_only_when_enabled() {
        use ftui_a11y::tree::A11yTreeBuilder;
        use ftui_render::grapheme_pool::GraphemePool;

        let textarea = TextArea::new()
            .with_text("line one\nline two")
            .with_focus(true);
        let area = Rect::new(2, 1, 12, 2);
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(20, 5, &mut pool);
        Widget::render(&textarea, area, &mut frame);
        assert!(frame.a11y_order().is_empty());

        let mut builder = A11yTreeBuilder::new();
        let mut frame = Frame::new(20, 5, &mut pool);
        frame.set_a11y(&mut builder);
        Widget::render(&textarea, area, &mut frame);
        frame.finish_a11y();
        drop(frame);
        let tree = builder.build();
        assert_eq!(tree.nodes().count(), 1);
        assert_eq!(
            tree.focused().and_then(|node| node.name.as_deref()),
            Some("line one\nline two")
        );
    }

    #[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 command_chords_do_not_type_their_letter() {
        // macOS sends Cmd as SUPER. Cmd+V is a paste shortcut handled by the
        // host; the buffer must not also receive a literal "v". Same for the
        // other common Cmd chords a user will hit over a focused editor.
        for (label, ch) in [("paste", 'v'), ("copy", 'c'), ("cut", 'x'), ("all", 'a')] {
            let mut ta = TextArea::new();
            let handled = ta.handle_event(&Event::Key(
                KeyEvent::new(KeyCode::Char(ch)).with_modifiers(Modifiers::SUPER),
            ));
            assert_eq!(ta.text(), "", "Cmd+{ch} ({label}) typed into the buffer");
            assert!(!handled, "Cmd+{ch} ({label}) should be left to the host");
        }
    }

    #[test]
    fn key_release_does_not_type() {
        // Synthetic drivers (the demo's guided tour) send a press followed by a
        // release so key-latching screens unlatch. The release must be inert
        // here, or every driven keystroke would be typed twice.
        let mut ta = TextArea::new();
        let handled = ta.handle_event(&Event::Key(
            KeyEvent::new(KeyCode::Char('x')).with_kind(KeyEventKind::Release),
        ));
        assert!(!handled, "a key release should not be consumed as typing");
        assert_eq!(ta.text(), "");
    }

    #[test]
    fn plain_and_shifted_characters_still_type() {
        let mut ta = TextArea::new();
        assert!(ta.handle_event(&Event::Key(KeyEvent::new(KeyCode::Char('v')))));
        assert!(ta.handle_event(&Event::Key(
            KeyEvent::new(KeyCode::Char('V')).with_modifiers(Modifiers::SHIFT),
        )));
        assert_eq!(ta.text(), "vV");
    }

    #[test]
    fn paste_event_inserts_clipboard_text() {
        let mut ta = TextArea::new().with_text("ab");
        ta.move_to_document_end();
        assert!(ta.handle_event(&Event::Paste(ftui_core::event::PasteEvent::bracketed("cd"))));
        assert_eq!(ta.text(), "abcd");
    }

    #[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));
                }
            }
        }
    }

    mod highlighter_tests {
        use super::*;
        use ftui_render::cell::{PackedRgba, StyleFlags};
        use ftui_render::frame::Frame;
        use ftui_render::grapheme_pool::GraphemePool;
        use proptest::prelude::*;

        fn render(ta: &TextArea, w: u16, h: u16, mut f: impl FnMut(&Frame)) {
            let mut pool = GraphemePool::new();
            let mut frame = Frame::new(w, h, &mut pool);
            Widget::render(ta, Rect::new(0, 0, w, h), &mut frame);
            f(&frame);
        }

        #[test]
        fn highlighter_receives_each_visible_line_once() {
            let seen = Arc::new(std::sync::Mutex::new(Vec::<usize>::new()));
            let recorder = seen.clone();
            let ta = TextArea::new()
                .with_text("one\ntwo\nthree")
                .with_highlighter(Arc::new(move |line, _text| {
                    recorder.lock().unwrap().push(line);
                    Vec::new()
                }));
            assert!(ta.has_highlighter());
            render(&ta, 20, 3, |_| {});
            let mut lines = seen.lock().unwrap().clone();
            lines.sort_unstable();
            assert_eq!(lines, vec![0, 1, 2]);
        }

        #[test]
        fn highlighter_ranges_style_graphemes() {
            let ta = TextArea::new()
                .with_text("abcdef")
                .with_highlighter(Arc::new(|_l, _t| {
                    vec![(0..3, Style::new().fg(PackedRgba::RED))]
                }));
            render(&ta, 10, 1, |frame| {
                for x in 0..3 {
                    assert_eq!(
                        frame.buffer.get(x, 0).unwrap().fg,
                        PackedRgba::RED,
                        "col {x}"
                    );
                }
                assert_ne!(frame.buffer.get(3, 0).unwrap().fg, PackedRgba::RED);
            });
        }

        #[test]
        fn out_of_range_and_non_boundary_ranges_ignored() {
            // "café": c(0) a(1) f(2) é(3..5); len 5. All three ranges are
            // invalid (past end / splits 'é' / inverted) and are dropped.
            let ta = TextArea::new()
                .with_text("café")
                .with_highlighter(Arc::new(|_l, _t| {
                    // Struct literal so clippy does not flag the reversed range.
                    let inverted = Range { start: 5, end: 2 };
                    vec![
                        (0..100, Style::new().fg(PackedRgba::RED)),
                        (3..4, Style::new().fg(PackedRgba::GREEN)),
                        (inverted, Style::new().fg(PackedRgba::BLUE)),
                    ]
                }));
            assert!(ta.line_spans(0, "café", true).is_empty());
            render(&ta, 10, 1, |_| {}); // no panic
        }

        #[test]
        fn multibyte_ranges_align_to_graphemes() {
            // Highlight only the 2-byte 'é' (bytes 3..5).
            let ta = TextArea::new()
                .with_text("café")
                .with_highlighter(Arc::new(|_l, _t| {
                    vec![(3..5, Style::new().fg(PackedRgba::RED))]
                }));
            assert_eq!(ta.line_spans(0, "café", true).len(), 1);
            render(&ta, 10, 1, |frame| {
                assert_eq!(frame.buffer.get(3, 0).unwrap().fg, PackedRgba::RED, "'é'");
                assert_ne!(frame.buffer.get(0, 0).unwrap().fg, PackedRgba::RED, "'c'");
            });
        }

        #[test]
        fn selection_style_merges_over_highlight() {
            let mut ta = TextArea::new()
                .with_text("abcdef")
                .with_focus(true)
                .with_selection_style(Style::new().bg(PackedRgba::GREEN))
                .with_highlighter(Arc::new(|_l, _t| {
                    vec![(0..6, Style::new().bg(PackedRgba::RED).fg(PackedRgba::WHITE))]
                }));
            ta.move_to_document_start();
            ta.select_right();
            ta.select_right();
            ta.select_right();
            render(&ta, 10, 1, |frame| {
                let selected = frame.buffer.get(0, 0).unwrap();
                assert_eq!(
                    selected.bg,
                    PackedRgba::GREEN,
                    "selection bg wins over highlight"
                );
                assert_eq!(selected.fg, PackedRgba::WHITE, "highlight fg preserved");
                let highlighted = frame.buffer.get(3, 0).unwrap();
                assert_eq!(
                    highlighted.bg,
                    PackedRgba::RED,
                    "unselected cell keeps highlight bg"
                );
            });
        }

        #[test]
        fn soft_wrap_applies_highlight_on_continuation_rows() {
            // 10 chars wrapped at width 5 -> row 0 "abcde", row 1 "fghij"; the
            // whole-line highlight must reach the continuation row.
            let ta = TextArea::new()
                .with_text("abcdefghij")
                .with_soft_wrap(true)
                .with_highlighter(Arc::new(|_l, _t| {
                    vec![(0..10, Style::new().fg(PackedRgba::RED))]
                }));
            render(&ta, 5, 2, |frame| {
                assert_eq!(
                    frame.buffer.get(0, 0).unwrap().fg,
                    PackedRgba::RED,
                    "first row"
                );
                assert_eq!(
                    frame.buffer.get(0, 1).unwrap().fg,
                    PackedRgba::RED,
                    "continuation row highlighted"
                );
            });
        }

        #[test]
        fn degraded_frame_ignores_highlight() {
            use ftui_render::budget::DegradationLevel;

            let ta = TextArea::new()
                .with_text("abcdef")
                .with_highlighter(Arc::new(|_l, _t| {
                    vec![(0..3, Style::new().fg(PackedRgba::RED))]
                }));
            let mut pool = GraphemePool::new();
            let mut frame = Frame::new(10, 1, &mut pool);
            frame.buffer.degradation = DegradationLevel::NoStyling;
            Widget::render(&ta, Rect::new(0, 0, 10, 1), &mut frame);
            for x in 0..6 {
                assert_ne!(
                    frame.buffer.get(x, 0).unwrap().fg,
                    PackedRgba::RED,
                    "cell at x={x} must not have highlight fg under NoStyling"
                );
            }
        }

        #[test]
        fn style_at_last_range_wins() {
            let style_a = Style::new().fg(PackedRgba::RED);
            let style_b = Style::new().fg(PackedRgba::BLUE);
            let spans = vec![(0..5, style_a), (2..4, style_b)];
            assert_eq!(style_at(&spans, 0), Some(style_a));
            assert_eq!(style_at(&spans, 1), Some(style_a));
            assert_eq!(style_at(&spans, 2), Some(style_b));
            assert_eq!(style_at(&spans, 3), Some(style_b));
            assert_eq!(style_at(&spans, 4), Some(style_a));
            assert_eq!(style_at(&spans, 5), None);
        }

        #[test]
        fn cjk_and_emoji_multibyte_ranges_align_to_graphemes() {
            // "日本語 ok 🎉"
            // 日本 is bytes 0..6 (columns 0 and 2; each width 2)
            // 🎉 is bytes 13..17 (column 10; width 2)
            let text = "日本語 ok 🎉";
            let ta = TextArea::new()
                .with_text(text)
                .with_highlighter(Arc::new(|_l, _t| {
                    vec![
                        (0..6, Style::new().fg(PackedRgba::RED)),
                        (13..17, Style::new().fg(PackedRgba::BLUE)),
                    ]
                }));
            render(&ta, 20, 1, |frame| {
                // Both wide graphemes in 日本 received RED
                assert_eq!(
                    frame.buffer.get(0, 0).unwrap().fg,
                    PackedRgba::RED,
                    "æ—¥ at col 0"
                );
                assert_eq!(
                    frame.buffer.get(2, 0).unwrap().fg,
                    PackedRgba::RED,
                    "本 at col 2"
                );

                // Unstyled graphemes 語 (col 4), ' ' (col 6), 'o' (col 7), 'k' (col 8), ' ' (col 9)
                for col in [4, 6, 7, 8, 9] {
                    assert_ne!(
                        frame.buffer.get(col, 0).unwrap().fg,
                        PackedRgba::RED,
                        "col {col} must not be red"
                    );
                    assert_ne!(
                        frame.buffer.get(col, 0).unwrap().fg,
                        PackedRgba::BLUE,
                        "col {col} must not be blue"
                    );
                }

                // Emoji 🎉 covering bytes 13..17 styles the whole emoji at col 10
                assert_eq!(
                    frame.buffer.get(10, 0).unwrap().fg,
                    PackedRgba::BLUE,
                    "col 10 of 🎉 must be blue"
                );
            });
        }

        fn toy_rust_highlighter(_line_idx: usize, line: &str) -> Vec<(Range<usize>, Style)> {
            let mut spans = Vec::new();
            let keyword_style = Style::new().bold();
            let string_style = Style::new().fg(PackedRgba::GREEN);
            let comment_style = Style::new().dim();

            let code_part = if let Some(comment_pos) = line.find("//") {
                spans.push((comment_pos..line.len(), comment_style));
                &line[..comment_pos]
            } else {
                line
            };

            let mut in_quote: Option<usize> = None;
            for (idx, ch) in code_part.char_indices() {
                if ch == '"' {
                    if let Some(start) = in_quote {
                        spans.push((start..idx + 1, string_style));
                        in_quote = None;
                    } else {
                        in_quote = Some(idx);
                    }
                }
            }

            for kw in ["fn", "let"] {
                let mut search_from = 0;
                while let Some(pos) = code_part[search_from..].find(kw) {
                    let abs_pos = search_from + pos;
                    let end_pos = abs_pos + kw.len();
                    let prev_ok = abs_pos == 0
                        || !code_part[..abs_pos]
                            .chars()
                            .next_back()
                            .is_some_and(|c| c.is_alphanumeric() || c == '_');
                    let next_ok = end_pos == code_part.len()
                        || !code_part[end_pos..]
                            .chars()
                            .next()
                            .is_some_and(|c| c.is_alphanumeric() || c == '_');
                    let in_str = spans
                        .iter()
                        .any(|(r, s)| *s == string_style && r.contains(&abs_pos));
                    if prev_ok && next_ok && !in_str {
                        spans.push((abs_pos..end_pos, keyword_style));
                    }
                    search_from = end_pos;
                }
            }

            spans.sort_by_key(|(r, _)| r.start);
            spans
        }

        fn style_row_text(frame: &Frame, y: u16, width: u16) -> String {
            (0..width)
                .map(|x| {
                    let cell = frame.buffer.get(x, y).unwrap();
                    if cell.attrs.has_flag(StyleFlags::BOLD) {
                        'B'
                    } else if cell.fg == PackedRgba::GREEN {
                        'S'
                    } else if cell.attrs.has_flag(StyleFlags::DIM) {
                        'C'
                    } else {
                        '.'
                    }
                })
                .collect()
        }

        #[test]
        fn textarea_highlighted_rust_60x8() {
            let snippet =
                "fn main() {\n    let name = \"ftui\"; // greet\n    println!(\"hi {name}\");\n}";
            let ta = TextArea::new()
                .with_text(snippet)
                .with_highlighter(Arc::new(toy_rust_highlighter));

            render(&ta, 60, 8, |frame| {
                // Verify text content of lines
                assert_eq!(raw_row_text(frame, 0, 60), format!("{:<60}", "fn main() {"));
                assert_eq!(
                    raw_row_text(frame, 1, 60),
                    format!("{:<60}", "    let name = \"ftui\"; // greet")
                );
                assert_eq!(
                    raw_row_text(frame, 2, 60),
                    format!("{:<60}", "    println!(\"hi {name}\");")
                );
                assert_eq!(raw_row_text(frame, 3, 60), format!("{:<60}", "}"));
                for y in 4..8 {
                    assert_eq!(raw_row_text(frame, y, 60), " ".repeat(60));
                }

                // Verify style masks
                // Row 0: fn (bold) main() {
                assert_eq!(
                    style_row_text(frame, 0, 60),
                    format!("BB{}", ".".repeat(58))
                );
                // Row 1: let (bold), "ftui" (string/green), // greet (dim/comment)
                assert_eq!(
                    style_row_text(frame, 1, 60),
                    format!("....BBB........SSSSSS..CCCCCCCC{}", ".".repeat(29))
                );
                // Row 2: "hi {name}" (string/green)
                assert_eq!(
                    style_row_text(frame, 2, 60),
                    format!(".............SSSSSSSSSSS..{}", ".".repeat(34))
                );
                // Row 3: }
                assert_eq!(style_row_text(frame, 3, 60), ".".repeat(60));
                // Rows 4..8: empty
                for y in 4..8 {
                    assert_eq!(style_row_text(frame, y, 60), ".".repeat(60));
                }
            });
        }

        proptest! {
            #![proptest_config(ProptestConfig::with_cases(512))]

            /// `style_at` returns the last covering range's style and never
            /// panics for any byte offset.
            #[test]
            fn style_at_returns_last_covering_range(
                bounds in prop::collection::vec((0usize..20, 0usize..20), 0..6),
                byte in 0usize..25,
            ) {
                let spans: Vec<(Range<usize>, Style)> = bounds
                    .iter()
                    .filter(|(a, b)| a < b)
                    .enumerate()
                    .map(|(i, (a, b))| (*a..*b, Style::new().fg(PackedRgba::rgb((i * 30) as u8, 1, 2))))
                    .collect();
                let expected = spans.iter().rev().find(|(r, _)| r.contains(&byte)).map(|(_, s)| *s);
                prop_assert_eq!(style_at(&spans, byte), expected);
            }
        }
    }
}