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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import fs from 'node:fs';
import os from 'node:os';
import pathMod from 'node:path';
import * as path from 'node:path';
import { useState, useCallback, useEffect, useMemo, useReducer } from 'react';
import { LRUCache } from 'mnemonist';
import {
  coreEvents,
  debugLogger,
  getErrorMessage,
  unescapePath,
  type EditorType,
} from '@google/gemini-cli-core';
import {
  toCodePoints,
  cpLen,
  cpSlice,
  stripUnsafeCharacters,
  getCachedStringWidth,
} from '../../utils/textUtils.js';
import { parsePastedPaths } from '../../utils/clipboardUtils.js';
import type { Key } from '../../contexts/KeypressContext.js';
import { Command } from '../../key/keyMatchers.js';
import type { VimAction } from './vim-buffer-actions.js';
import { handleVimAction } from './vim-buffer-actions.js';
import { LRU_BUFFER_PERF_CACHE_LIMIT } from '../../constants.js';
import { openFileInEditor } from '../../utils/editorUtils.js';
import { useSettings } from '../../contexts/SettingsContext.js';
import { useKeyMatchers } from '../../hooks/useKeyMatchers.js';

export const LARGE_PASTE_LINE_THRESHOLD = 5;
export const LARGE_PASTE_CHAR_THRESHOLD = 500;

// Regex to match paste placeholders like [Pasted Text: 6 lines] or [Pasted Text: 501 chars #2]
export const PASTED_TEXT_PLACEHOLDER_REGEX =
  /\[Pasted Text: \d+ (?:lines|chars)(?: #\d+)?\]/g;

// Replace paste placeholder strings with their actual pasted content.
export function expandPastePlaceholders(
  text: string,
  pastedContent: Record<string, string>,
): string {
  return text.replace(
    PASTED_TEXT_PLACEHOLDER_REGEX,
    (match) => pastedContent[match] || match,
  );
}

export type Direction =
  | 'left'
  | 'right'
  | 'up'
  | 'down'
  | 'wordLeft'
  | 'wordRight'
  | 'home'
  | 'end';

// Helper functions for line-based word navigation
export const isWordCharStrict = (char: string): boolean =>
  /[\w\p{L}\p{N}]/u.test(char); // Matches a single character that is any Unicode letter, any Unicode number, or an underscore

export const isWhitespace = (char: string): boolean => /\s/.test(char);

// Check if a character is a combining mark (only diacritics for now)
export const isCombiningMark = (char: string): boolean => /\p{M}/u.test(char);

// Check if a character should be considered part of a word (including combining marks)
export const isWordCharWithCombining = (char: string): boolean =>
  isWordCharStrict(char) || isCombiningMark(char);

// Get the script of a character (simplified for common scripts)
export const getCharScript = (char: string): string => {
  if (/[\p{Script=Latin}]/u.test(char)) return 'latin'; // All Latin script chars including diacritics
  if (/[\p{Script=Han}]/u.test(char)) return 'han'; // Chinese
  if (/[\p{Script=Arabic}]/u.test(char)) return 'arabic';
  if (/[\p{Script=Hiragana}]/u.test(char)) return 'hiragana';
  if (/[\p{Script=Katakana}]/u.test(char)) return 'katakana';
  if (/[\p{Script=Cyrillic}]/u.test(char)) return 'cyrillic';
  return 'other';
};

// Check if two characters are from different scripts (indicating word boundary)
export const isDifferentScript = (char1: string, char2: string): boolean => {
  if (!isWordCharStrict(char1) || !isWordCharStrict(char2)) return false;
  return getCharScript(char1) !== getCharScript(char2);
};

// Find next word start within a line, starting from col
export const findNextWordStartInLine = (
  line: string,
  col: number,
): number | null => {
  const chars = toCodePoints(line);
  let i = col;

  if (i >= chars.length) return null;

  const currentChar = chars[i];

  // Skip current word/sequence based on character type
  if (isWordCharStrict(currentChar)) {
    while (i < chars.length && isWordCharWithCombining(chars[i])) {
      // Check for script boundary - if next character is from different script, stop here
      if (
        i + 1 < chars.length &&
        isWordCharStrict(chars[i + 1]) &&
        isDifferentScript(chars[i], chars[i + 1])
      ) {
        i++; // Include current character
        break; // Stop at script boundary
      }
      i++;
    }
  } else if (!isWhitespace(currentChar)) {
    while (
      i < chars.length &&
      !isWordCharStrict(chars[i]) &&
      !isWhitespace(chars[i])
    ) {
      i++;
    }
  }

  // Skip whitespace
  while (i < chars.length && isWhitespace(chars[i])) {
    i++;
  }

  return i < chars.length ? i : null;
};

// Find previous word start within a line
export const findPrevWordStartInLine = (
  line: string,
  col: number,
): number | null => {
  const chars = toCodePoints(line);
  let i = col;

  if (i <= 0) return null;

  i--;

  // Skip whitespace moving backwards
  while (i >= 0 && isWhitespace(chars[i])) {
    i--;
  }

  if (i < 0) return null;

  if (isWordCharStrict(chars[i])) {
    // We're in a word, move to its beginning
    while (i >= 0 && isWordCharStrict(chars[i])) {
      // Check for script boundary - if previous character is from different script, stop here
      if (
        i - 1 >= 0 &&
        isWordCharStrict(chars[i - 1]) &&
        isDifferentScript(chars[i], chars[i - 1])
      ) {
        return i; // Return current position at script boundary
      }
      i--;
    }
    return i + 1;
  } else {
    // We're in punctuation, move to its beginning
    while (i >= 0 && !isWordCharStrict(chars[i]) && !isWhitespace(chars[i])) {
      i--;
    }
    return i + 1;
  }
};

// Find word end within a line
export const findWordEndInLine = (line: string, col: number): number | null => {
  const chars = toCodePoints(line);
  let i = col;

  // If we're already at the end of a word (including punctuation sequences), advance to next word
  // This includes both regular word endings and script boundaries
  let nextBaseCharIdx = i + 1;
  while (
    nextBaseCharIdx < chars.length &&
    isCombiningMark(chars[nextBaseCharIdx])
  ) {
    nextBaseCharIdx++;
  }

  const atEndOfWordChar =
    i < chars.length &&
    isWordCharWithCombining(chars[i]) &&
    (nextBaseCharIdx >= chars.length ||
      !isWordCharStrict(chars[nextBaseCharIdx]) ||
      (isWordCharStrict(chars[i]) &&
        isDifferentScript(chars[i], chars[nextBaseCharIdx])));

  const atEndOfPunctuation =
    i < chars.length &&
    !isWordCharWithCombining(chars[i]) &&
    !isWhitespace(chars[i]) &&
    (i + 1 >= chars.length ||
      isWhitespace(chars[i + 1]) ||
      isWordCharWithCombining(chars[i + 1]));

  if (atEndOfWordChar || atEndOfPunctuation) {
    // We're at the end of a word or punctuation sequence, move forward to find next word
    i++;
    // Skip any combining marks that belong to the word we just finished
    while (i < chars.length && isCombiningMark(chars[i])) {
      i++;
    }
    // Skip whitespace to find next word or punctuation
    while (i < chars.length && isWhitespace(chars[i])) {
      i++;
    }
  }

  // If we're not on a word character, find the next word or punctuation sequence
  if (i < chars.length && !isWordCharWithCombining(chars[i])) {
    // Skip whitespace to find next word or punctuation
    while (i < chars.length && isWhitespace(chars[i])) {
      i++;
    }
  }

  // Move to end of current word (including combining marks, but stop at script boundaries)
  let foundWord = false;
  let lastBaseCharPos = -1;

  if (i < chars.length && isWordCharWithCombining(chars[i])) {
    // Handle word characters
    while (i < chars.length && isWordCharWithCombining(chars[i])) {
      foundWord = true;

      // Track the position of the last base character (not combining mark)
      if (isWordCharStrict(chars[i])) {
        lastBaseCharPos = i;
      }

      // Check if next character is from a different script (word boundary)
      if (
        i + 1 < chars.length &&
        isWordCharStrict(chars[i + 1]) &&
        isDifferentScript(chars[i], chars[i + 1])
      ) {
        i++; // Include current character
        if (isWordCharStrict(chars[i - 1])) {
          lastBaseCharPos = i - 1;
        }
        break; // Stop at script boundary
      }

      i++;
    }
  } else if (i < chars.length && !isWhitespace(chars[i])) {
    // Handle punctuation sequences (like ████)
    while (
      i < chars.length &&
      !isWordCharStrict(chars[i]) &&
      !isWhitespace(chars[i])
    ) {
      foundWord = true;
      lastBaseCharPos = i;
      i++;
    }
  }

  // Only return a position if we actually found a word
  // Return the position of the last base character, not combining marks
  if (foundWord && lastBaseCharPos >= col) {
    return lastBaseCharPos;
  }

  return null;
};

// Find next big word start within a line (W)
export const findNextBigWordStartInLine = (
  line: string,
  col: number,
): number | null => {
  const chars = toCodePoints(line);
  let i = col;

  if (i >= chars.length) return null;

  // If currently on non-whitespace, skip it
  if (!isWhitespace(chars[i])) {
    while (i < chars.length && !isWhitespace(chars[i])) {
      i++;
    }
  }

  // Skip whitespace
  while (i < chars.length && isWhitespace(chars[i])) {
    i++;
  }

  return i < chars.length ? i : null;
};

// Find previous big word start within a line (B)
export const findPrevBigWordStartInLine = (
  line: string,
  col: number,
): number | null => {
  const chars = toCodePoints(line);
  let i = col;

  if (i <= 0) return null;

  i--;

  // Skip whitespace moving backwards
  while (i >= 0 && isWhitespace(chars[i])) {
    i--;
  }

  if (i < 0) return null;

  // We're in a big word, move to its beginning
  while (i >= 0 && !isWhitespace(chars[i])) {
    i--;
  }
  return i + 1;
};

// Find big word end within a line (E)
export const findBigWordEndInLine = (
  line: string,
  col: number,
): number | null => {
  const chars = toCodePoints(line);
  let i = col;

  // If we're already at the end of a big word, advance to next
  const atEndOfBigWord =
    i < chars.length &&
    !isWhitespace(chars[i]) &&
    (i + 1 >= chars.length || isWhitespace(chars[i + 1]));

  if (atEndOfBigWord) {
    i++;
  }

  // Skip whitespace
  while (i < chars.length && isWhitespace(chars[i])) {
    i++;
  }

  // Move to end of current big word
  if (i < chars.length && !isWhitespace(chars[i])) {
    while (i < chars.length && !isWhitespace(chars[i])) {
      i++;
    }
    return i - 1;
  }

  return null;
};

// Initialize segmenter for word boundary detection
const segmenter = new Intl.Segmenter(undefined, { granularity: 'word' });

function findPrevWordBoundary(line: string, cursorCol: number): number {
  const codePoints = toCodePoints(line);
  // Convert cursorCol (CP index) to string index
  const prefix = codePoints.slice(0, cursorCol).join('');
  const cursorIdx = prefix.length;

  let targetIdx = 0;

  for (const seg of segmenter.segment(line)) {
    // We want the last word start strictly before the cursor.
    // If we've reached or passed the cursor, we stop.
    if (seg.index >= cursorIdx) break;

    if (seg.isWordLike) {
      targetIdx = seg.index;
    }
  }

  return toCodePoints(line.slice(0, targetIdx)).length;
}

function findNextWordBoundary(line: string, cursorCol: number): number {
  const codePoints = toCodePoints(line);
  const prefix = codePoints.slice(0, cursorCol).join('');
  const cursorIdx = prefix.length;

  let targetIdx = line.length;

  for (const seg of segmenter.segment(line)) {
    const segEnd = seg.index + seg.segment.length;

    if (segEnd > cursorIdx) {
      if (seg.isWordLike) {
        targetIdx = segEnd;
        break;
      }
    }
  }

  return toCodePoints(line.slice(0, targetIdx)).length;
}

// Find next word across lines
export const findNextWordAcrossLines = (
  lines: string[],
  cursorRow: number,
  cursorCol: number,
  searchForWordStart: boolean,
): { row: number; col: number } | null => {
  // First try current line
  const currentLine = lines[cursorRow] || '';
  const colInCurrentLine = searchForWordStart
    ? findNextWordStartInLine(currentLine, cursorCol)
    : findWordEndInLine(currentLine, cursorCol);

  if (colInCurrentLine !== null) {
    return { row: cursorRow, col: colInCurrentLine };
  }

  let firstEmptyRow: number | null = null;

  // Search subsequent lines
  for (let row = cursorRow + 1; row < lines.length; row++) {
    const line = lines[row] || '';
    const chars = toCodePoints(line);

    // For empty lines, if we haven't found any words yet, remember the first empty line
    if (chars.length === 0) {
      if (firstEmptyRow === null) {
        firstEmptyRow = row;
      }
      continue;
    }

    // Find first non-whitespace
    let firstNonWhitespace = 0;
    while (
      firstNonWhitespace < chars.length &&
      isWhitespace(chars[firstNonWhitespace])
    ) {
      firstNonWhitespace++;
    }

    if (firstNonWhitespace < chars.length) {
      if (searchForWordStart) {
        return { row, col: firstNonWhitespace };
      } else {
        // For word end, find the end of the first word
        const endCol = findWordEndInLine(line, firstNonWhitespace);
        if (endCol !== null) {
          return { row, col: endCol };
        }
      }
    }
  }

  // If no words in later lines, return the first empty line we found
  if (firstEmptyRow !== null) {
    return { row: firstEmptyRow, col: 0 };
  }

  return null;
};

// Find previous word across lines
export const findPrevWordAcrossLines = (
  lines: string[],
  cursorRow: number,
  cursorCol: number,
): { row: number; col: number } | null => {
  // First try current line
  const currentLine = lines[cursorRow] || '';
  const colInCurrentLine = findPrevWordStartInLine(currentLine, cursorCol);

  if (colInCurrentLine !== null) {
    return { row: cursorRow, col: colInCurrentLine };
  }

  // Search previous lines
  for (let row = cursorRow - 1; row >= 0; row--) {
    const line = lines[row] || '';
    const chars = toCodePoints(line);

    if (chars.length === 0) continue;

    // Find last word start
    let lastWordStart = chars.length;
    while (lastWordStart > 0 && isWhitespace(chars[lastWordStart - 1])) {
      lastWordStart--;
    }

    if (lastWordStart > 0) {
      // Find start of this word
      const wordStart = findPrevWordStartInLine(line, lastWordStart);
      if (wordStart !== null) {
        return { row, col: wordStart };
      }
    }
  }

  return null;
};

// Find next big word across lines
export const findNextBigWordAcrossLines = (
  lines: string[],
  cursorRow: number,
  cursorCol: number,
  searchForWordStart: boolean,
): { row: number; col: number } | null => {
  // First try current line
  const currentLine = lines[cursorRow] || '';
  const colInCurrentLine = searchForWordStart
    ? findNextBigWordStartInLine(currentLine, cursorCol)
    : findBigWordEndInLine(currentLine, cursorCol);

  if (colInCurrentLine !== null) {
    return { row: cursorRow, col: colInCurrentLine };
  }

  let firstEmptyRow: number | null = null;

  // Search subsequent lines
  for (let row = cursorRow + 1; row < lines.length; row++) {
    const line = lines[row] || '';
    const chars = toCodePoints(line);

    // For empty lines, if we haven't found any words yet, remember the first empty line
    if (chars.length === 0) {
      if (firstEmptyRow === null) {
        firstEmptyRow = row;
      }
      continue;
    }

    // Find first non-whitespace
    let firstNonWhitespace = 0;
    while (
      firstNonWhitespace < chars.length &&
      isWhitespace(chars[firstNonWhitespace])
    ) {
      firstNonWhitespace++;
    }

    if (firstNonWhitespace < chars.length) {
      // Found a non-whitespace character (start of a big word)
      if (searchForWordStart) {
        return { row, col: firstNonWhitespace };
      } else {
        const endCol = findBigWordEndInLine(line, firstNonWhitespace);
        if (endCol !== null) {
          return { row, col: endCol };
        }
      }
    }
  }

  // If no words in later lines, return the first empty line we found
  if (firstEmptyRow !== null) {
    return { row: firstEmptyRow, col: 0 };
  }

  return null;
};

// Find previous big word across lines
export const findPrevBigWordAcrossLines = (
  lines: string[],
  cursorRow: number,
  cursorCol: number,
): { row: number; col: number } | null => {
  // First try current line
  const currentLine = lines[cursorRow] || '';
  const colInCurrentLine = findPrevBigWordStartInLine(currentLine, cursorCol);

  if (colInCurrentLine !== null) {
    return { row: cursorRow, col: colInCurrentLine };
  }

  // Search previous lines
  for (let row = cursorRow - 1; row >= 0; row--) {
    const line = lines[row] || '';
    const chars = toCodePoints(line);

    if (chars.length === 0) continue;

    // Find last big word start
    let lastWordStart = chars.length;
    while (lastWordStart > 0 && isWhitespace(chars[lastWordStart - 1])) {
      lastWordStart--;
    }

    if (lastWordStart > 0) {
      const wordStart = findPrevBigWordStartInLine(line, lastWordStart);
      if (wordStart !== null) {
        return { row, col: wordStart };
      }
    }
  }

  return null;
};

// Helper functions for vim line operations
export const getPositionFromOffsets = (
  startOffset: number,
  endOffset: number,
  lines: string[],
) => {
  let offset = 0;
  let startRow = 0;
  let startCol = 0;
  let endRow = 0;
  let endCol = 0;

  // Find start position
  for (let i = 0; i < lines.length; i++) {
    const lineLength = lines[i].length + 1; // +1 for newline
    if (offset + lineLength > startOffset) {
      startRow = i;
      startCol = startOffset - offset;
      break;
    }
    offset += lineLength;
  }

  // Find end position
  offset = 0;
  for (let i = 0; i < lines.length; i++) {
    const lineLength = lines[i].length + (i < lines.length - 1 ? 1 : 0); // +1 for newline except last line
    if (offset + lineLength >= endOffset) {
      endRow = i;
      endCol = endOffset - offset;
      break;
    }
    offset += lineLength;
  }

  return { startRow, startCol, endRow, endCol };
};

export const getLineRangeOffsets = (
  startRow: number,
  lineCount: number,
  lines: string[],
) => {
  let startOffset = 0;

  // Calculate start offset
  for (let i = 0; i < startRow; i++) {
    startOffset += lines[i].length + 1; // +1 for newline
  }

  // Calculate end offset
  let endOffset = startOffset;
  for (let i = 0; i < lineCount; i++) {
    const lineIndex = startRow + i;
    if (lineIndex < lines.length) {
      endOffset += lines[lineIndex].length;
      if (lineIndex < lines.length - 1) {
        endOffset += 1; // +1 for newline
      }
    }
  }

  return { startOffset, endOffset };
};

export const replaceRangeInternal = (
  state: TextBufferState,
  startRow: number,
  startCol: number,
  endRow: number,
  endCol: number,
  text: string,
): TextBufferState => {
  const currentLine = (row: number) => state.lines[row] || '';
  const currentLineLen = (row: number) => cpLen(currentLine(row));
  const clamp = (value: number, min: number, max: number) =>
    Math.min(Math.max(value, min), max);

  if (
    startRow > endRow ||
    (startRow === endRow && startCol > endCol) ||
    startRow < 0 ||
    startCol < 0 ||
    endRow >= state.lines.length ||
    (endRow < state.lines.length && endCol > currentLineLen(endRow))
  ) {
    return state; // Invalid range
  }

  const newLines = [...state.lines];

  const sCol = clamp(startCol, 0, currentLineLen(startRow));
  const eCol = clamp(endCol, 0, currentLineLen(endRow));

  const prefix = cpSlice(currentLine(startRow), 0, sCol);
  const suffix = cpSlice(currentLine(endRow), eCol);

  const normalisedReplacement = text
    .replace(/\r\n/g, '\n')
    .replace(/\r/g, '\n');
  const replacementParts = normalisedReplacement.split('\n');

  // The combined first line of the new text
  const firstLine = prefix + replacementParts[0];

  if (replacementParts.length === 1) {
    // No newlines in replacement: combine prefix, replacement, and suffix on one line.
    newLines.splice(startRow, endRow - startRow + 1, firstLine + suffix);
  } else {
    // Newlines in replacement: create new lines.
    const lastLine = replacementParts[replacementParts.length - 1] + suffix;
    const middleLines = replacementParts.slice(1, -1);
    newLines.splice(
      startRow,
      endRow - startRow + 1,
      firstLine,
      ...middleLines,
      lastLine,
    );
  }

  const finalCursorRow = startRow + replacementParts.length - 1;
  const finalCursorCol =
    (replacementParts.length > 1 ? 0 : sCol) +
    cpLen(replacementParts[replacementParts.length - 1]);

  return {
    ...state,
    lines: newLines,
    cursorRow: Math.min(Math.max(finalCursorRow, 0), newLines.length - 1),
    cursorCol: Math.max(
      0,
      Math.min(finalCursorCol, cpLen(newLines[finalCursorRow] || '')),
    ),
    preferredCol: null,
  };
};

export interface Viewport {
  height: number;
  width: number;
}

function clamp(v: number, min: number, max: number): number {
  return v < min ? min : v > max ? max : v;
}

/* ────────────────────────────────────────────────────────────────────────── */

interface UseTextBufferProps {
  initialText?: string;
  initialCursorOffset?: number;
  viewport: Viewport; // Viewport dimensions needed for scrolling
  stdin?: NodeJS.ReadStream | null; // For external editor
  setRawMode?: (mode: boolean) => void; // For external editor
  onChange?: (text: string) => void; // Callback for when text changes
  escapePastedPaths?: boolean;
  shellModeActive?: boolean; // Whether the text buffer is in shell mode
  inputFilter?: (text: string) => string; // Optional filter for input text
  singleLine?: boolean;
  getPreferredEditor?: () => EditorType | undefined;
}

interface UndoHistoryEntry {
  lines: string[];
  cursorRow: number;
  cursorCol: number;
  pastedContent: Record<string, string>;
  expandedPaste: ExpandedPasteInfo | null;
}

function calculateInitialCursorPosition(
  initialLines: string[],
  offset: number,
): [number, number] {
  let remainingChars = offset;
  let row = 0;
  while (row < initialLines.length) {
    const lineLength = cpLen(initialLines[row]);
    // Add 1 for the newline character (except for the last line)
    const totalCharsInLineAndNewline =
      lineLength + (row < initialLines.length - 1 ? 1 : 0);

    if (remainingChars <= lineLength) {
      // Cursor is on this line
      return [row, remainingChars];
    }
    remainingChars -= totalCharsInLineAndNewline;
    row++;
  }
  // Offset is beyond the text, place cursor at the end of the last line
  if (initialLines.length > 0) {
    const lastRow = initialLines.length - 1;
    return [lastRow, cpLen(initialLines[lastRow])];
  }
  return [0, 0]; // Default for empty text
}

export function offsetToLogicalPos(
  text: string,
  offset: number,
): [number, number] {
  let row = 0;
  let col = 0;
  let currentOffset = 0;

  if (offset === 0) return [0, 0];

  const lines = text.split('\n');
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const lineLength = cpLen(line);
    const lineLengthWithNewline = lineLength + (i < lines.length - 1 ? 1 : 0);

    if (offset <= currentOffset + lineLength) {
      // Check against lineLength first
      row = i;
      col = offset - currentOffset;
      return [row, col];
    } else if (offset <= currentOffset + lineLengthWithNewline) {
      // Check if offset is the newline itself
      row = i;
      col = lineLength; // Position cursor at the end of the current line content
      // If the offset IS the newline, and it's not the last line, advance to next line, col 0
      if (
        offset === currentOffset + lineLengthWithNewline &&
        i < lines.length - 1
      ) {
        return [i + 1, 0];
      }
      return [row, col]; // Otherwise, it's at the end of the current line content
    }
    currentOffset += lineLengthWithNewline;
  }

  // If offset is beyond the text length, place cursor at the end of the last line
  // or [0,0] if text is empty
  if (lines.length > 0) {
    row = lines.length - 1;
    col = cpLen(lines[row]);
  } else {
    row = 0;
    col = 0;
  }
  return [row, col];
}

/**
 * Converts logical row/col position to absolute text offset
 * Inverse operation of offsetToLogicalPos
 */
export function logicalPosToOffset(
  lines: string[],
  row: number,
  col: number,
): number {
  let offset = 0;

  // Clamp row to valid range
  const actualRow = Math.min(row, lines.length - 1);

  // Add lengths of all lines before the target row
  for (let i = 0; i < actualRow; i++) {
    offset += cpLen(lines[i]) + 1; // +1 for newline
  }

  // Add column offset within the target row
  if (actualRow >= 0 && actualRow < lines.length) {
    offset += Math.min(col, cpLen(lines[actualRow]));
  }

  return offset;
}
/**
 * Transformations allow for the CLI to render terse representations of things like file paths
 * (e.g., "@some/path/to/an/image.png" to "[Image image.png]")
 * When the cursor enters a transformed representation, it expands to reveal the logical representation.
 * (e.g., "[Image image.png]" to "@some/path/to/an/image.png")
 */
export interface Transformation {
  logStart: number;
  logEnd: number;
  logicalText: string;
  collapsedText: string;
  type: 'image' | 'paste';
  id?: string; // For paste placeholders
}
export const imagePathRegex =
  /@((?:\\.|[^\s\r\n\\])+?\.(?:png|jpg|jpeg|gif|webp|svg|bmp))\b/gi;

export function getTransformedImagePath(filePath: string): string {
  const raw = filePath;

  // Ignore leading @ when stripping directories, but keep it for simple '@file.png'
  const withoutAt = raw.startsWith('@') ? raw.slice(1) : raw;

  // Unescape the path to handle escaped spaces and other characters
  const unescaped = unescapePath(withoutAt);

  // Find last directory separator, supporting both POSIX and Windows styles
  const lastSepIndex = Math.max(
    unescaped.lastIndexOf('/'),
    unescaped.lastIndexOf('\\'),
  );

  // If we saw a separator, take the segment after it; otherwise fall back to the unescaped string
  const fileName =
    lastSepIndex >= 0 ? unescaped.slice(lastSepIndex + 1) : unescaped;

  const extension = path.extname(fileName);
  const baseName = path.basename(fileName, extension);
  const maxBaseLength = 10;

  const truncatedBase =
    baseName.length > maxBaseLength
      ? `...${baseName.slice(-maxBaseLength)}`
      : baseName;

  return `[Image ${truncatedBase}${extension}]`;
}

const transformationsCache = new LRUCache<string, Transformation[]>(
  LRU_BUFFER_PERF_CACHE_LIMIT,
);

export function calculateTransformationsForLine(
  line: string,
): Transformation[] {
  const cached = transformationsCache.get(line);
  if (cached) {
    return cached;
  }

  const transformations: Transformation[] = [];

  // 1. Detect image paths
  imagePathRegex.lastIndex = 0;
  let match: RegExpExecArray | null;
  while ((match = imagePathRegex.exec(line)) !== null) {
    const logicalText = match[0];
    const logStart = cpLen(line.substring(0, match.index));
    const logEnd = logStart + cpLen(logicalText);

    transformations.push({
      logStart,
      logEnd,
      logicalText,
      collapsedText: getTransformedImagePath(logicalText),
      type: 'image',
    });
  }

  // 2. Detect paste placeholders
  const pasteRegex = new RegExp(PASTED_TEXT_PLACEHOLDER_REGEX.source, 'g');
  while ((match = pasteRegex.exec(line)) !== null) {
    const logicalText = match[0];
    const logStart = cpLen(line.substring(0, match.index));
    const logEnd = logStart + cpLen(logicalText);

    transformations.push({
      logStart,
      logEnd,
      logicalText,
      collapsedText: logicalText,
      type: 'paste',
      id: logicalText,
    });
  }

  // Sort transformations by logStart to maintain consistency
  transformations.sort((a, b) => a.logStart - b.logStart);

  transformationsCache.set(line, transformations);

  return transformations;
}

export function calculateTransformations(lines: string[]): Transformation[][] {
  return lines.map((ln) => calculateTransformationsForLine(ln));
}

export function getTransformUnderCursor(
  row: number,
  col: number,
  spansByLine: Transformation[][],
  options: { includeEdge?: boolean } = {},
): Transformation | null {
  const spans = spansByLine[row];
  if (!spans || spans.length === 0) return null;
  for (const span of spans) {
    if (
      col >= span.logStart &&
      (options.includeEdge ? col <= span.logEnd : col < span.logEnd)
    ) {
      return span;
    }
    if (col < span.logStart) break;
  }
  return null;
}

export interface ExpandedPasteInfo {
  id: string;
  startLine: number;
  lineCount: number;
  prefix: string;
  suffix: string;
}

/**
 * Check if a line index falls within an expanded paste region.
 * Returns the paste placeholder ID if found, null otherwise.
 */
export function getExpandedPasteAtLine(
  lineIndex: number,
  expandedPaste: ExpandedPasteInfo | null,
): string | null {
  if (
    expandedPaste &&
    lineIndex >= expandedPaste.startLine &&
    lineIndex < expandedPaste.startLine + expandedPaste.lineCount
  ) {
    return expandedPaste.id;
  }
  return null;
}

/**
 * Surgery for expanded paste regions when lines are added or removed.
 * Adjusts startLine indices and detaches any region that is partially or fully deleted.
 */
export function shiftExpandedRegions(
  expandedPaste: ExpandedPasteInfo | null,
  changeStartLine: number,
  lineDelta: number,
  changeEndLine?: number, // Inclusive
): {
  newInfo: ExpandedPasteInfo | null;
  isDetached: boolean;
} {
  if (!expandedPaste) return { newInfo: null, isDetached: false };

  const effectiveEndLine = changeEndLine ?? changeStartLine;
  const infoEndLine = expandedPaste.startLine + expandedPaste.lineCount - 1;

  // 1. Check for overlap/intersection with the changed range
  const isOverlapping =
    changeStartLine <= infoEndLine &&
    effectiveEndLine >= expandedPaste.startLine;

  if (isOverlapping) {
    // If the change is a deletion (lineDelta < 0) that touches this region, we detach.
    // If it's an insertion, we only detach if it's a multi-line insertion (lineDelta > 0)
    // that isn't at the very start of the region (which would shift it).
    // Regular character typing (lineDelta === 0) does NOT detach.
    if (
      lineDelta < 0 ||
      (lineDelta > 0 &&
        changeStartLine > expandedPaste.startLine &&
        changeStartLine <= infoEndLine)
    ) {
      return { newInfo: null, isDetached: true };
    }
  }

  // 2. Shift regions that start at or after the change point
  if (expandedPaste.startLine >= changeStartLine) {
    return {
      newInfo: {
        ...expandedPaste,
        startLine: expandedPaste.startLine + lineDelta,
      },
      isDetached: false,
    };
  }

  return { newInfo: expandedPaste, isDetached: false };
}

/**
 * Detach any expanded paste region if the cursor is within it.
 * This converts the expanded content to regular text that can no longer be collapsed.
 * Returns the state unchanged if cursor is not in an expanded region.
 */
export function detachExpandedPaste(state: TextBufferState): TextBufferState {
  const expandedId = getExpandedPasteAtLine(
    state.cursorRow,
    state.expandedPaste,
  );
  if (!expandedId) return state;

  const { [expandedId]: _, ...newPastedContent } = state.pastedContent;
  return {
    ...state,
    expandedPaste: null,
    pastedContent: newPastedContent,
  };
}

/**
 * Represents an atomic placeholder that should be deleted as a unit.
 * Extensible to support future placeholder types.
 */
interface AtomicPlaceholder {
  start: number; // Start position in logical text
  end: number; // End position in logical text
  type: 'paste' | 'image'; // Type for cleanup logic
  id?: string; // For paste placeholders: the pastedContent key
}

/**
 * Find atomic placeholder at cursor for backspace (cursor at end).
 * Checks all placeholder types in priority order.
 */
function findAtomicPlaceholderForBackspace(
  line: string,
  cursorCol: number,
  transformations: Transformation[],
): AtomicPlaceholder | null {
  for (const transform of transformations) {
    if (cursorCol === transform.logEnd) {
      return {
        start: transform.logStart,
        end: transform.logEnd,
        type: transform.type,
        id: transform.id,
      };
    }
  }

  return null;
}

/**
 * Find atomic placeholder at cursor for delete (cursor at start).
 */
function findAtomicPlaceholderForDelete(
  line: string,
  cursorCol: number,
  transformations: Transformation[],
): AtomicPlaceholder | null {
  for (const transform of transformations) {
    if (cursorCol === transform.logStart) {
      return {
        start: transform.logStart,
        end: transform.logEnd,
        type: transform.type,
        id: transform.id,
      };
    }
  }

  return null;
}

export function calculateTransformedLine(
  logLine: string,
  logIndex: number,
  logicalCursor: [number, number],
  transformations: Transformation[],
): { transformedLine: string; transformedToLogMap: number[] } {
  let transformedLine = '';
  const transformedToLogMap: number[] = [];
  let lastLogPos = 0;

  const cursorIsOnThisLine = logIndex === logicalCursor[0];
  const cursorCol = logicalCursor[1];

  for (const transform of transformations) {
    const textBeforeTransformation = cpSlice(
      logLine,
      lastLogPos,
      transform.logStart,
    );
    transformedLine += textBeforeTransformation;
    for (let i = 0; i < cpLen(textBeforeTransformation); i++) {
      transformedToLogMap.push(lastLogPos + i);
    }

    const isExpanded =
      transform.type === 'image' &&
      cursorIsOnThisLine &&
      cursorCol >= transform.logStart &&
      cursorCol <= transform.logEnd;
    const transformedText = isExpanded
      ? transform.logicalText
      : transform.collapsedText;
    transformedLine += transformedText;

    // Map transformed characters back to logical characters
    const transformedLen = cpLen(transformedText);
    if (isExpanded) {
      for (let i = 0; i < transformedLen; i++) {
        transformedToLogMap.push(transform.logStart + i);
      }
    } else {
      // Collapsed: distribute transformed positions monotonically across the raw span.
      // This preserves ordering across wrapped slices so logicalToVisualMap has
      // increasing startColInLogical and visual cursor mapping remains consistent.
      const logicalLength = Math.max(0, transform.logEnd - transform.logStart);
      for (let i = 0; i < transformedLen; i++) {
        // Map the i-th transformed code point into [logStart, logEnd)
        const transformationToLogicalOffset =
          logicalLength === 0
            ? 0
            : Math.floor((i * logicalLength) / transformedLen);
        const transformationToLogicalIndex =
          transform.logStart +
          Math.min(
            transformationToLogicalOffset,
            Math.max(logicalLength - 1, 0),
          );
        transformedToLogMap.push(transformationToLogicalIndex);
      }
    }
    lastLogPos = transform.logEnd;
  }

  // Append text after last transform
  const remainingUntransformedText = cpSlice(logLine, lastLogPos);
  transformedLine += remainingUntransformedText;
  for (let i = 0; i < cpLen(remainingUntransformedText); i++) {
    transformedToLogMap.push(lastLogPos + i);
  }

  // For a cursor at the very end of the transformed line
  transformedToLogMap.push(cpLen(logLine));

  return { transformedLine, transformedToLogMap };
}

export interface VisualLayout {
  visualLines: string[];
  // For each logical line, an array of [visualLineIndex, startColInLogical]
  logicalToVisualMap: Array<Array<[number, number]>>;
  // For each visual line, its [logicalLineIndex, startColInLogical]
  visualToLogicalMap: Array<[number, number]>;
  // Image paths are transformed (e.g., "@some/path/to/an/image.png" to "[Image image.png]")
  // For each logical line, an array that maps each transformedCol to a logicalCol
  transformedToLogicalMaps: number[][];
  // For each visual line, its [startColInTransformed]
  visualToTransformedMap: number[];
}

// Caches for layout calculation
interface LineLayoutResult {
  visualLines: string[];
  logicalToVisualMap: Array<[number, number]>;
  visualToLogicalMap: Array<[number, number]>;
  transformedToLogMap: number[];
  visualToTransformedMap: number[];
}

const lineLayoutCache = new LRUCache<string, LineLayoutResult>(
  LRU_BUFFER_PERF_CACHE_LIMIT,
);

function getLineLayoutCacheKey(
  line: string,
  viewportWidth: number,
  isCursorOnLine: boolean,
  cursorCol: number,
): string {
  // Most lines (99.9% in a large buffer) are not cursor lines.
  // We use a simpler key for them to reduce string allocation overhead.
  if (!isCursorOnLine) {
    return `${viewportWidth}:N:${line}`;
  }
  return `${viewportWidth}:C:${cursorCol}:${line}`;
}

// Calculates the visual wrapping of lines and the mapping between logical and visual coordinates.
// This is an expensive operation and should be memoized.
function calculateLayout(
  logicalLines: string[],
  viewportWidth: number,
  logicalCursor: [number, number],
): VisualLayout {
  const visualLines: string[] = [];
  const logicalToVisualMap: Array<Array<[number, number]>> = [];
  const visualToLogicalMap: Array<[number, number]> = [];
  const transformedToLogicalMaps: number[][] = [];
  const visualToTransformedMap: number[] = [];

  logicalLines.forEach((logLine, logIndex) => {
    logicalToVisualMap[logIndex] = [];

    const isCursorOnLine = logIndex === logicalCursor[0];
    const cacheKey = getLineLayoutCacheKey(
      logLine,
      viewportWidth,
      isCursorOnLine,
      logicalCursor[1],
    );
    const cached = lineLayoutCache.get(cacheKey);

    if (cached) {
      const visualLineOffset = visualLines.length;
      visualLines.push(...cached.visualLines);
      cached.logicalToVisualMap.forEach(([relVisualIdx, logCol]) => {
        logicalToVisualMap[logIndex].push([
          visualLineOffset + relVisualIdx,
          logCol,
        ]);
      });
      cached.visualToLogicalMap.forEach(([, logCol]) => {
        visualToLogicalMap.push([logIndex, logCol]);
      });
      transformedToLogicalMaps[logIndex] = cached.transformedToLogMap;
      visualToTransformedMap.push(...cached.visualToTransformedMap);
      return;
    }

    // Not in cache, calculate
    const transformations = calculateTransformationsForLine(logLine);
    const { transformedLine, transformedToLogMap } = calculateTransformedLine(
      logLine,
      logIndex,
      logicalCursor,
      transformations,
    );

    const lineVisualLines: string[] = [];
    const lineLogicalToVisualMap: Array<[number, number]> = [];
    const lineVisualToLogicalMap: Array<[number, number]> = [];
    const lineVisualToTransformedMap: number[] = [];

    if (transformedLine.length === 0) {
      // Handle empty logical line
      lineLogicalToVisualMap.push([0, 0]);
      lineVisualToLogicalMap.push([logIndex, 0]);
      lineVisualToTransformedMap.push(0);
      lineVisualLines.push('');
    } else {
      // Non-empty logical line
      let currentPosInLogLine = 0; // Tracks position within the current logical line (code point index)
      const codePointsInLogLine = toCodePoints(transformedLine);

      while (currentPosInLogLine < codePointsInLogLine.length) {
        let currentChunk = '';
        let currentChunkVisualWidth = 0;
        let numCodePointsInChunk = 0;
        let lastWordBreakPoint = -1; // Index in codePointsInLogLine for word break
        let numCodePointsAtLastWordBreak = 0;

        // Iterate through code points to build the current visual line (chunk)
        for (let i = currentPosInLogLine; i < codePointsInLogLine.length; i++) {
          const char = codePointsInLogLine[i];
          const charVisualWidth = getCachedStringWidth(char);

          if (currentChunkVisualWidth + charVisualWidth > viewportWidth) {
            // Character would exceed viewport width
            if (
              lastWordBreakPoint !== -1 &&
              numCodePointsAtLastWordBreak > 0 &&
              currentPosInLogLine + numCodePointsAtLastWordBreak < i
            ) {
              // We have a valid word break point to use, and it's not the start of the current segment
              currentChunk = codePointsInLogLine
                .slice(
                  currentPosInLogLine,
                  currentPosInLogLine + numCodePointsAtLastWordBreak,
                )
                .join('');
              numCodePointsInChunk = numCodePointsAtLastWordBreak;
            } else {
              // No word break, or word break is at the start of this potential chunk, or word break leads to empty chunk.
              // Hard break: take characters up to viewportWidth, or just the current char if it alone is too wide.
              if (
                numCodePointsInChunk === 0 &&
                charVisualWidth > viewportWidth
              ) {
                // Single character is wider than viewport, take it anyway
                currentChunk = char;
                numCodePointsInChunk = 1;
              }
            }
            break; // Break from inner loop to finalize this chunk
          }

          currentChunk += char;
          currentChunkVisualWidth += charVisualWidth;
          numCodePointsInChunk++;

          // Check for word break opportunity (space)
          if (char === ' ') {
            lastWordBreakPoint = i; // Store code point index of the space
            // Store the state *before* adding the space, if we decide to break here.
            numCodePointsAtLastWordBreak = numCodePointsInChunk - 1; // Chars *before* the space
          }
        }

        if (
          numCodePointsInChunk === 0 &&
          currentPosInLogLine < codePointsInLogLine.length
        ) {
          const firstChar = codePointsInLogLine[currentPosInLogLine];
          currentChunk = firstChar;
          numCodePointsInChunk = 1;
        }

        const logicalStartCol = transformedToLogMap[currentPosInLogLine] ?? 0;
        lineLogicalToVisualMap.push([lineVisualLines.length, logicalStartCol]);
        lineVisualToLogicalMap.push([logIndex, logicalStartCol]);
        lineVisualToTransformedMap.push(currentPosInLogLine);
        lineVisualLines.push(currentChunk);

        const logicalStartOfThisChunk = currentPosInLogLine;
        currentPosInLogLine += numCodePointsInChunk;

        if (
          logicalStartOfThisChunk + numCodePointsInChunk <
            codePointsInLogLine.length &&
          currentPosInLogLine < codePointsInLogLine.length &&
          codePointsInLogLine[currentPosInLogLine] === ' '
        ) {
          currentPosInLogLine++;
        }
      }
    }

    // Cache the result for this line
    lineLayoutCache.set(cacheKey, {
      visualLines: lineVisualLines,
      logicalToVisualMap: lineLogicalToVisualMap,
      visualToLogicalMap: lineVisualToLogicalMap,
      transformedToLogMap,
      visualToTransformedMap: lineVisualToTransformedMap,
    });

    const visualLineOffset = visualLines.length;
    visualLines.push(...lineVisualLines);
    lineLogicalToVisualMap.forEach(([relVisualIdx, logCol]) => {
      logicalToVisualMap[logIndex].push([
        visualLineOffset + relVisualIdx,
        logCol,
      ]);
    });
    lineVisualToLogicalMap.forEach(([, logCol]) => {
      visualToLogicalMap.push([logIndex, logCol]);
    });
    transformedToLogicalMaps[logIndex] = transformedToLogMap;
    visualToTransformedMap.push(...lineVisualToTransformedMap);
  });

  // If the entire logical text was empty, ensure there's one empty visual line.
  if (
    logicalLines.length === 0 ||
    (logicalLines.length === 1 && logicalLines[0] === '')
  ) {
    if (visualLines.length === 0) {
      visualLines.push('');
      if (!logicalToVisualMap[0]) logicalToVisualMap[0] = [];
      logicalToVisualMap[0].push([0, 0]);
      visualToLogicalMap.push([0, 0]);
      visualToTransformedMap.push(0);
    }
  }

  return {
    visualLines,
    logicalToVisualMap,
    visualToLogicalMap,
    transformedToLogicalMaps,
    visualToTransformedMap,
  };
}

// Calculates the visual cursor position based on a pre-calculated layout.
// This is a lightweight operation.
function calculateVisualCursorFromLayout(
  layout: VisualLayout,
  logicalCursor: [number, number],
): [number, number] {
  const { logicalToVisualMap, visualLines, transformedToLogicalMaps } = layout;
  const [logicalRow, logicalCol] = logicalCursor;

  const segmentsForLogicalLine = logicalToVisualMap[logicalRow];

  if (!segmentsForLogicalLine || segmentsForLogicalLine.length === 0) {
    // This can happen for an empty document.
    return [0, 0];
  }

  // Find the segment where the logical column fits.
  // The segments are sorted by startColInLogical.
  let targetSegmentIndex = segmentsForLogicalLine.findIndex(
    ([, startColInLogical], index) => {
      const nextStartColInLogical =
        index + 1 < segmentsForLogicalLine.length
          ? segmentsForLogicalLine[index + 1][1]
          : Infinity;
      return (
        logicalCol >= startColInLogical && logicalCol < nextStartColInLogical
      );
    },
  );

  // If not found, it means the cursor is at the end of the logical line.
  if (targetSegmentIndex === -1) {
    if (logicalCol === 0) {
      targetSegmentIndex = 0;
    } else {
      targetSegmentIndex = segmentsForLogicalLine.length - 1;
    }
  }

  const [visualRow, startColInLogical] =
    segmentsForLogicalLine[targetSegmentIndex];

  // Find the coordinates in transformed space in order to conver to visual
  const transformedToLogicalMap = transformedToLogicalMaps[logicalRow] ?? [];
  let transformedCol = 0;
  for (let i = 0; i < transformedToLogicalMap.length; i++) {
    if (transformedToLogicalMap[i] > logicalCol) {
      transformedCol = Math.max(0, i - 1);
      break;
    }
    if (i === transformedToLogicalMap.length - 1) {
      transformedCol = transformedToLogicalMap.length - 1;
    }
  }
  let startColInTransformed = 0;
  while (
    startColInTransformed < transformedToLogicalMap.length &&
    transformedToLogicalMap[startColInTransformed] < startColInLogical
  ) {
    startColInTransformed++;
  }
  const clampedTransformedCol = Math.min(
    transformedCol,
    Math.max(0, transformedToLogicalMap.length - 1),
  );
  const visualCol = clampedTransformedCol - startColInTransformed;
  const clampedVisualCol = Math.min(
    Math.max(visualCol, 0),
    cpLen(visualLines[visualRow] ?? ''),
  );
  return [visualRow, clampedVisualCol];
}

// --- Start of reducer logic ---

export interface TextBufferState {
  lines: string[];
  cursorRow: number;
  cursorCol: number;
  transformationsByLine: Transformation[][];
  preferredCol: number | null; // This is the logical character offset in the visual line
  undoStack: UndoHistoryEntry[];
  redoStack: UndoHistoryEntry[];
  clipboard: string | null;
  selectionAnchor: [number, number] | null;
  viewportWidth: number;
  viewportHeight: number;
  visualLayout: VisualLayout;
  pastedContent: Record<string, string>;
  expandedPaste: ExpandedPasteInfo | null;
  yankRegister: { text: string; linewise: boolean } | null;
}

const historyLimit = 100;

export const pushUndo = (currentState: TextBufferState): TextBufferState => {
  const snapshot: UndoHistoryEntry = {
    lines: [...currentState.lines],
    cursorRow: currentState.cursorRow,
    cursorCol: currentState.cursorCol,
    pastedContent: { ...currentState.pastedContent },
    expandedPaste: currentState.expandedPaste
      ? { ...currentState.expandedPaste }
      : null,
  };
  const newStack = [...currentState.undoStack, snapshot];
  if (newStack.length > historyLimit) {
    newStack.shift();
  }
  return { ...currentState, undoStack: newStack, redoStack: [] };
};

function generatePastedTextId(
  content: string,
  lineCount: number,
  pastedContent: Record<string, string>,
): string {
  const base =
    lineCount > LARGE_PASTE_LINE_THRESHOLD
      ? `[Pasted Text: ${lineCount} lines]`
      : `[Pasted Text: ${content.length} chars]`;

  let id = base;
  let suffix = 2;
  while (pastedContent[id]) {
    id = base.replace(']', ` #${suffix}]`);
    suffix++;
  }
  return id;
}

function collectPlaceholderIdsFromLines(lines: string[]): Set<string> {
  const ids = new Set<string>();
  const pasteRegex = new RegExp(PASTED_TEXT_PLACEHOLDER_REGEX.source, 'g');
  for (const line of lines) {
    if (!line) continue;
    for (const match of line.matchAll(pasteRegex)) {
      const placeholderId = match[0];
      if (placeholderId) {
        ids.add(placeholderId);
      }
    }
  }
  return ids;
}

function pruneOrphanedPastedContent(
  pastedContent: Record<string, string>,
  expandedPasteId: string | null,
  beforeChangedLines: string[],
  allLines: string[],
): Record<string, string> {
  if (Object.keys(pastedContent).length === 0) return pastedContent;

  const beforeIds = collectPlaceholderIdsFromLines(beforeChangedLines);
  if (beforeIds.size === 0) return pastedContent;

  const afterIds = collectPlaceholderIdsFromLines(allLines);
  const removedIds = [...beforeIds].filter(
    (id) => !afterIds.has(id) && id !== expandedPasteId,
  );
  if (removedIds.length === 0) return pastedContent;

  const pruned = { ...pastedContent };
  for (const id of removedIds) {
    if (pruned[id]) {
      delete pruned[id];
    }
  }
  return pruned;
}

export type TextBufferAction =
  | { type: 'insert'; payload: string; isPaste?: boolean }
  | {
      type: 'set_text';
      payload: string;
      pushToUndo?: boolean;
      cursorPosition?: 'start' | 'end' | number;
    }
  | { type: 'add_pasted_content'; payload: { id: string; text: string } }
  | { type: 'backspace' }
  | {
      type: 'move';
      payload: {
        dir: Direction;
      };
    }
  | {
      type: 'set_cursor';
      payload: {
        cursorRow: number;
        cursorCol: number;
        preferredCol: number | null;
      };
    }
  | { type: 'delete' }
  | { type: 'delete_word_left' }
  | { type: 'delete_word_right' }
  | { type: 'kill_line_right' }
  | { type: 'kill_line_left' }
  | { type: 'undo' }
  | { type: 'redo' }
  | {
      type: 'replace_range';
      payload: {
        startRow: number;
        startCol: number;
        endRow: number;
        endCol: number;
        text: string;
      };
    }
  | { type: 'move_to_offset'; payload: { offset: number } }
  | { type: 'create_undo_snapshot' }
  | { type: 'set_viewport'; payload: { width: number; height: number } }
  | { type: 'vim_delete_word_forward'; payload: { count: number } }
  | { type: 'vim_delete_word_backward'; payload: { count: number } }
  | { type: 'vim_delete_word_end'; payload: { count: number } }
  | { type: 'vim_delete_big_word_forward'; payload: { count: number } }
  | { type: 'vim_delete_big_word_backward'; payload: { count: number } }
  | { type: 'vim_delete_big_word_end'; payload: { count: number } }
  | { type: 'vim_change_word_forward'; payload: { count: number } }
  | { type: 'vim_change_word_backward'; payload: { count: number } }
  | { type: 'vim_change_word_end'; payload: { count: number } }
  | { type: 'vim_change_big_word_forward'; payload: { count: number } }
  | { type: 'vim_change_big_word_backward'; payload: { count: number } }
  | { type: 'vim_change_big_word_end'; payload: { count: number } }
  | { type: 'vim_delete_line'; payload: { count: number } }
  | { type: 'vim_change_line'; payload: { count: number } }
  | { type: 'vim_delete_to_end_of_line'; payload: { count: number } }
  | { type: 'vim_delete_to_start_of_line' }
  | { type: 'vim_change_to_end_of_line'; payload: { count: number } }
  | {
      type: 'vim_change_movement';
      payload: { movement: 'h' | 'j' | 'k' | 'l'; count: number };
    }
  // New vim actions for stateless command handling
  | { type: 'vim_move_left'; payload: { count: number } }
  | { type: 'vim_move_right'; payload: { count: number } }
  | { type: 'vim_move_up'; payload: { count: number } }
  | { type: 'vim_move_down'; payload: { count: number } }
  | { type: 'vim_move_word_forward'; payload: { count: number } }
  | { type: 'vim_move_word_backward'; payload: { count: number } }
  | { type: 'vim_move_word_end'; payload: { count: number } }
  | { type: 'vim_move_big_word_forward'; payload: { count: number } }
  | { type: 'vim_move_big_word_backward'; payload: { count: number } }
  | { type: 'vim_move_big_word_end'; payload: { count: number } }
  | { type: 'vim_delete_char'; payload: { count: number } }
  | { type: 'vim_insert_at_cursor' }
  | { type: 'vim_append_at_cursor' }
  | { type: 'vim_open_line_below' }
  | { type: 'vim_open_line_above' }
  | { type: 'vim_append_at_line_end' }
  | { type: 'vim_insert_at_line_start' }
  | { type: 'vim_move_to_line_start' }
  | { type: 'vim_move_to_line_end' }
  | { type: 'vim_move_to_first_nonwhitespace' }
  | { type: 'vim_move_to_first_line' }
  | { type: 'vim_move_to_last_line' }
  | { type: 'vim_move_to_line'; payload: { lineNumber: number } }
  | { type: 'vim_escape_insert_mode' }
  | { type: 'vim_delete_to_first_nonwhitespace' }
  | { type: 'vim_change_to_start_of_line' }
  | { type: 'vim_change_to_first_nonwhitespace' }
  | { type: 'vim_delete_to_first_line'; payload: { count: number } }
  | { type: 'vim_delete_to_last_line'; payload: { count: number } }
  | { type: 'vim_delete_char_before'; payload: { count: number } }
  | { type: 'vim_toggle_case'; payload: { count: number } }
  | { type: 'vim_replace_char'; payload: { char: string; count: number } }
  | {
      type: 'vim_find_char_forward';
      payload: { char: string; count: number; till: boolean };
    }
  | {
      type: 'vim_find_char_backward';
      payload: { char: string; count: number; till: boolean };
    }
  | {
      type: 'vim_delete_to_char_forward';
      payload: { char: string; count: number; till: boolean };
    }
  | {
      type: 'vim_delete_to_char_backward';
      payload: { char: string; count: number; till: boolean };
    }
  | { type: 'vim_yank_line'; payload: { count: number } }
  | { type: 'vim_yank_word_forward'; payload: { count: number } }
  | { type: 'vim_yank_big_word_forward'; payload: { count: number } }
  | { type: 'vim_yank_word_end'; payload: { count: number } }
  | { type: 'vim_yank_big_word_end'; payload: { count: number } }
  | { type: 'vim_yank_to_end_of_line'; payload: { count: number } }
  | { type: 'vim_paste_after'; payload: { count: number } }
  | { type: 'vim_paste_before'; payload: { count: number } }
  | {
      type: 'toggle_paste_expansion';
      payload: { id: string; row: number; col: number };
    };

export interface TextBufferOptions {
  inputFilter?: (text: string) => string;
  singleLine?: boolean;
}

function textBufferReducerLogic(
  state: TextBufferState,
  action: TextBufferAction,
  options: TextBufferOptions = {},
): TextBufferState {
  const pushUndoLocal = pushUndo;

  const currentLine = (r: number): string => state.lines[r] ?? '';
  const currentLineLen = (r: number): number => cpLen(currentLine(r));

  switch (action.type) {
    case 'set_text': {
      let nextState = state;
      if (action.pushToUndo !== false) {
        nextState = pushUndoLocal(state);
      }
      const newContentLines = action.payload
        .replace(/\r\n?/g, '\n')
        .split('\n');
      const lines = newContentLines.length === 0 ? [''] : newContentLines;

      let newCursorRow: number;
      let newCursorCol: number;

      if (typeof action.cursorPosition === 'number') {
        [newCursorRow, newCursorCol] = offsetToLogicalPos(
          action.payload,
          action.cursorPosition,
        );
      } else if (action.cursorPosition === 'start') {
        newCursorRow = 0;
        newCursorCol = 0;
      } else {
        // Default to 'end'
        newCursorRow = lines.length - 1;
        newCursorCol = cpLen(lines[newCursorRow] ?? '');
      }

      return {
        ...nextState,
        lines,
        cursorRow: newCursorRow,
        cursorCol: newCursorCol,
        preferredCol: null,
        pastedContent: action.payload === '' ? {} : nextState.pastedContent,
      };
    }

    case 'insert': {
      const nextState = detachExpandedPaste(pushUndoLocal(state));
      const newLines = [...nextState.lines];
      let newCursorRow = nextState.cursorRow;
      let newCursorCol = nextState.cursorCol;

      const currentLine = (r: number) => newLines[r] ?? '';

      let payload = action.payload;
      let newPastedContent = nextState.pastedContent;

      if (action.isPaste) {
        // Normalize line endings for pastes
        payload = payload.replace(/\r\n|\r/g, '\n');
        const lineCount = payload.split('\n').length;
        if (
          lineCount > LARGE_PASTE_LINE_THRESHOLD ||
          payload.length > LARGE_PASTE_CHAR_THRESHOLD
        ) {
          const id = generatePastedTextId(payload, lineCount, newPastedContent);
          newPastedContent = {
            ...newPastedContent,
            [id]: payload,
          };
          payload = id;
        }
      }

      if (options.singleLine) {
        payload = payload.replace(/[\r\n]/g, '');
      }
      if (options.inputFilter) {
        payload = options.inputFilter(payload);
      }

      if (payload.length === 0) {
        return state;
      }

      const str = stripUnsafeCharacters(
        payload.replace(/\r\n/g, '\n').replace(/\r/g, '\n'),
      );
      const parts = str.split('\n');
      const lineContent = currentLine(newCursorRow);
      const before = cpSlice(lineContent, 0, newCursorCol);
      const after = cpSlice(lineContent, newCursorCol);

      let lineDelta = 0;
      if (parts.length > 1) {
        newLines[newCursorRow] = before + parts[0];
        const remainingParts = parts.slice(1);
        const lastPartOriginal = remainingParts.pop() ?? '';
        newLines.splice(newCursorRow + 1, 0, ...remainingParts);
        newLines.splice(
          newCursorRow + parts.length - 1,
          0,
          lastPartOriginal + after,
        );
        lineDelta = parts.length - 1;
        newCursorRow = newCursorRow + parts.length - 1;
        newCursorCol = cpLen(lastPartOriginal);
      } else {
        newLines[newCursorRow] = before + parts[0] + after;
        newCursorCol = cpLen(before) + cpLen(parts[0]);
      }

      const { newInfo: newExpandedPaste, isDetached } = shiftExpandedRegions(
        nextState.expandedPaste,
        nextState.cursorRow,
        lineDelta,
      );

      if (isDetached && newExpandedPaste === null && nextState.expandedPaste) {
        delete newPastedContent[nextState.expandedPaste.id];
      }

      return {
        ...nextState,
        lines: newLines,
        cursorRow: newCursorRow,
        cursorCol: newCursorCol,
        preferredCol: null,
        pastedContent: newPastedContent,
        expandedPaste: newExpandedPaste,
      };
    }

    case 'add_pasted_content': {
      const { id, text } = action.payload;
      return {
        ...state,
        pastedContent: {
          ...state.pastedContent,
          [id]: text,
        },
      };
    }

    case 'backspace': {
      const stateWithUndo = pushUndoLocal(state);
      const currentState = detachExpandedPaste(stateWithUndo);
      const { cursorRow, cursorCol, lines, transformationsByLine } =
        currentState;

      // Early return if at start of buffer
      if (cursorCol === 0 && cursorRow === 0) return currentState;

      // Check if cursor is at end of an atomic placeholder
      const transformations = transformationsByLine[cursorRow] ?? [];
      const placeholder = findAtomicPlaceholderForBackspace(
        lines[cursorRow],
        cursorCol,
        transformations,
      );

      if (placeholder) {
        const nextState = currentState;
        const newLines = [...nextState.lines];
        newLines[cursorRow] =
          cpSlice(newLines[cursorRow], 0, placeholder.start) +
          cpSlice(newLines[cursorRow], placeholder.end);

        // Recalculate transformations for the modified line
        const newTransformations = [...nextState.transformationsByLine];
        newTransformations[cursorRow] = calculateTransformationsForLine(
          newLines[cursorRow],
        );

        // Clean up pastedContent if this was a paste placeholder
        let newPastedContent = nextState.pastedContent;
        if (placeholder.type === 'paste' && placeholder.id) {
          const { [placeholder.id]: _, ...remaining } = nextState.pastedContent;
          newPastedContent = remaining;
        }

        return {
          ...nextState,
          lines: newLines,
          cursorCol: placeholder.start,
          preferredCol: null,
          transformationsByLine: newTransformations,
          pastedContent: newPastedContent,
        };
      }

      // Standard backspace logic
      const nextState = currentState;
      const newLines = [...nextState.lines];
      let newCursorRow = nextState.cursorRow;
      let newCursorCol = nextState.cursorCol;

      const currentLine = (r: number) => newLines[r] ?? '';

      let lineDelta = 0;
      if (newCursorCol > 0) {
        const lineContent = currentLine(newCursorRow);
        newLines[newCursorRow] =
          cpSlice(lineContent, 0, newCursorCol - 1) +
          cpSlice(lineContent, newCursorCol);
        newCursorCol--;
      } else if (newCursorRow > 0) {
        const prevLineContent = currentLine(newCursorRow - 1);
        const currentLineContentVal = currentLine(newCursorRow);
        const newCol = cpLen(prevLineContent);
        newLines[newCursorRow - 1] = prevLineContent + currentLineContentVal;
        newLines.splice(newCursorRow, 1);
        lineDelta = -1;
        newCursorRow--;
        newCursorCol = newCol;
      }

      const { newInfo: newExpandedPaste, isDetached } = shiftExpandedRegions(
        nextState.expandedPaste,
        nextState.cursorRow + lineDelta, // shift based on the line that was removed
        lineDelta,
        nextState.cursorRow,
      );

      const newPastedContent = { ...nextState.pastedContent };
      if (isDetached && nextState.expandedPaste) {
        delete newPastedContent[nextState.expandedPaste.id];
      }

      return {
        ...nextState,
        lines: newLines,
        cursorRow: newCursorRow,
        cursorCol: newCursorCol,
        preferredCol: null,
        pastedContent: newPastedContent,
        expandedPaste: newExpandedPaste,
      };
    }

    case 'set_viewport': {
      const { width, height } = action.payload;
      if (width === state.viewportWidth && height === state.viewportHeight) {
        return state;
      }
      return {
        ...state,
        viewportWidth: width,
        viewportHeight: height,
      };
    }

    case 'move': {
      const { dir } = action.payload;
      const { cursorRow, cursorCol, lines, visualLayout, preferredCol } = state;

      // Visual movements
      if (
        dir === 'left' ||
        dir === 'right' ||
        dir === 'up' ||
        dir === 'down' ||
        dir === 'home' ||
        dir === 'end'
      ) {
        const visualCursor = calculateVisualCursorFromLayout(visualLayout, [
          cursorRow,
          cursorCol,
        ]);
        const { visualLines, visualToLogicalMap } = visualLayout;

        let newVisualRow = visualCursor[0];
        let newVisualCol = visualCursor[1];
        let newPreferredCol = preferredCol;

        const currentVisLineLen = cpLen(visualLines[newVisualRow] ?? '');

        switch (dir) {
          case 'left':
            newPreferredCol = null;
            if (newVisualCol > 0) {
              newVisualCol--;
            } else if (newVisualRow > 0) {
              newVisualRow--;
              newVisualCol = cpLen(visualLines[newVisualRow] ?? '');
            }
            break;
          case 'right':
            newPreferredCol = null;
            if (newVisualCol < currentVisLineLen) {
              newVisualCol++;
            } else if (newVisualRow < visualLines.length - 1) {
              newVisualRow++;
              newVisualCol = 0;
            }
            break;
          case 'up':
            if (newVisualRow > 0) {
              if (newPreferredCol === null) newPreferredCol = newVisualCol;
              newVisualRow--;
              newVisualCol = clamp(
                newPreferredCol,
                0,
                cpLen(visualLines[newVisualRow] ?? ''),
              );
            }
            break;
          case 'down':
            if (newVisualRow < visualLines.length - 1) {
              if (newPreferredCol === null) newPreferredCol = newVisualCol;
              newVisualRow++;
              newVisualCol = clamp(
                newPreferredCol,
                0,
                cpLen(visualLines[newVisualRow] ?? ''),
              );
            }
            break;
          case 'home':
            newPreferredCol = null;
            newVisualCol = 0;
            break;
          case 'end':
            newPreferredCol = null;
            newVisualCol = currentVisLineLen;
            break;
          default: {
            const exhaustiveCheck: never = dir;
            debugLogger.error(
              `Unknown visual movement direction: ${exhaustiveCheck}`,
            );
            return state;
          }
        }

        if (visualToLogicalMap[newVisualRow]) {
          const [logRow, logicalStartCol] = visualToLogicalMap[newVisualRow];
          const transformedToLogicalMap =
            visualLayout.transformedToLogicalMaps?.[logRow] ?? [];
          let transformedStartCol = 0;
          while (
            transformedStartCol < transformedToLogicalMap.length &&
            transformedToLogicalMap[transformedStartCol] < logicalStartCol
          ) {
            transformedStartCol++;
          }
          const clampedTransformedCol = Math.min(
            transformedStartCol + newVisualCol,
            Math.max(0, transformedToLogicalMap.length - 1),
          );
          const newLogicalCol =
            transformedToLogicalMap[clampedTransformedCol] ??
            cpLen(lines[logRow] ?? '');
          return {
            ...state,
            cursorRow: logRow,
            cursorCol: newLogicalCol,
            preferredCol: newPreferredCol,
          };
        }
        return state;
      }

      // Logical movements
      switch (dir) {
        case 'wordLeft': {
          if (cursorCol === 0 && cursorRow === 0) return state;

          let newCursorRow = cursorRow;
          let newCursorCol = cursorCol;

          if (cursorCol === 0) {
            newCursorRow--;
            newCursorCol = cpLen(lines[newCursorRow] ?? '');
          } else {
            const lineContent = lines[cursorRow];
            newCursorCol = findPrevWordBoundary(lineContent, cursorCol);
          }
          return {
            ...state,
            cursorRow: newCursorRow,
            cursorCol: newCursorCol,
            preferredCol: null,
          };
        }
        case 'wordRight': {
          const lineContent = lines[cursorRow] ?? '';
          if (
            cursorRow === lines.length - 1 &&
            cursorCol === cpLen(lineContent)
          ) {
            return state;
          }

          let newCursorRow = cursorRow;
          let newCursorCol = cursorCol;
          const lineLen = cpLen(lineContent);

          if (cursorCol >= lineLen) {
            newCursorRow++;
            newCursorCol = 0;
          } else {
            newCursorCol = findNextWordBoundary(lineContent, cursorCol);
          }
          return {
            ...state,
            cursorRow: newCursorRow,
            cursorCol: newCursorCol,
            preferredCol: null,
          };
        }
        default:
          return state;
      }
    }

    case 'set_cursor': {
      return {
        ...state,
        ...action.payload,
      };
    }

    case 'delete': {
      const stateWithUndo = pushUndoLocal(state);
      const currentState = detachExpandedPaste(stateWithUndo);
      const { cursorRow, cursorCol, lines, transformationsByLine } =
        currentState;

      // Check if cursor is at start of an atomic placeholder
      const transformations = transformationsByLine[cursorRow] ?? [];
      const placeholder = findAtomicPlaceholderForDelete(
        lines[cursorRow],
        cursorCol,
        transformations,
      );

      if (placeholder) {
        const nextState = currentState;
        const newLines = [...nextState.lines];
        newLines[cursorRow] =
          cpSlice(newLines[cursorRow], 0, placeholder.start) +
          cpSlice(newLines[cursorRow], placeholder.end);

        // Recalculate transformations for the modified line
        const newTransformations = [...nextState.transformationsByLine];
        newTransformations[cursorRow] = calculateTransformationsForLine(
          newLines[cursorRow],
        );

        // Clean up pastedContent if this was a paste placeholder
        let newPastedContent = nextState.pastedContent;
        if (placeholder.type === 'paste' && placeholder.id) {
          const { [placeholder.id]: _, ...remaining } = nextState.pastedContent;
          newPastedContent = remaining;
        }

        return {
          ...nextState,
          lines: newLines,
          // cursorCol stays the same
          preferredCol: null,
          transformationsByLine: newTransformations,
          pastedContent: newPastedContent,
        };
      }

      // Standard delete logic
      const lineContent = currentLine(cursorRow);
      let lineDelta = 0;
      const nextState = currentState;
      const newLines = [...nextState.lines];

      if (cursorCol < currentLineLen(cursorRow)) {
        newLines[cursorRow] =
          cpSlice(lineContent, 0, cursorCol) +
          cpSlice(lineContent, cursorCol + 1);
      } else if (cursorRow < lines.length - 1) {
        const nextLineContent = currentLine(cursorRow + 1);
        newLines[cursorRow] = lineContent + nextLineContent;
        newLines.splice(cursorRow + 1, 1);
        lineDelta = -1;
      } else {
        return currentState;
      }

      const { newInfo: newExpandedPaste, isDetached } = shiftExpandedRegions(
        nextState.expandedPaste,
        nextState.cursorRow,
        lineDelta,
        nextState.cursorRow + (lineDelta < 0 ? 1 : 0),
      );

      const newPastedContent = { ...nextState.pastedContent };
      if (isDetached && nextState.expandedPaste) {
        delete newPastedContent[nextState.expandedPaste.id];
      }

      return {
        ...nextState,
        lines: newLines,
        preferredCol: null,
        pastedContent: newPastedContent,
        expandedPaste: newExpandedPaste,
      };
    }

    case 'delete_word_left': {
      const stateWithUndo = pushUndoLocal(state);
      const currentState = detachExpandedPaste(stateWithUndo);
      const { cursorRow, cursorCol } = currentState;
      if (cursorCol === 0 && cursorRow === 0) return currentState;

      const nextState = currentState;
      const newLines = [...nextState.lines];
      let newCursorRow = cursorRow;
      let newCursorCol = cursorCol;
      let beforeChangedLines: string[] = [];

      if (newCursorCol > 0) {
        const lineContent = currentLine(newCursorRow);
        beforeChangedLines = [lineContent];
        const prevWordStart = findPrevWordStartInLine(
          lineContent,
          newCursorCol,
        );
        const start = prevWordStart === null ? 0 : prevWordStart;
        newLines[newCursorRow] =
          cpSlice(lineContent, 0, start) + cpSlice(lineContent, newCursorCol);
        newCursorCol = start;
      } else {
        // Act as a backspace
        const prevLineContent = currentLine(cursorRow - 1);
        const currentLineContentVal = currentLine(cursorRow);
        beforeChangedLines = [prevLineContent, currentLineContentVal];
        const newCol = cpLen(prevLineContent);
        newLines[cursorRow - 1] = prevLineContent + currentLineContentVal;
        newLines.splice(cursorRow, 1);
        newCursorRow--;
        newCursorCol = newCol;
      }

      const newPastedContent = pruneOrphanedPastedContent(
        nextState.pastedContent,
        nextState.expandedPaste?.id ?? null,
        beforeChangedLines,
        newLines,
      );

      return {
        ...nextState,
        lines: newLines,
        cursorRow: newCursorRow,
        cursorCol: newCursorCol,
        preferredCol: null,
        pastedContent: newPastedContent,
      };
    }

    case 'delete_word_right': {
      const stateWithUndo = pushUndoLocal(state);
      const currentState = detachExpandedPaste(stateWithUndo);
      const { cursorRow, cursorCol, lines } = currentState;
      const lineContent = currentLine(cursorRow);
      const lineLen = cpLen(lineContent);

      if (cursorCol >= lineLen && cursorRow === lines.length - 1) {
        return currentState;
      }

      const nextState = currentState;
      const newLines = [...nextState.lines];
      let beforeChangedLines: string[] = [];

      if (cursorCol >= lineLen) {
        // Act as a delete, joining with the next line
        const nextLineContent = currentLine(cursorRow + 1);
        beforeChangedLines = [lineContent, nextLineContent];
        newLines[cursorRow] = lineContent + nextLineContent;
        newLines.splice(cursorRow + 1, 1);
      } else {
        beforeChangedLines = [lineContent];
        const nextWordStart = findNextWordStartInLine(lineContent, cursorCol);
        const end = nextWordStart === null ? lineLen : nextWordStart;
        newLines[cursorRow] =
          cpSlice(lineContent, 0, cursorCol) + cpSlice(lineContent, end);
      }

      const newPastedContent = pruneOrphanedPastedContent(
        nextState.pastedContent,
        nextState.expandedPaste?.id ?? null,
        beforeChangedLines,
        newLines,
      );

      return {
        ...nextState,
        lines: newLines,
        preferredCol: null,
        pastedContent: newPastedContent,
      };
    }

    case 'kill_line_right': {
      const stateWithUndo = pushUndoLocal(state);
      const currentState = detachExpandedPaste(stateWithUndo);
      const { cursorRow, cursorCol, lines } = currentState;
      const lineContent = currentLine(cursorRow);
      if (cursorCol < currentLineLen(cursorRow)) {
        const nextState = currentState;
        const newLines = [...nextState.lines];
        const beforeChangedLines = [lineContent];
        newLines[cursorRow] = cpSlice(lineContent, 0, cursorCol);
        const newPastedContent = pruneOrphanedPastedContent(
          nextState.pastedContent,
          nextState.expandedPaste?.id ?? null,
          beforeChangedLines,
          newLines,
        );
        return {
          ...nextState,
          lines: newLines,
          preferredCol: null,
          pastedContent: newPastedContent,
        };
      } else if (cursorRow < lines.length - 1) {
        // Act as a delete
        const nextState = currentState;
        const nextLineContent = currentLine(cursorRow + 1);
        const newLines = [...nextState.lines];
        const beforeChangedLines = [lineContent, nextLineContent];
        newLines[cursorRow] = lineContent + nextLineContent;
        newLines.splice(cursorRow + 1, 1);
        const newPastedContent = pruneOrphanedPastedContent(
          nextState.pastedContent,
          nextState.expandedPaste?.id ?? null,
          beforeChangedLines,
          newLines,
        );
        return {
          ...nextState,
          lines: newLines,
          preferredCol: null,
          pastedContent: newPastedContent,
        };
      }
      return currentState;
    }

    case 'kill_line_left': {
      const stateWithUndo = pushUndoLocal(state);
      const currentState = detachExpandedPaste(stateWithUndo);
      const { cursorRow, cursorCol } = currentState;
      if (cursorCol > 0) {
        const nextState = currentState;
        const lineContent = currentLine(cursorRow);
        const newLines = [...nextState.lines];
        const beforeChangedLines = [lineContent];
        newLines[cursorRow] = cpSlice(lineContent, cursorCol);
        const newPastedContent = pruneOrphanedPastedContent(
          nextState.pastedContent,
          nextState.expandedPaste?.id ?? null,
          beforeChangedLines,
          newLines,
        );
        return {
          ...nextState,
          lines: newLines,
          cursorCol: 0,
          preferredCol: null,
          pastedContent: newPastedContent,
        };
      }
      return currentState;
    }

    case 'undo': {
      const stateToRestore = state.undoStack[state.undoStack.length - 1];
      if (!stateToRestore) return state;

      const currentSnapshot: UndoHistoryEntry = {
        lines: [...state.lines],
        cursorRow: state.cursorRow,
        cursorCol: state.cursorCol,
        pastedContent: { ...state.pastedContent },
        expandedPaste: state.expandedPaste ? { ...state.expandedPaste } : null,
      };
      return {
        ...state,
        ...stateToRestore,
        undoStack: state.undoStack.slice(0, -1),
        redoStack: [...state.redoStack, currentSnapshot],
      };
    }

    case 'redo': {
      const stateToRestore = state.redoStack[state.redoStack.length - 1];
      if (!stateToRestore) return state;

      const currentSnapshot: UndoHistoryEntry = {
        lines: [...state.lines],
        cursorRow: state.cursorRow,
        cursorCol: state.cursorCol,
        pastedContent: { ...state.pastedContent },
        expandedPaste: state.expandedPaste ? { ...state.expandedPaste } : null,
      };
      return {
        ...state,
        ...stateToRestore,
        redoStack: state.redoStack.slice(0, -1),
        undoStack: [...state.undoStack, currentSnapshot],
      };
    }

    case 'replace_range': {
      const { startRow, startCol, endRow, endCol, text } = action.payload;
      const nextState = pushUndoLocal(state);
      const newState = replaceRangeInternal(
        nextState,
        startRow,
        startCol,
        endRow,
        endCol,
        text,
      );

      const oldLineCount = endRow - startRow + 1;
      const newLineCount =
        newState.lines.length - (nextState.lines.length - oldLineCount);
      const lineDelta = newLineCount - oldLineCount;

      const { newInfo: newExpandedPaste, isDetached } = shiftExpandedRegions(
        nextState.expandedPaste,
        startRow,
        lineDelta,
        endRow,
      );

      const newPastedContent = { ...newState.pastedContent };
      if (isDetached && nextState.expandedPaste) {
        delete newPastedContent[nextState.expandedPaste.id];
      }

      return {
        ...newState,
        pastedContent: newPastedContent,
        expandedPaste: newExpandedPaste,
      };
    }

    case 'move_to_offset': {
      const { offset } = action.payload;
      const [newRow, newCol] = offsetToLogicalPos(
        state.lines.join('\n'),
        offset,
      );
      return {
        ...state,
        cursorRow: newRow,
        cursorCol: newCol,
        preferredCol: null,
      };
    }

    case 'create_undo_snapshot': {
      return pushUndoLocal(state);
    }

    // Vim-specific operations
    case 'vim_delete_word_forward':
    case 'vim_delete_word_backward':
    case 'vim_delete_word_end':
    case 'vim_delete_big_word_forward':
    case 'vim_delete_big_word_backward':
    case 'vim_delete_big_word_end':
    case 'vim_change_word_forward':
    case 'vim_change_word_backward':
    case 'vim_change_word_end':
    case 'vim_change_big_word_forward':
    case 'vim_change_big_word_backward':
    case 'vim_change_big_word_end':
    case 'vim_delete_line':
    case 'vim_change_line':
    case 'vim_delete_to_end_of_line':
    case 'vim_delete_to_start_of_line':
    case 'vim_change_to_end_of_line':
    case 'vim_change_movement':
    case 'vim_move_left':
    case 'vim_move_right':
    case 'vim_move_up':
    case 'vim_move_down':
    case 'vim_move_word_forward':
    case 'vim_move_word_backward':
    case 'vim_move_word_end':
    case 'vim_move_big_word_forward':
    case 'vim_move_big_word_backward':
    case 'vim_move_big_word_end':
    case 'vim_delete_char':
    case 'vim_insert_at_cursor':
    case 'vim_append_at_cursor':
    case 'vim_open_line_below':
    case 'vim_open_line_above':
    case 'vim_append_at_line_end':
    case 'vim_insert_at_line_start':
    case 'vim_move_to_line_start':
    case 'vim_move_to_line_end':
    case 'vim_move_to_first_nonwhitespace':
    case 'vim_move_to_first_line':
    case 'vim_move_to_last_line':
    case 'vim_move_to_line':
    case 'vim_escape_insert_mode':
    case 'vim_delete_to_first_nonwhitespace':
    case 'vim_change_to_start_of_line':
    case 'vim_change_to_first_nonwhitespace':
    case 'vim_delete_to_first_line':
    case 'vim_delete_to_last_line':
    case 'vim_delete_char_before':
    case 'vim_toggle_case':
    case 'vim_replace_char':
    case 'vim_find_char_forward':
    case 'vim_find_char_backward':
    case 'vim_delete_to_char_forward':
    case 'vim_delete_to_char_backward':
    case 'vim_yank_line':
    case 'vim_yank_word_forward':
    case 'vim_yank_big_word_forward':
    case 'vim_yank_word_end':
    case 'vim_yank_big_word_end':
    case 'vim_yank_to_end_of_line':
    case 'vim_paste_after':
    case 'vim_paste_before':
      return handleVimAction(state, action as VimAction);

    case 'toggle_paste_expansion': {
      const { id, row, col } = action.payload;
      const expandedPaste = state.expandedPaste;

      if (expandedPaste && expandedPaste.id === id) {
        const nextState = pushUndoLocal(state);
        // COLLAPSE: Restore original line with placeholder
        const newLines = [...nextState.lines];
        newLines.splice(
          expandedPaste.startLine,
          expandedPaste.lineCount,
          expandedPaste.prefix + id + expandedPaste.suffix,
        );

        // Move cursor to end of collapsed placeholder
        const newCursorRow = expandedPaste.startLine;
        const newCursorCol = cpLen(expandedPaste.prefix) + cpLen(id);

        return {
          ...nextState,
          lines: newLines,
          cursorRow: newCursorRow,
          cursorCol: newCursorCol,
          preferredCol: null,
          expandedPaste: null,
        };
      } else {
        // EXPAND: Replace placeholder with content

        // Collapse any existing expanded paste first
        let currentState = state;
        let targetRow = row;
        if (state.expandedPaste) {
          const existingInfo = state.expandedPaste;
          const lineDelta = 1 - existingInfo.lineCount;

          if (targetRow !== undefined && targetRow > existingInfo.startLine) {
            // If we collapsed something above our target, our target row shifted up
            targetRow += lineDelta;
          }

          currentState = textBufferReducerLogic(state, {
            type: 'toggle_paste_expansion',
            payload: {
              id: existingInfo.id,
              row: existingInfo.startLine,
              col: 0,
            },
          });
          // Update transformations because they are needed for finding the next placeholder
          currentState.transformationsByLine = calculateTransformations(
            currentState.lines,
          );
        }

        const content = currentState.pastedContent[id];
        if (!content) return currentState;

        // Find line and position containing exactly this placeholder
        let lineIndex = -1;
        let placeholderStart = -1;

        const tryFindOnLine = (idx: number) => {
          const transforms = currentState.transformationsByLine[idx] ?? [];

          // Precise match by col
          let transform = transforms.find(
            (t) =>
              t.type === 'paste' &&
              t.id === id &&
              col >= t.logStart &&
              col <= t.logEnd,
          );

          if (!transform) {
            // Fallback to first match on line
            transform = transforms.find(
              (t) => t.type === 'paste' && t.id === id,
            );
          }

          if (transform) {
            lineIndex = idx;
            placeholderStart = transform.logStart;
            return true;
          }
          return false;
        };

        // Try provided row first for precise targeting
        if (targetRow >= 0 && targetRow < currentState.lines.length) {
          tryFindOnLine(targetRow);
        }

        if (lineIndex === -1) {
          for (let i = 0; i < currentState.lines.length; i++) {
            if (tryFindOnLine(i)) break;
          }
        }

        if (lineIndex === -1) return currentState;

        const nextState = pushUndoLocal(currentState);

        const line = nextState.lines[lineIndex];
        const prefix = cpSlice(line, 0, placeholderStart);
        const suffix = cpSlice(line, placeholderStart + cpLen(id));

        // Split content into lines
        const contentLines = content.split('\n');
        const newLines = [...nextState.lines];

        let expandedLines: string[];
        if (contentLines.length === 1) {
          // Single-line content
          expandedLines = [prefix + contentLines[0] + suffix];
        } else {
          // Multi-line content
          expandedLines = [
            prefix + contentLines[0],
            ...contentLines.slice(1, -1),
            contentLines[contentLines.length - 1] + suffix,
          ];
        }

        newLines.splice(lineIndex, 1, ...expandedLines);

        // Move cursor to end of expanded content (before suffix)
        const newCursorRow = lineIndex + expandedLines.length - 1;
        const lastExpandedLine = expandedLines[expandedLines.length - 1];
        const newCursorCol = cpLen(lastExpandedLine) - cpLen(suffix);

        return {
          ...nextState,
          lines: newLines,
          cursorRow: newCursorRow,
          cursorCol: newCursorCol,
          preferredCol: null,
          expandedPaste: {
            id,
            startLine: lineIndex,
            lineCount: expandedLines.length,
            prefix,
            suffix,
          },
        };
      }
    }

    default: {
      const exhaustiveCheck: never = action;
      debugLogger.error(`Unknown action encountered: ${exhaustiveCheck}`);
      return state;
    }
  }
}

export function textBufferReducer(
  state: TextBufferState,
  action: TextBufferAction,
  options: TextBufferOptions = {},
): TextBufferState {
  const newState = textBufferReducerLogic(state, action, options);

  const newTransformedLines =
    newState.lines !== state.lines
      ? calculateTransformations(newState.lines)
      : state.transformationsByLine;

  const oldTransform = getTransformUnderCursor(
    state.cursorRow,
    state.cursorCol,
    state.transformationsByLine,
  );
  const newTransform = getTransformUnderCursor(
    newState.cursorRow,
    newState.cursorCol,
    newTransformedLines,
  );
  const oldInside = oldTransform !== null;
  const newInside = newTransform !== null;
  const movedBetweenTransforms =
    oldTransform !== newTransform &&
    (oldTransform !== null || newTransform !== null);

  if (
    newState.lines !== state.lines ||
    newState.viewportWidth !== state.viewportWidth ||
    oldInside !== newInside ||
    movedBetweenTransforms
  ) {
    const shouldResetPreferred =
      oldInside !== newInside || movedBetweenTransforms;

    return {
      ...newState,
      preferredCol: shouldResetPreferred ? null : newState.preferredCol,
      visualLayout: calculateLayout(newState.lines, newState.viewportWidth, [
        newState.cursorRow,
        newState.cursorCol,
      ]),
      transformationsByLine: newTransformedLines,
    };
  }

  return newState;
}

// --- End of reducer logic ---

export function useTextBuffer({
  initialText = '',
  initialCursorOffset = 0,
  viewport,
  stdin,
  setRawMode,
  onChange,
  escapePastedPaths = false,
  shellModeActive = false,
  inputFilter,
  singleLine = false,
  getPreferredEditor,
}: UseTextBufferProps): TextBuffer {
  const settings = useSettings();
  const keyMatchers = useKeyMatchers();
  const initialState = useMemo((): TextBufferState => {
    const lines = initialText.split('\n');
    const [initialCursorRow, initialCursorCol] = calculateInitialCursorPosition(
      lines.length === 0 ? [''] : lines,
      initialCursorOffset,
    );
    const transformationsByLine = calculateTransformations(
      lines.length === 0 ? [''] : lines,
    );
    const visualLayout = calculateLayout(
      lines.length === 0 ? [''] : lines,
      viewport.width,
      [initialCursorRow, initialCursorCol],
    );
    return {
      lines: lines.length === 0 ? [''] : lines,
      cursorRow: initialCursorRow,
      cursorCol: initialCursorCol,
      transformationsByLine,
      preferredCol: null,
      undoStack: [],
      redoStack: [],
      clipboard: null,
      selectionAnchor: null,
      viewportWidth: viewport.width,
      viewportHeight: viewport.height,
      visualLayout,
      pastedContent: {},
      expandedPaste: null,
      yankRegister: null,
    };
  }, [initialText, initialCursorOffset, viewport.width, viewport.height]);

  const [state, dispatch] = useReducer(
    (s: TextBufferState, a: TextBufferAction) =>
      textBufferReducer(s, a, { inputFilter, singleLine }),
    initialState,
  );
  const {
    lines,
    cursorRow,
    cursorCol,
    preferredCol,
    selectionAnchor,
    visualLayout,
    transformationsByLine,
    pastedContent,
    expandedPaste,
    undoStack,
    redoStack,
  } = state;

  const text = useMemo(() => lines.join('\n'), [lines]);

  const visualCursor = useMemo(
    () => calculateVisualCursorFromLayout(visualLayout, [cursorRow, cursorCol]),
    [visualLayout, cursorRow, cursorCol],
  );

  const {
    visualLines,
    visualToLogicalMap,
    transformedToLogicalMaps,
    visualToTransformedMap,
  } = visualLayout;

  const [scrollRowState, setScrollRowState] = useState<number>(0);

  const { height } = viewport;
  const totalVisualLines = visualLines.length;
  const maxScrollStart = Math.max(0, totalVisualLines - height);
  let newVisualScrollRow = scrollRowState;

  if (visualCursor[0] < scrollRowState) {
    newVisualScrollRow = visualCursor[0];
  } else if (visualCursor[0] >= scrollRowState + height) {
    newVisualScrollRow = visualCursor[0] - height + 1;
  }

  newVisualScrollRow = clamp(newVisualScrollRow, 0, maxScrollStart);

  if (newVisualScrollRow !== scrollRowState) {
    setScrollRowState(newVisualScrollRow);
  }

  const actualScrollRowState = newVisualScrollRow;

  useEffect(() => {
    if (onChange) {
      onChange(text);
    }
  }, [text, onChange]);

  useEffect(() => {
    dispatch({
      type: 'set_viewport',
      payload: { width: viewport.width, height: viewport.height },
    });
  }, [viewport.width, viewport.height]);

  const insert = useCallback(
    (ch: string, { paste = false }: { paste?: boolean } = {}): void => {
      if (typeof ch !== 'string') {
        return;
      }

      let textToInsert = ch;
      const minLengthToInferAsDragDrop = 3;
      if (
        ch.length >= minLengthToInferAsDragDrop &&
        !shellModeActive &&
        paste &&
        escapePastedPaths
      ) {
        const processed = parsePastedPaths(ch.trim());
        if (processed) {
          textToInsert = processed;
        }
      }

      let currentText = '';
      for (const char of toCodePoints(textToInsert)) {
        if (char.codePointAt(0) === 127) {
          if (currentText.length > 0) {
            dispatch({ type: 'insert', payload: currentText, isPaste: paste });
            currentText = '';
          }
          dispatch({ type: 'backspace' });
        } else {
          currentText += char;
        }
      }
      if (currentText.length > 0) {
        dispatch({ type: 'insert', payload: currentText, isPaste: paste });
      }
    },
    [shellModeActive, escapePastedPaths],
  );

  const newline = useCallback((): void => {
    if (singleLine) {
      return;
    }
    dispatch({ type: 'insert', payload: '\n' });
  }, [singleLine]);

  const backspace = useCallback((): void => {
    dispatch({ type: 'backspace' });
  }, []);

  const del = useCallback((): void => {
    dispatch({ type: 'delete' });
  }, []);

  const move = useCallback(
    (dir: Direction): void => {
      dispatch({ type: 'move', payload: { dir } });
    },
    [dispatch],
  );

  const undo = useCallback((): void => {
    dispatch({ type: 'undo' });
  }, []);

  const redo = useCallback((): void => {
    dispatch({ type: 'redo' });
  }, []);

  const setText = useCallback(
    (newText: string, cursorPosition?: 'start' | 'end' | number): void => {
      dispatch({ type: 'set_text', payload: newText, cursorPosition });
    },
    [],
  );

  const deleteWordLeft = useCallback((): void => {
    dispatch({ type: 'delete_word_left' });
  }, []);

  const deleteWordRight = useCallback((): void => {
    dispatch({ type: 'delete_word_right' });
  }, []);

  const killLineRight = useCallback((): void => {
    dispatch({ type: 'kill_line_right' });
  }, []);

  const killLineLeft = useCallback((): void => {
    dispatch({ type: 'kill_line_left' });
  }, []);

  // Vim-specific operations
  const vimDeleteWordForward = useCallback((count: number): void => {
    dispatch({ type: 'vim_delete_word_forward', payload: { count } });
  }, []);

  const vimDeleteWordBackward = useCallback((count: number): void => {
    dispatch({ type: 'vim_delete_word_backward', payload: { count } });
  }, []);

  const vimDeleteWordEnd = useCallback((count: number): void => {
    dispatch({ type: 'vim_delete_word_end', payload: { count } });
  }, []);

  const vimDeleteBigWordForward = useCallback((count: number): void => {
    dispatch({ type: 'vim_delete_big_word_forward', payload: { count } });
  }, []);

  const vimDeleteBigWordBackward = useCallback((count: number): void => {
    dispatch({ type: 'vim_delete_big_word_backward', payload: { count } });
  }, []);

  const vimDeleteBigWordEnd = useCallback((count: number): void => {
    dispatch({ type: 'vim_delete_big_word_end', payload: { count } });
  }, []);

  const vimChangeWordForward = useCallback((count: number): void => {
    dispatch({ type: 'vim_change_word_forward', payload: { count } });
  }, []);

  const vimChangeWordBackward = useCallback((count: number): void => {
    dispatch({ type: 'vim_change_word_backward', payload: { count } });
  }, []);

  const vimChangeWordEnd = useCallback((count: number): void => {
    dispatch({ type: 'vim_change_word_end', payload: { count } });
  }, []);

  const vimChangeBigWordForward = useCallback((count: number): void => {
    dispatch({ type: 'vim_change_big_word_forward', payload: { count } });
  }, []);

  const vimChangeBigWordBackward = useCallback((count: number): void => {
    dispatch({ type: 'vim_change_big_word_backward', payload: { count } });
  }, []);

  const vimChangeBigWordEnd = useCallback((count: number): void => {
    dispatch({ type: 'vim_change_big_word_end', payload: { count } });
  }, []);

  const vimDeleteLine = useCallback((count: number): void => {
    dispatch({ type: 'vim_delete_line', payload: { count } });
  }, []);

  const vimChangeLine = useCallback((count: number): void => {
    dispatch({ type: 'vim_change_line', payload: { count } });
  }, []);

  const vimDeleteToEndOfLine = useCallback((count: number = 1): void => {
    dispatch({ type: 'vim_delete_to_end_of_line', payload: { count } });
  }, []);

  const vimDeleteToStartOfLine = useCallback((): void => {
    dispatch({ type: 'vim_delete_to_start_of_line' });
  }, []);

  const vimChangeToEndOfLine = useCallback((count: number = 1): void => {
    dispatch({ type: 'vim_change_to_end_of_line', payload: { count } });
  }, []);

  const vimDeleteToFirstNonWhitespace = useCallback((): void => {
    dispatch({ type: 'vim_delete_to_first_nonwhitespace' });
  }, []);

  const vimChangeToStartOfLine = useCallback((): void => {
    dispatch({ type: 'vim_change_to_start_of_line' });
  }, []);

  const vimChangeToFirstNonWhitespace = useCallback((): void => {
    dispatch({ type: 'vim_change_to_first_nonwhitespace' });
  }, []);

  const vimDeleteToFirstLine = useCallback((count: number): void => {
    dispatch({ type: 'vim_delete_to_first_line', payload: { count } });
  }, []);

  const vimDeleteToLastLine = useCallback((count: number): void => {
    dispatch({ type: 'vim_delete_to_last_line', payload: { count } });
  }, []);

  const vimChangeMovement = useCallback(
    (movement: 'h' | 'j' | 'k' | 'l', count: number): void => {
      dispatch({ type: 'vim_change_movement', payload: { movement, count } });
    },
    [],
  );

  // New vim navigation and operation methods
  const vimMoveLeft = useCallback((count: number): void => {
    dispatch({ type: 'vim_move_left', payload: { count } });
  }, []);

  const vimMoveRight = useCallback((count: number): void => {
    dispatch({ type: 'vim_move_right', payload: { count } });
  }, []);

  const vimMoveUp = useCallback((count: number): void => {
    dispatch({ type: 'vim_move_up', payload: { count } });
  }, []);

  const vimMoveDown = useCallback((count: number): void => {
    dispatch({ type: 'vim_move_down', payload: { count } });
  }, []);

  const vimMoveWordForward = useCallback((count: number): void => {
    dispatch({ type: 'vim_move_word_forward', payload: { count } });
  }, []);

  const vimMoveWordBackward = useCallback((count: number): void => {
    dispatch({ type: 'vim_move_word_backward', payload: { count } });
  }, []);

  const vimMoveWordEnd = useCallback((count: number): void => {
    dispatch({ type: 'vim_move_word_end', payload: { count } });
  }, []);

  const vimMoveBigWordForward = useCallback((count: number): void => {
    dispatch({ type: 'vim_move_big_word_forward', payload: { count } });
  }, []);

  const vimMoveBigWordBackward = useCallback((count: number): void => {
    dispatch({ type: 'vim_move_big_word_backward', payload: { count } });
  }, []);

  const vimMoveBigWordEnd = useCallback((count: number): void => {
    dispatch({ type: 'vim_move_big_word_end', payload: { count } });
  }, []);

  const vimDeleteChar = useCallback((count: number): void => {
    dispatch({ type: 'vim_delete_char', payload: { count } });
  }, []);

  const vimDeleteCharBefore = useCallback((count: number): void => {
    dispatch({ type: 'vim_delete_char_before', payload: { count } });
  }, []);

  const vimToggleCase = useCallback((count: number): void => {
    dispatch({ type: 'vim_toggle_case', payload: { count } });
  }, []);

  const vimReplaceChar = useCallback((char: string, count: number): void => {
    dispatch({ type: 'vim_replace_char', payload: { char, count } });
  }, []);

  const vimFindCharForward = useCallback(
    (char: string, count: number, till: boolean): void => {
      dispatch({
        type: 'vim_find_char_forward',
        payload: { char, count, till },
      });
    },
    [],
  );

  const vimFindCharBackward = useCallback(
    (char: string, count: number, till: boolean): void => {
      dispatch({
        type: 'vim_find_char_backward',
        payload: { char, count, till },
      });
    },
    [],
  );

  const vimDeleteToCharForward = useCallback(
    (char: string, count: number, till: boolean): void => {
      dispatch({
        type: 'vim_delete_to_char_forward',
        payload: { char, count, till },
      });
    },
    [],
  );

  const vimDeleteToCharBackward = useCallback(
    (char: string, count: number, till: boolean): void => {
      dispatch({
        type: 'vim_delete_to_char_backward',
        payload: { char, count, till },
      });
    },
    [],
  );

  const vimInsertAtCursor = useCallback((): void => {
    dispatch({ type: 'vim_insert_at_cursor' });
  }, []);

  const vimAppendAtCursor = useCallback((): void => {
    dispatch({ type: 'vim_append_at_cursor' });
  }, []);

  const vimOpenLineBelow = useCallback((): void => {
    dispatch({ type: 'vim_open_line_below' });
  }, []);

  const vimOpenLineAbove = useCallback((): void => {
    dispatch({ type: 'vim_open_line_above' });
  }, []);

  const vimAppendAtLineEnd = useCallback((): void => {
    dispatch({ type: 'vim_append_at_line_end' });
  }, []);

  const vimInsertAtLineStart = useCallback((): void => {
    dispatch({ type: 'vim_insert_at_line_start' });
  }, []);

  const vimMoveToLineStart = useCallback((): void => {
    dispatch({ type: 'vim_move_to_line_start' });
  }, []);

  const vimMoveToLineEnd = useCallback((): void => {
    dispatch({ type: 'vim_move_to_line_end' });
  }, []);

  const vimMoveToFirstNonWhitespace = useCallback((): void => {
    dispatch({ type: 'vim_move_to_first_nonwhitespace' });
  }, []);

  const vimMoveToFirstLine = useCallback((): void => {
    dispatch({ type: 'vim_move_to_first_line' });
  }, []);

  const vimMoveToLastLine = useCallback((): void => {
    dispatch({ type: 'vim_move_to_last_line' });
  }, []);

  const vimMoveToLine = useCallback((lineNumber: number): void => {
    dispatch({ type: 'vim_move_to_line', payload: { lineNumber } });
  }, []);

  const vimEscapeInsertMode = useCallback((): void => {
    dispatch({ type: 'vim_escape_insert_mode' });
  }, []);

  const vimYankLine = useCallback((count: number): void => {
    dispatch({ type: 'vim_yank_line', payload: { count } });
  }, []);

  const vimYankWordForward = useCallback((count: number): void => {
    dispatch({ type: 'vim_yank_word_forward', payload: { count } });
  }, []);

  const vimYankBigWordForward = useCallback((count: number): void => {
    dispatch({ type: 'vim_yank_big_word_forward', payload: { count } });
  }, []);

  const vimYankWordEnd = useCallback((count: number): void => {
    dispatch({ type: 'vim_yank_word_end', payload: { count } });
  }, []);

  const vimYankBigWordEnd = useCallback((count: number): void => {
    dispatch({ type: 'vim_yank_big_word_end', payload: { count } });
  }, []);

  const vimYankToEndOfLine = useCallback((count: number): void => {
    dispatch({ type: 'vim_yank_to_end_of_line', payload: { count } });
  }, []);

  const vimPasteAfter = useCallback((count: number): void => {
    dispatch({ type: 'vim_paste_after', payload: { count } });
  }, []);

  const vimPasteBefore = useCallback((count: number): void => {
    dispatch({ type: 'vim_paste_before', payload: { count } });
  }, []);

  const openInExternalEditor = useCallback(async (): Promise<void> => {
    const tmpDir = fs.mkdtempSync(pathMod.join(os.tmpdir(), 'gemini-edit-'));
    const filePath = pathMod.join(tmpDir, 'buffer.txt');
    // Expand paste placeholders so user sees full content in editor
    const expandedText = expandPastePlaceholders(text, pastedContent);
    fs.writeFileSync(filePath, expandedText, 'utf8');

    dispatch({ type: 'create_undo_snapshot' });

    try {
      await openFileInEditor(
        filePath,
        stdin,
        setRawMode,
        getPreferredEditor?.(),
        settings.merged.general.openEditorInNewWindow,
      );

      let newText = fs.readFileSync(filePath, 'utf8');
      newText = newText.replace(/\r\n?/g, '\n');

      // Attempt to re-collapse unchanged pasted content back into placeholders
      const sortedPlaceholders = Object.entries(pastedContent).sort(
        (a, b) => b[1].length - a[1].length,
      );
      for (const [id, content] of sortedPlaceholders) {
        if (newText.includes(content)) {
          newText = newText.replace(content, id);
        }
      }

      dispatch({ type: 'set_text', payload: newText, pushToUndo: false });
    } catch (err) {
      coreEvents.emitFeedback('error', getErrorMessage(err), err);
    } finally {
      try {
        fs.unlinkSync(filePath);
      } catch {
        /* ignore */
      }
      try {
        fs.rmdirSync(tmpDir);
      } catch {
        /* ignore */
      }
    }
  }, [
    text,
    pastedContent,
    stdin,
    setRawMode,
    getPreferredEditor,
    settings.merged.general.openEditorInNewWindow,
  ]);

  const handleInput = useCallback(
    (key: Key): boolean => {
      const { sequence: input } = key;

      if (key.name === 'paste') {
        insert(input, { paste: true });
        return true;
      }
      if (keyMatchers[Command.RETURN](key)) {
        if (singleLine) {
          return false;
        }
        newline();
        return true;
      }
      if (keyMatchers[Command.NEWLINE](key)) {
        if (singleLine) {
          return false;
        }
        newline();
        return true;
      }
      if (keyMatchers[Command.MOVE_LEFT](key)) {
        if (cursorRow === 0 && cursorCol === 0) return false;
        move('left');
        return true;
      }
      if (keyMatchers[Command.MOVE_RIGHT](key)) {
        const lastLineIdx = lines.length - 1;
        if (
          cursorRow === lastLineIdx &&
          cursorCol === cpLen(lines[lastLineIdx] ?? '')
        ) {
          return false;
        }
        move('right');
        return true;
      }
      if (keyMatchers[Command.MOVE_UP](key)) {
        if (visualCursor[0] === 0) return false;
        move('up');
        return true;
      }
      if (keyMatchers[Command.MOVE_DOWN](key)) {
        if (visualCursor[0] === visualLines.length - 1) return false;
        move('down');
        return true;
      }
      if (keyMatchers[Command.MOVE_WORD_LEFT](key)) {
        move('wordLeft');
        return true;
      }
      if (keyMatchers[Command.MOVE_WORD_RIGHT](key)) {
        move('wordRight');
        return true;
      }
      if (keyMatchers[Command.HOME](key)) {
        move('home');
        return true;
      }
      if (keyMatchers[Command.END](key)) {
        move('end');
        return true;
      }
      if (keyMatchers[Command.CLEAR_INPUT](key)) {
        if (text.length > 0) {
          setText('');
          return true;
        }
        return false;
      }
      if (keyMatchers[Command.DELETE_WORD_BACKWARD](key)) {
        deleteWordLeft();
        return true;
      }
      if (keyMatchers[Command.DELETE_WORD_FORWARD](key)) {
        deleteWordRight();
        return true;
      }
      if (keyMatchers[Command.DELETE_CHAR_LEFT](key)) {
        backspace();
        return true;
      }
      if (keyMatchers[Command.DELETE_CHAR_RIGHT](key)) {
        const lastLineIdx = lines.length - 1;
        if (
          cursorRow === lastLineIdx &&
          cursorCol === cpLen(lines[lastLineIdx] ?? '')
        ) {
          return false;
        }
        del();
        return true;
      }
      if (keyMatchers[Command.UNDO](key)) {
        if (undoStack.length === 0) {
          return false;
        }
        undo();
        return true;
      }
      if (keyMatchers[Command.REDO](key)) {
        if (redoStack.length === 0) {
          return false;
        }
        redo();
        return true;
      }
      if (key.insertable) {
        insert(input, { paste: false });
        return true;
      }
      return false;
    },
    [
      newline,
      move,
      deleteWordLeft,
      deleteWordRight,
      backspace,
      del,
      insert,
      undo,
      redo,
      cursorRow,
      cursorCol,
      lines,
      singleLine,
      setText,
      text,
      visualCursor,
      visualLines,
      keyMatchers,
      undoStack.length,
      redoStack.length,
    ],
  );

  const visualScrollRow = useMemo(() => {
    const totalVisualLines = visualLines.length;
    return Math.min(
      actualScrollRowState,
      Math.max(0, totalVisualLines - viewport.height),
    );
  }, [visualLines.length, actualScrollRowState, viewport.height]);

  const renderedVisualLines = useMemo(
    () => visualLines.slice(visualScrollRow, visualScrollRow + viewport.height),
    [visualLines, visualScrollRow, viewport.height],
  );

  const replaceRange = useCallback(
    (
      startRow: number,
      startCol: number,
      endRow: number,
      endCol: number,
      text: string,
    ): void => {
      dispatch({
        type: 'replace_range',
        payload: { startRow, startCol, endRow, endCol, text },
      });
    },
    [],
  );

  const replaceRangeByOffset = useCallback(
    (startOffset: number, endOffset: number, replacementText: string): void => {
      const [startRow, startCol] = offsetToLogicalPos(text, startOffset);
      const [endRow, endCol] = offsetToLogicalPos(text, endOffset);
      replaceRange(startRow, startCol, endRow, endCol, replacementText);
    },
    [text, replaceRange],
  );

  const moveToOffset = useCallback((offset: number): void => {
    dispatch({ type: 'move_to_offset', payload: { offset } });
  }, []);

  const moveToVisualPosition = useCallback(
    (visRow: number, visCol: number): void => {
      const {
        visualLines,
        visualToLogicalMap,
        transformedToLogicalMaps,
        visualToTransformedMap,
      } = visualLayout;
      // Clamp visRow to valid range
      const clampedVisRow = Math.max(
        0,
        Math.min(visRow, visualLines.length - 1),
      );
      const visualLine = visualLines[clampedVisRow] || '';

      if (visualToLogicalMap[clampedVisRow]) {
        const [logRow] = visualToLogicalMap[clampedVisRow];
        const transformedToLogicalMap =
          transformedToLogicalMaps?.[logRow] ?? [];

        // Where does this visual line begin within the transformed line?
        const startColInTransformed =
          visualToTransformedMap?.[clampedVisRow] ?? 0;

        // Handle wide characters: convert visual X position to character offset
        const codePoints = toCodePoints(visualLine);
        let currentVisX = 0;
        let charOffset = 0;

        for (const char of codePoints) {
          const charWidth = getCachedStringWidth(char);
          // If the click is within this character
          if (visCol < currentVisX + charWidth) {
            // Check if we clicked the second half of a wide character
            if (charWidth > 1 && visCol >= currentVisX + charWidth / 2) {
              charOffset++;
            }
            break;
          }
          currentVisX += charWidth;
          charOffset++;
        }

        // Clamp charOffset to length
        charOffset = Math.min(charOffset, codePoints.length);

        // Map character offset through transformations to get logical position
        const transformedCol = Math.min(
          startColInTransformed + charOffset,
          Math.max(0, transformedToLogicalMap.length - 1),
        );

        const newCursorRow = logRow;
        const newCursorCol =
          transformedToLogicalMap[transformedCol] ?? cpLen(lines[logRow] ?? '');

        dispatch({
          type: 'set_cursor',
          payload: {
            cursorRow: newCursorRow,
            cursorCol: newCursorCol,
            preferredCol: charOffset,
          },
        });
      }
    },
    [visualLayout, lines],
  );

  const getLogicalPositionFromVisual = useCallback(
    (visRow: number, visCol: number): { row: number; col: number } | null => {
      const {
        visualLines,
        visualToLogicalMap,
        transformedToLogicalMaps,
        visualToTransformedMap,
      } = visualLayout;

      // Clamp visRow to valid range
      const clampedVisRow = Math.max(
        0,
        Math.min(visRow, visualLines.length - 1),
      );
      const visualLine = visualLines[clampedVisRow] || '';

      if (!visualToLogicalMap[clampedVisRow]) {
        return null;
      }

      const [logRow] = visualToLogicalMap[clampedVisRow];
      const transformedToLogicalMap = transformedToLogicalMaps?.[logRow] ?? [];

      // Where does this visual line begin within the transformed line?
      const startColInTransformed =
        visualToTransformedMap?.[clampedVisRow] ?? 0;

      // Handle wide characters: convert visual X position to character offset
      const codePoints = toCodePoints(visualLine);
      let currentVisX = 0;
      let charOffset = 0;

      for (const char of codePoints) {
        const charWidth = getCachedStringWidth(char);
        if (visCol < currentVisX + charWidth) {
          if (charWidth > 1 && visCol >= currentVisX + charWidth / 2) {
            charOffset++;
          }
          break;
        }
        currentVisX += charWidth;
        charOffset++;
      }

      charOffset = Math.min(charOffset, codePoints.length);

      const transformedCol = Math.min(
        startColInTransformed + charOffset,
        Math.max(0, transformedToLogicalMap.length - 1),
      );

      const row = logRow;
      const col =
        transformedToLogicalMap[transformedCol] ?? cpLen(lines[logRow] ?? '');

      return { row, col };
    },
    [visualLayout, lines],
  );

  const getOffset = useCallback(
    (): number => logicalPosToOffset(lines, cursorRow, cursorCol),
    [lines, cursorRow, cursorCol],
  );

  const togglePasteExpansion = useCallback(
    (id: string, row: number, col: number): void => {
      dispatch({ type: 'toggle_paste_expansion', payload: { id, row, col } });
    },
    [],
  );

  const getExpandedPasteAtLineCallback = useCallback(
    (lineIndex: number): string | null =>
      getExpandedPasteAtLine(lineIndex, expandedPaste),
    [expandedPaste],
  );

  const returnValue: TextBuffer = useMemo(
    () => ({
      lines,
      text,
      cursor: [cursorRow, cursorCol],
      preferredCol,
      selectionAnchor,
      pastedContent,

      allVisualLines: visualLines,
      viewportVisualLines: renderedVisualLines,
      visualCursor,
      visualScrollRow,
      viewportHeight: viewport.height,
      visualToLogicalMap,
      transformedToLogicalMaps,
      visualToTransformedMap,
      transformationsByLine,
      visualLayout,
      setText,
      insert,
      newline,
      backspace,
      del,
      move,
      undo,
      redo,
      replaceRange,
      replaceRangeByOffset,
      moveToOffset,
      getOffset,
      moveToVisualPosition,
      getLogicalPositionFromVisual,
      getExpandedPasteAtLine: getExpandedPasteAtLineCallback,
      togglePasteExpansion,
      expandedPaste,
      deleteWordLeft,
      deleteWordRight,

      killLineRight,
      killLineLeft,
      handleInput,
      openInExternalEditor,
      // Vim-specific operations
      vimDeleteWordForward,
      vimDeleteWordBackward,
      vimDeleteWordEnd,
      vimDeleteBigWordForward,
      vimDeleteBigWordBackward,
      vimDeleteBigWordEnd,
      vimChangeWordForward,
      vimChangeWordBackward,
      vimChangeWordEnd,
      vimChangeBigWordForward,
      vimChangeBigWordBackward,
      vimChangeBigWordEnd,
      vimDeleteLine,
      vimChangeLine,
      vimDeleteToEndOfLine,
      vimDeleteToStartOfLine,
      vimChangeToEndOfLine,
      vimDeleteToFirstNonWhitespace,
      vimChangeToStartOfLine,
      vimChangeToFirstNonWhitespace,
      vimDeleteToFirstLine,
      vimDeleteToLastLine,
      vimChangeMovement,
      vimMoveLeft,
      vimMoveRight,
      vimMoveUp,
      vimMoveDown,
      vimMoveWordForward,
      vimMoveWordBackward,
      vimMoveWordEnd,
      vimMoveBigWordForward,
      vimMoveBigWordBackward,
      vimMoveBigWordEnd,
      vimDeleteChar,
      vimDeleteCharBefore,
      vimToggleCase,
      vimReplaceChar,
      vimFindCharForward,
      vimFindCharBackward,
      vimDeleteToCharForward,
      vimDeleteToCharBackward,
      vimInsertAtCursor,
      vimAppendAtCursor,
      vimOpenLineBelow,
      vimOpenLineAbove,
      vimAppendAtLineEnd,
      vimInsertAtLineStart,
      vimMoveToLineStart,
      vimMoveToLineEnd,
      vimMoveToFirstNonWhitespace,
      vimMoveToFirstLine,
      vimMoveToLastLine,
      vimMoveToLine,
      vimEscapeInsertMode,
      vimYankLine,
      vimYankWordForward,
      vimYankBigWordForward,
      vimYankWordEnd,
      vimYankBigWordEnd,
      vimYankToEndOfLine,
      vimPasteAfter,
      vimPasteBefore,
    }),
    [
      lines,
      text,
      cursorRow,
      cursorCol,
      preferredCol,
      selectionAnchor,
      pastedContent,
      visualLines,
      renderedVisualLines,
      visualCursor,
      visualScrollRow,
      viewport.height,
      visualToLogicalMap,
      transformedToLogicalMaps,
      visualToTransformedMap,
      transformationsByLine,
      visualLayout,
      setText,
      insert,
      newline,
      backspace,
      del,
      move,
      undo,
      redo,
      replaceRange,
      replaceRangeByOffset,
      moveToOffset,
      getOffset,
      moveToVisualPosition,
      getLogicalPositionFromVisual,
      getExpandedPasteAtLineCallback,
      togglePasteExpansion,
      expandedPaste,
      deleteWordLeft,
      deleteWordRight,
      killLineRight,
      killLineLeft,
      handleInput,
      openInExternalEditor,
      vimDeleteWordForward,
      vimDeleteWordBackward,
      vimDeleteWordEnd,
      vimDeleteBigWordForward,
      vimDeleteBigWordBackward,
      vimDeleteBigWordEnd,
      vimChangeWordForward,
      vimChangeWordBackward,
      vimChangeWordEnd,
      vimChangeBigWordForward,
      vimChangeBigWordBackward,
      vimChangeBigWordEnd,
      vimDeleteLine,
      vimChangeLine,
      vimDeleteToEndOfLine,
      vimDeleteToStartOfLine,
      vimChangeToEndOfLine,
      vimDeleteToFirstNonWhitespace,
      vimChangeToStartOfLine,
      vimChangeToFirstNonWhitespace,
      vimDeleteToFirstLine,
      vimDeleteToLastLine,
      vimChangeMovement,
      vimMoveLeft,
      vimMoveRight,
      vimMoveUp,
      vimMoveDown,
      vimMoveWordForward,
      vimMoveWordBackward,
      vimMoveWordEnd,
      vimMoveBigWordForward,
      vimMoveBigWordBackward,
      vimMoveBigWordEnd,
      vimDeleteChar,
      vimDeleteCharBefore,
      vimToggleCase,
      vimReplaceChar,
      vimFindCharForward,
      vimFindCharBackward,
      vimDeleteToCharForward,
      vimDeleteToCharBackward,
      vimInsertAtCursor,
      vimAppendAtCursor,
      vimOpenLineBelow,
      vimOpenLineAbove,
      vimAppendAtLineEnd,
      vimInsertAtLineStart,
      vimMoveToLineStart,
      vimMoveToLineEnd,
      vimMoveToFirstNonWhitespace,
      vimMoveToFirstLine,
      vimMoveToLastLine,
      vimMoveToLine,
      vimEscapeInsertMode,
      vimYankLine,
      vimYankWordForward,
      vimYankBigWordForward,
      vimYankWordEnd,
      vimYankBigWordEnd,
      vimYankToEndOfLine,
      vimPasteAfter,
      vimPasteBefore,
    ],
  );
  return returnValue;
}

export interface TextBuffer {
  // State
  lines: string[]; // Logical lines
  text: string;
  cursor: [number, number]; // Logical cursor [row, col]
  /**
   * When the user moves the caret vertically we try to keep their original
   * horizontal column even when passing through shorter lines.  We remember
   * that *preferred* column in this field while the user is still travelling
   * vertically.  Any explicit horizontal movement resets the preference.
   */
  preferredCol: number | null; // Preferred visual column
  selectionAnchor: [number, number] | null; // Logical selection anchor
  pastedContent: Record<string, string>;

  // Visual state (handles wrapping)
  allVisualLines: string[]; // All visual lines for the current text and viewport width.
  viewportVisualLines: string[]; // The subset of visual lines to be rendered based on visualScrollRow and viewport.height
  visualCursor: [number, number]; // Visual cursor [row, col] relative to the start of all visualLines
  visualScrollRow: number; // Scroll position for visual lines (index of the first visible visual line)
  viewportHeight: number; // The maximum height of the viewport
  /**
   * For each visual line (by absolute index in allVisualLines) provides a tuple
   * [logicalLineIndex, startColInLogical] that maps where that visual line
   * begins within the logical buffer. Indices are code-point based.
   */
  visualToLogicalMap: Array<[number, number]>;
  /**
   * For each logical line, an array mapping transformed positions (in the transformed
   * line) back to logical column indices.
   */
  transformedToLogicalMaps: number[][];
  /**
   * For each visual line (absolute index across all visual lines), the start index
   * within that logical line's transformed content.
   */
  visualToTransformedMap: number[];
  /** Cached transformations per logical line */
  transformationsByLine: Transformation[][];
  visualLayout: VisualLayout;

  // Actions

  /**
   * Replaces the entire buffer content with the provided text.
   * The operation is undoable.
   */
  setText: (text: string, cursorPosition?: 'start' | 'end' | number) => void;
  /**
   * Insert a single character or string without newlines.
   */
  insert: (ch: string, opts?: { paste?: boolean }) => void;
  newline: () => void;
  backspace: () => void;
  del: () => void;
  move: (dir: Direction) => void;
  undo: () => void;
  redo: () => void;
  /**
   * Replaces the text within the specified range with new text.
   * Handles both single-line and multi-line ranges.
   *
   * @param startRow The starting row index (inclusive).
   * @param startCol The starting column index (inclusive, code-point based).
   * @param endRow The ending row index (inclusive).
   * @param endCol The ending column index (exclusive, code-point based).
   * @param text The new text to insert.
   * @returns True if the buffer was modified, false otherwise.
   */
  replaceRange: (
    startRow: number,
    startCol: number,
    endRow: number,
    endCol: number,
    text: string,
  ) => void;
  /**
   * Delete the word to the *left* of the caret, mirroring common
   * Ctrl/Alt+Backspace behaviour in editors & terminals. Both the adjacent
   * whitespace *and* the word characters immediately preceding the caret are
   * removed.  If the caret is already at column‑0 this becomes a no-op.
   */
  deleteWordLeft: () => void;
  /**
   * Delete the word to the *right* of the caret, akin to many editors'
   * Ctrl/Alt+Delete shortcut.  Removes any whitespace/punctuation that
   * follows the caret and the next contiguous run of word characters.
   */
  deleteWordRight: () => void;

  /**
   * Deletes text from the cursor to the end of the current line.
   */
  killLineRight: () => void;
  /**
   * Deletes text from the start of the current line to the cursor.
   */
  killLineLeft: () => void;
  /**
   * High level "handleInput" – receives what Ink gives us.
   */
  handleInput: (key: Key) => boolean;
  /**
   * Opens the current buffer contents in the user's preferred terminal text
   * editor ($VISUAL or $EDITOR, falling back to "vi").  The method blocks
   * until the editor exits, then reloads the file and replaces the in‑memory
   * buffer with whatever the user saved.
   *
   * The operation is treated as a single undoable edit – we snapshot the
   * previous state *once* before launching the editor so one `undo()` will
   * revert the entire change set.
   *
   * Note: We purposefully rely on the *synchronous* spawn API so that the
   * calling process genuinely waits for the editor to close before
   * continuing.  This mirrors Git's behaviour and simplifies downstream
   * control‑flow (callers can simply `await` the Promise).
   */
  openInExternalEditor: () => Promise<void>;

  replaceRangeByOffset: (
    startOffset: number,
    endOffset: number,
    replacementText: string,
  ) => void;
  getOffset: () => number;
  moveToOffset(offset: number): void;
  moveToVisualPosition(visualRow: number, visualCol: number): void;
  /**
   * Convert visual coordinates to logical position without moving cursor.
   * Returns null if the position is out of bounds.
   */
  getLogicalPositionFromVisual(
    visualRow: number,
    visualCol: number,
  ): { row: number; col: number } | null;
  /**
   * Check if a line index falls within an expanded paste region.
   * Returns the paste placeholder ID if found, null otherwise.
   */
  getExpandedPasteAtLine(lineIndex: number): string | null;
  /**
   * Toggle expansion state for a paste placeholder.
   * If collapsed, expands to show full content inline.
   * If expanded, collapses back to placeholder.
   */
  togglePasteExpansion(id: string, row: number, col: number): void;
  /**
   * The current expanded paste info (read-only).
   */
  expandedPaste: ExpandedPasteInfo | null;

  // Vim-specific operations
  /**
   * Delete N words forward from cursor position (vim 'dw' command)
   */
  vimDeleteWordForward: (count: number) => void;
  /**
   * Delete N words backward from cursor position (vim 'db' command)
   */
  vimDeleteWordBackward: (count: number) => void;
  /**
   * Delete to end of N words from cursor position (vim 'de' command)
   */
  vimDeleteWordEnd: (count: number) => void;
  /**
   * Delete N big words forward from cursor position (vim 'dW' command)
   */
  vimDeleteBigWordForward: (count: number) => void;
  /**
   * Delete N big words backward from cursor position (vim 'dB' command)
   */
  vimDeleteBigWordBackward: (count: number) => void;
  /**
   * Delete to end of N big words from cursor position (vim 'dE' command)
   */
  vimDeleteBigWordEnd: (count: number) => void;
  /**
   * Change N words forward from cursor position (vim 'cw' command)
   */
  vimChangeWordForward: (count: number) => void;
  /**
   * Change N words backward from cursor position (vim 'cb' command)
   */
  vimChangeWordBackward: (count: number) => void;
  /**
   * Change to end of N words from cursor position (vim 'ce' command)
   */
  vimChangeWordEnd: (count: number) => void;
  /**
   * Change N big words forward from cursor position (vim 'cW' command)
   */
  vimChangeBigWordForward: (count: number) => void;
  /**
   * Change N big words backward from cursor position (vim 'cB' command)
   */
  vimChangeBigWordBackward: (count: number) => void;
  /**
   * Change to end of N big words from cursor position (vim 'cE' command)
   */
  vimChangeBigWordEnd: (count: number) => void;
  /**
   * Delete N lines from cursor position (vim 'dd' command)
   */
  vimDeleteLine: (count: number) => void;
  /**
   * Change N lines from cursor position (vim 'cc' command)
   */
  vimChangeLine: (count: number) => void;
  /**
   * Delete from cursor to end of line (vim 'D' command)
   * With count > 1, deletes to end of current line plus (count-1) additional lines
   */
  vimDeleteToEndOfLine: (count?: number) => void;
  /**
   * Delete from start of line to cursor (vim 'd0' command)
   */
  vimDeleteToStartOfLine: () => void;
  /**
   * Change from cursor to end of line (vim 'C' command)
   * With count > 1, changes to end of current line plus (count-1) additional lines
   */
  vimChangeToEndOfLine: (count?: number) => void;
  /**
   * Delete from cursor to first non-whitespace character (vim 'd^' command)
   */
  vimDeleteToFirstNonWhitespace: () => void;
  /**
   * Change from cursor to start of line (vim 'c0' command)
   */
  vimChangeToStartOfLine: () => void;
  /**
   * Change from cursor to first non-whitespace character (vim 'c^' command)
   */
  vimChangeToFirstNonWhitespace: () => void;
  /**
   * Delete from current line to first line (vim 'dgg' command)
   */
  vimDeleteToFirstLine: (count: number) => void;
  /**
   * Delete from current line to last line (vim 'dG' command)
   */
  vimDeleteToLastLine: (count: number) => void;
  /**
   * Change movement operations (vim 'ch', 'cj', 'ck', 'cl' commands)
   */
  vimChangeMovement: (movement: 'h' | 'j' | 'k' | 'l', count: number) => void;
  /**
   * Move cursor left N times (vim 'h' command)
   */
  vimMoveLeft: (count: number) => void;
  /**
   * Move cursor right N times (vim 'l' command)
   */
  vimMoveRight: (count: number) => void;
  /**
   * Move cursor up N times (vim 'k' command)
   */
  vimMoveUp: (count: number) => void;
  /**
   * Move cursor down N times (vim 'j' command)
   */
  vimMoveDown: (count: number) => void;
  /**
   * Move cursor forward N words (vim 'w' command)
   */
  vimMoveWordForward: (count: number) => void;
  /**
   * Move cursor backward N words (vim 'b' command)
   */
  vimMoveWordBackward: (count: number) => void;
  /**
   * Move cursor to end of Nth word (vim 'e' command)
   */
  vimMoveWordEnd: (count: number) => void;
  /**
   * Move cursor forward N big words (vim 'W' command)
   */
  vimMoveBigWordForward: (count: number) => void;
  /**
   * Move cursor backward N big words (vim 'B' command)
   */
  vimMoveBigWordBackward: (count: number) => void;
  /**
   * Move cursor to end of Nth big word (vim 'E' command)
   */
  vimMoveBigWordEnd: (count: number) => void;
  /**
   * Delete N characters at cursor (vim 'x' command)
   */
  vimDeleteChar: (count: number) => void;
  /** Delete N characters before cursor (vim 'X') */
  vimDeleteCharBefore: (count: number) => void;
  /** Toggle case of N characters at cursor (vim '~') */
  vimToggleCase: (count: number) => void;
  /** Replace N characters at cursor with char, stay in NORMAL mode (vim 'r') */
  vimReplaceChar: (char: string, count: number) => void;
  /** Move to Nth occurrence of char forward on line; till=true stops before it (vim 'f'/'t') */
  vimFindCharForward: (char: string, count: number, till: boolean) => void;
  /** Move to Nth occurrence of char backward on line; till=true stops after it (vim 'F'/'T') */
  vimFindCharBackward: (char: string, count: number, till: boolean) => void;
  /** Delete from cursor to Nth occurrence of char forward; till=true excludes the char (vim 'df'/'dt') */
  vimDeleteToCharForward: (char: string, count: number, till: boolean) => void;
  /** Delete from Nth occurrence of char backward to cursor; till=true excludes the char (vim 'dF'/'dT') */
  vimDeleteToCharBackward: (char: string, count: number, till: boolean) => void;
  /**
   * Enter insert mode at cursor (vim 'i' command)
   */
  vimInsertAtCursor: () => void;
  /**
   * Enter insert mode after cursor (vim 'a' command)
   */
  vimAppendAtCursor: () => void;
  /**
   * Open new line below and enter insert mode (vim 'o' command)
   */
  vimOpenLineBelow: () => void;
  /**
   * Open new line above and enter insert mode (vim 'O' command)
   */
  vimOpenLineAbove: () => void;
  /**
   * Move to end of line and enter insert mode (vim 'A' command)
   */
  vimAppendAtLineEnd: () => void;
  /**
   * Move to first non-whitespace and enter insert mode (vim 'I' command)
   */
  vimInsertAtLineStart: () => void;
  /**
   * Move cursor to beginning of line (vim '0' command)
   */
  vimMoveToLineStart: () => void;
  /**
   * Move cursor to end of line (vim '$' command)
   */
  vimMoveToLineEnd: () => void;
  /**
   * Move cursor to first non-whitespace character (vim '^' command)
   */
  vimMoveToFirstNonWhitespace: () => void;
  /**
   * Move cursor to first line (vim 'gg' command)
   */
  vimMoveToFirstLine: () => void;
  /**
   * Move cursor to last line (vim 'G' command)
   */
  vimMoveToLastLine: () => void;
  /**
   * Move cursor to specific line number (vim '[N]G' command)
   */
  vimMoveToLine: (lineNumber: number) => void;
  /**
   * Handle escape from insert mode (moves cursor left if not at line start)
   */
  vimEscapeInsertMode: () => void;
  /** Yank N lines into the unnamed register (vim 'yy' / 'Nyy') */
  vimYankLine: (count: number) => void;
  /** Yank forward N words into the unnamed register (vim 'yw') */
  vimYankWordForward: (count: number) => void;
  /** Yank forward N big words into the unnamed register (vim 'yW') */
  vimYankBigWordForward: (count: number) => void;
  /** Yank to end of N words into the unnamed register (vim 'ye') */
  vimYankWordEnd: (count: number) => void;
  /** Yank to end of N big words into the unnamed register (vim 'yE') */
  vimYankBigWordEnd: (count: number) => void;
  /** Yank from cursor to end of line into the unnamed register (vim 'y$') */
  vimYankToEndOfLine: (count: number) => void;
  /** Paste the unnamed register after cursor (vim 'p') */
  vimPasteAfter: (count: number) => void;
  /** Paste the unnamed register before cursor (vim 'P') */
  vimPasteBefore: (count: number) => void;
}