fresh-editor 0.1.86

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
//! E2E tests for git features (git grep and git find file)

use crate::common::git_test_helper::{DirGuard, GitTestRepo};
use crate::common::harness::EditorTestHarness;
use crate::common::tracing::init_tracing_from_env;
use crossterm::event::{KeyCode, KeyModifiers};
use fresh::config::Config;

/// Check if screen contains a path with either forward or backslash separator
fn contains_src_path(s: &str) -> bool {
    s.contains("src/") || s.contains("src\\")
}

/// Helper to trigger git grep via command palette
fn trigger_git_grep(harness: &mut EditorTestHarness) {
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_prompt().unwrap();
    harness.type_text("Git Grep").unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
}

/// Helper to trigger git find file via command palette
fn trigger_git_find_file(harness: &mut EditorTestHarness) {
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.wait_for_prompt().unwrap();
    harness.type_text("Git Find File").unwrap();
    // Wait for the command to appear in the palette
    harness.wait_for_screen_contains("Git Find File").unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    // Wait for the find file prompt to appear
    harness.wait_for_screen_contains("Find file:").unwrap();
}

/// Test git grep basic functionality - visibility of results
#[test]
fn test_git_grep_shows_results() {
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_plugins();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git grep
    trigger_git_grep(&mut harness);

    // Check that the prompt appeared
    harness.assert_screen_contains("Git grep: ");

    // Type search query
    harness.type_text("config").unwrap();

    // Wait for git grep to complete by checking for results in the suggestions box
    // The plugin populates suggestions with file:line:column format
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            // Wait for suggestions to appear - they show as "filename:line:column: content"
            // The suggestion box appears above the prompt
            screen.contains(".yml:") || screen.contains(".md:") || screen.contains(".rs:")
        })
        .unwrap();

    // Verify results are visible
    let screen = harness.screen_to_string();
    println!("Git grep screen:\n{screen}");

    // Should show at least one match
    assert!(
        contains_src_path(&screen) || screen.contains("Config") || screen.contains("config"),
        "Should show grep results"
    );
}

/// Test git grep interactive updates - results update as user types
#[test]
fn test_git_grep_interactive_updates() {
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_plugins();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git grep
    trigger_git_grep(&mut harness);

    // Type first query
    harness.type_text("Config").unwrap();

    // Wait for initial results
    harness
        .wait_until(|h| contains_src_path(&h.screen_to_string()))
        .unwrap();

    let screen_config = harness.screen_to_string();

    // Backspace to clear and type different query
    for _ in 0..6 {
        harness
            .send_key(KeyCode::Backspace, KeyModifiers::NONE)
            .unwrap();
        harness.sleep(std::time::Duration::from_millis(10));
    }
    harness.render().unwrap();

    harness.type_text("println").unwrap();

    // Wait for new results
    harness
        .wait_until(|h| {
            let s = h.screen_to_string();
            s.contains("println") || s.contains("main.rs")
        })
        .unwrap();

    let screen_println = harness.screen_to_string();

    // Results should have changed
    println!("After 'Config' query:\n{screen_config}");
    println!("After 'println' query:\n{screen_println}");

    // Both searches should show some results
    assert!(
        screen_config.contains("Config") || contains_src_path(&screen_config),
        "Config search should show results"
    );
}

/// Test git grep selection and navigation
#[test]
fn test_git_grep_selection_navigation() {
    // Initialize tracing and signal handlers for debugging
    init_tracing_from_env();
    fresh::services::signal_handler::install_signal_handlers();

    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_plugins();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git grep
    trigger_git_grep(&mut harness);

    // Search for something that appears multiple times
    harness.type_text("config").unwrap();

    // Wait for results
    harness
        .wait_until(|h| contains_src_path(&h.screen_to_string()))
        .unwrap();

    // Navigate down through suggestions
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.process_async_and_render().unwrap();

    let screen_after_down = harness.screen_to_string();

    // Navigate up
    harness.send_key(KeyCode::Up, KeyModifiers::NONE).unwrap();
    harness.process_async_and_render().unwrap();

    let screen_after_up = harness.screen_to_string();

    println!("After down:\n{screen_after_down}");
    println!("After up:\n{screen_after_up}");

    // The screens should show the prompt is still active
    assert!(screen_after_down.contains("Git grep:"));
    assert!(screen_after_up.contains("Git grep:"));
}

/// Test git grep confirm - jump to match location
#[test]
fn test_git_grep_confirm_jumps_to_location() {
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_plugins();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git grep
    trigger_git_grep(&mut harness);

    // Search for specific text
    harness.type_text("Hello, world").unwrap();

    // Wait for results
    harness
        .wait_until(|h| h.screen_to_string().contains("main.rs"))
        .unwrap();

    // Confirm selection (Enter) - this should open file and jump to line
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Give it time to open the file
    harness.sleep(std::time::Duration::from_millis(200));
    harness.render().unwrap();

    let screen = harness.screen_to_string();
    println!("After confirming grep result:\n{screen}");

    // The file should have opened and we should be out of prompt mode
    // Note: The file might not show content if paths are relative and directory changed,
    // but at minimum the prompt should be gone
    harness.assert_screen_not_contains("Git grep:");

    // The screen should show either the file content OR at least not be in prompt mode
    // In a real scenario with proper path handling, this would show file content
    let has_file_content = screen.contains("Hello, world")
        || screen.contains("fn main")
        || screen.contains("println")
        || screen.contains("main.rs");

    if !has_file_content {
        // If file didn't open (due to relative path issues in test environment),
        // at least verify we exited the prompt successfully
        println!(
            "Note: File content not visible (likely due to relative path in test environment)"
        );
    }
}

/// Test git grep cancel
#[test]
fn test_git_grep_cancel() {
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_plugins();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git grep
    trigger_git_grep(&mut harness);

    harness.assert_screen_contains("Git grep: ");

    // Type something
    harness.type_text("config").unwrap();

    // Cancel with Escape
    harness.send_key(KeyCode::Esc, KeyModifiers::NONE).unwrap();
    harness.render().unwrap();

    // Prompt should be gone
    harness.assert_screen_not_contains("Git grep: ");
}

/// Test git find file basic functionality
#[test]
fn test_git_find_file_shows_results() {
    init_tracing_from_env();
    fresh::services::signal_handler::install_signal_handlers();
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_plugins();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git find file
    trigger_git_find_file(&mut harness);

    // Wait for async git ls-files to complete and the file picker to appear
    // The plugin loads files asynchronously, so we need to wait for both
    // the prompt "Find file: " and some file results to appear
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            // Wait for both the prompt and file content
            screen.contains("Find file:")
                && (contains_src_path(&screen)
                    || screen.contains(".rs")
                    || screen.contains("Cargo.toml"))
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("Git find file screen:\n{screen}");

    // Should show files from the project
    assert!(
        screen.contains(".rs") || screen.contains("Cargo") || screen.contains("README"),
        "Should show project files"
    );
}

/// Test git find file interactive filtering
#[test]
fn test_git_find_file_interactive_filtering() {
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_plugins();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git find file
    trigger_git_find_file(&mut harness);

    // Wait for initial results
    harness
        .wait_until(|h| contains_src_path(&h.screen_to_string()))
        .unwrap();

    // Type filter to narrow down results
    harness.type_text("main").unwrap();

    // Wait for filtered results
    harness
        .wait_until(|h| h.screen_to_string().contains("main"))
        .unwrap();

    let screen_main = harness.screen_to_string();
    println!("After filtering 'main':\n{screen_main}");

    // Should show main.rs in results
    assert!(
        screen_main.contains("main.rs") || screen_main.contains("main"),
        "Should filter to show main.rs"
    );

    // Change filter
    for _ in 0..4 {
        harness
            .send_key(KeyCode::Backspace, KeyModifiers::NONE)
            .unwrap();
        harness.sleep(std::time::Duration::from_millis(10));
    }
    harness.type_text("lib").unwrap();

    // Wait for new filtered results
    harness
        .wait_until(|h| h.screen_to_string().contains("lib"))
        .unwrap();

    let screen_lib = harness.screen_to_string();
    println!("After filtering 'lib':\n{screen_lib}");

    // Should show lib.rs
    assert!(
        screen_lib.contains("lib.rs") || screen_lib.contains("lib"),
        "Should filter to show lib.rs"
    );
}

/// Test git find file selection and navigation
#[test]
fn test_git_find_file_selection_navigation() {
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_plugins();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git find file
    trigger_git_find_file(&mut harness);

    // Wait for results
    harness
        .wait_until(|h| contains_src_path(&h.screen_to_string()))
        .unwrap();

    // Navigate down
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.process_async_and_render().unwrap();

    // Navigate down again
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.process_async_and_render().unwrap();

    // Navigate up
    harness.send_key(KeyCode::Up, KeyModifiers::NONE).unwrap();
    harness.process_async_and_render().unwrap();

    let screen = harness.screen_to_string();
    println!("After navigation:\n{screen}");

    // Prompt should still be active
    assert!(screen.contains("Find file:"));
}

/// Test git find file confirm - opens selected file
#[test]
#[cfg_attr(windows, ignore)] // Git plugin tests timeout on Windows CI
fn test_git_find_file_confirm_opens_file() {
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_plugins();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git find file
    trigger_git_find_file(&mut harness);

    // Filter to main.rs
    harness.type_text("main.rs").unwrap();

    // Wait for results
    harness
        .wait_until(|h| h.screen_to_string().contains("main.rs"))
        .unwrap();

    // Confirm selection - should open the file
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Wait for file to actually load (async operation)
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            // Wait for prompt to close (file opened)
            !screen.contains("Find file:")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("After confirming file:\n{screen}");

    // The file should have opened and we should be out of prompt mode
    harness.assert_screen_not_contains("Find file:");

    // Check if file content is visible
    let has_file_content =
        screen.contains("fn main()") || screen.contains("println") || screen.contains("Hello");

    if !has_file_content {
        println!(
            "Note: File content not visible (likely due to relative path in test environment)"
        );
    }
}

/// Test git features with many results - scrolling behavior
#[test]
fn test_git_grep_scrolling_many_results() {
    let repo = GitTestRepo::new();

    // Create many files with searchable content
    repo.setup_many_files(50);
    repo.setup_git_plugins();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git grep
    trigger_git_grep(&mut harness);

    // Search for "Searchable" which appears in all files
    harness.type_text("Searchable").unwrap();

    // Wait for results (should be truncated to 100 max)
    harness
        .wait_until(|h| h.screen_to_string().contains("file"))
        .unwrap();

    // Navigate down multiple times to test scrolling
    for _ in 0..10 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness.process_async_and_render().unwrap();
        harness.sleep(std::time::Duration::from_millis(20));
    }

    let screen = harness.screen_to_string();
    println!("After scrolling down:\n{screen}");

    // Should still show the prompt and results
    assert!(screen.contains("Git grep:"));
    assert!(screen.contains("file") || screen.contains("Searchable"));
}

/// Test git find file with many files - scrolling behavior
#[test]
fn test_git_find_file_scrolling_many_files() {
    let repo = GitTestRepo::new();
    repo.setup_many_files(50);
    repo.setup_git_plugins();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git find file
    trigger_git_find_file(&mut harness);

    // Wait for file list
    harness
        .wait_until(|h| h.screen_to_string().contains("file"))
        .unwrap();

    // Navigate down multiple times
    for _ in 0..15 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness.process_async_and_render().unwrap();
        harness.sleep(std::time::Duration::from_millis(20));
    }

    // Navigate up
    for _ in 0..5 {
        harness.send_key(KeyCode::Up, KeyModifiers::NONE).unwrap();
        harness.process_async_and_render().unwrap();
        harness.sleep(std::time::Duration::from_millis(20));
    }

    let screen = harness.screen_to_string();
    println!("After scrolling:\n{screen}");

    // Should still show the prompt
    assert!(screen.contains("Find file:"));
}

/// Test that git commands work from command palette
#[test]
fn test_git_commands_via_command_palette() {
    init_tracing_from_env();
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_plugins();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Test that we can invoke git commands via command palette
    // Open command palette with Ctrl+P
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();

    harness.assert_screen_contains("Command: ");

    // Type to filter to git commands (note: no colon in command name)
    harness.type_text("Git Grep").unwrap();
    harness.render().unwrap();

    // Confirm
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for git grep mode to appear (async plugin loading)
    harness
        .wait_until(|h| h.screen_to_string().contains("Git grep:"))
        .unwrap();
}

/// REPRODUCTION TEST: Git grep selection should open file and jump to exact line
#[test]
fn test_git_grep_opens_correct_file_and_jumps_to_line() {
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_plugins();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Verify we start with an empty buffer
    let initial_content = harness.get_buffer_content().unwrap();
    assert!(
        initial_content.is_empty() || initial_content == "\n",
        "Should start with empty buffer"
    );

    // Trigger git grep
    trigger_git_grep(&mut harness);

    // Search for "println" which appears in main.rs line 2
    harness.type_text("println").unwrap();

    // Wait for results
    harness
        .wait_until(|h| h.screen_to_string().contains("main.rs"))
        .unwrap();

    let screen_before = harness.screen_to_string();
    println!("Screen with results:\n{screen_before}");

    // Confirm selection (Enter)
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Wait for file to actually load (async operation)
    harness
        .wait_until(|h| {
            let content = h.get_buffer_content().unwrap();
            !content.is_empty() && content != "\n" && content.contains("println")
        })
        .unwrap();

    // CRITICAL CHECKS:

    // 1. Buffer content should have changed from empty to the file content
    let buffer_content = harness.get_buffer_content().unwrap();
    println!("Buffer content after selection:\n{buffer_content}");

    assert!(
        buffer_content.contains("println"),
        "BUG: Buffer does not contain expected file content. Expected 'println' in buffer. Buffer: {buffer_content:?}"
    );

    // 2. The cursor should be at the line with println (line 2)
    let cursor_pos = harness.cursor_position();
    println!("Cursor position: {cursor_pos}");

    // The cursor should NOT be at position 0 (start of file)
    // It should be near the "println" line
    assert!(
        cursor_pos > 0,
        "BUG: Cursor is at position 0! It should have jumped to the match line. Position: {cursor_pos}"
    );

    // 3. Verify screen shows the file content
    let screen_after = harness.screen_to_string();
    println!("Screen after selection:\n{screen_after}");

    assert!(
        screen_after.contains("fn main") || screen_after.contains("println"),
        "BUG: Screen does not show file content after selection"
    );
}

/// REPRODUCTION TEST: Git find file selection should actually open the file
#[test]
fn test_git_find_file_actually_opens_file() {
    init_tracing_from_env();
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_plugins();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Verify we start with an empty buffer
    let initial_content = harness.get_buffer_content().unwrap();
    assert!(
        initial_content.is_empty() || initial_content == "\n",
        "Should start with empty buffer"
    );

    // Trigger git find file
    trigger_git_find_file(&mut harness);

    // Wait for prompt to appear AND files to be loaded
    // This is important: we must wait for file loading to complete before typing
    // because the Finder's loadFilterItems() is async
    harness
        .wait_until(|h| {
            let s = h.screen_to_string();
            // Wait for both the prompt AND file results
            s.contains("Find file:") && contains_src_path(&s)
        })
        .unwrap();

    // Type to find lib.rs
    harness.type_text("lib.rs").unwrap();

    // Wait for filtering to complete - lib.rs should be visible and near the top
    // The fuzzy filter should prioritize "src/lib.rs" when filtering by "lib.rs"
    harness
        .wait_until(|h| {
            let s = h.screen_to_string();
            // After typing "lib.rs", the filtered results should show lib.rs
            // Check that the screen still contains lib.rs in the results
            s.contains("lib.rs") && s.contains("Find file:")
        })
        .unwrap();

    let screen_before = harness.screen_to_string();
    println!("Screen with file list:\n{screen_before}");

    // Confirm selection (Enter)
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for file to load (buffer content should change from empty)
    harness
        .wait_until(|h| {
            let content = h.get_buffer_content().unwrap_or_default();
            !content.is_empty() && content != "\n"
        })
        .unwrap();

    // CRITICAL CHECKS:

    // 1. Buffer content should have changed from empty to lib.rs content
    let buffer_content = harness.get_buffer_content().unwrap();
    println!("Buffer content after selection:\n{buffer_content}");

    assert!(
        !buffer_content.is_empty() && buffer_content != "\n",
        "BUG: Buffer is still empty! File lib.rs was not opened. Buffer: {buffer_content:?}"
    );

    assert!(
        buffer_content.contains("pub struct Config") || buffer_content.contains("impl Default"),
        "BUG: Buffer does not contain lib.rs content. Expected 'Config' or 'impl Default'. Buffer: {buffer_content:?}"
    );

    // 2. Verify screen shows the file content
    let screen_after = harness.screen_to_string();
    println!("Screen after selection:\n{screen_after}");

    assert!(
        screen_after.contains("Config") || screen_after.contains("pub struct"),
        "BUG: Screen does not show lib.rs content after selection. Screen:\n{screen_after}"
    );

    // 3. Status bar should show we're no longer in prompt mode
    harness.assert_screen_not_contains("Find file:");
}

/// REPRODUCTION TEST: Verify cursor jumps to correct line in git grep
#[test]
fn test_git_grep_cursor_position_accuracy() {
    let repo = GitTestRepo::new();

    // Create a file with known line content
    repo.create_file(
        "test.txt",
        "Line 1\nLine 2\nLine 3 with MARKER\nLine 4\nLine 5\n",
    );
    repo.git_add(&["test.txt"]);
    repo.git_commit("Add test file");
    repo.setup_git_plugins();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git grep
    trigger_git_grep(&mut harness);

    // Search for MARKER (should be on line 3)
    harness.type_text("MARKER").unwrap();

    // Wait for results
    harness
        .wait_until(|h| h.screen_to_string().contains("test.txt"))
        .unwrap();

    // Confirm selection
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();

    // Wait for file to actually load AND cursor to be positioned (both are async operations)
    // The cursor should be on line 3 (0-indexed = line 2)
    // Calculate expected byte position for line 3
    // Line 1: "Line 1\n" = 7 bytes
    // Line 2: "Line 2\n" = 7 bytes
    // Line 3 starts at byte 14
    harness
        .wait_until(|h| {
            let content = h.get_buffer_content().unwrap_or_default();
            let cursor_pos = h.cursor_position();
            // Wait for both: file content loaded AND cursor positioned at line 3
            content.contains("MARKER") && cursor_pos >= 14
        })
        .unwrap();

    // Check buffer content
    let buffer_content = harness.get_buffer_content().unwrap();
    println!("Buffer content:\n{buffer_content}");

    let cursor_pos = harness.cursor_position();
    println!("Cursor position: {cursor_pos}");

    // Verify cursor is at line 3 (byte position should be at or after byte 14)
    assert!(
        cursor_pos >= 14,
        "BUG: Cursor should be at line 3 (position >= 14), but is at position {cursor_pos}"
    );

    // Verify the line at cursor contains MARKER
    let screen = harness.screen_to_string();
    assert!(
        screen.contains("MARKER"),
        "BUG: Screen should show the line with MARKER"
    );
}

// =============================================================================
// Git Log Tests
// =============================================================================

/// Helper to trigger git log via command palette
fn trigger_git_log(harness: &mut EditorTestHarness) {
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Git Log").unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
}

/// Test git log opens and shows commits
#[test]
fn test_git_log_shows_commits() {
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_log_plugin();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git log
    trigger_git_log(&mut harness);

    // Wait for git log to load
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            // Should show "Commits:" header and at least one commit hash
            screen.contains("Commits:") && screen.contains("Initial commit")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("Git log screen:\n{screen}");

    assert!(screen.contains("Commits:"), "Should show Commits: header");
}

/// Test git log cursor navigation
#[test]
fn test_git_log_cursor_navigation() {
    let repo = GitTestRepo::new();

    // Create multiple commits for navigation testing
    repo.create_file("file1.txt", "Content 1");
    repo.git_add(&["file1.txt"]);
    repo.git_commit("First commit");

    repo.create_file("file2.txt", "Content 2");
    repo.git_add(&["file2.txt"]);
    repo.git_commit("Second commit");

    repo.create_file("file3.txt", "Content 3");
    repo.git_add(&["file3.txt"]);
    repo.git_commit("Third commit");

    repo.setup_git_log_plugin();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git log
    trigger_git_log(&mut harness);

    // Wait for git log to load
    harness
        .wait_until(|h| h.screen_to_string().contains("Commits:"))
        .unwrap();

    // Navigate down using j key (should work via inherited normal mode)
    harness
        .send_key(KeyCode::Char('j'), KeyModifiers::NONE)
        .unwrap();
    harness.process_async_and_render().unwrap();

    // Navigate down using Down arrow
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.process_async_and_render().unwrap();

    // Navigate up using k key
    harness
        .send_key(KeyCode::Char('k'), KeyModifiers::NONE)
        .unwrap();
    harness.process_async_and_render().unwrap();

    let screen = harness.screen_to_string();
    println!("After navigation:\n{screen}");

    // Git log should still be visible
    assert!(screen.contains("Commits:"));
}

/// Test git log show commit detail with Enter
#[test]
fn test_git_log_show_commit_detail() {
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_log_plugin();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git log
    trigger_git_log(&mut harness);

    // Wait for git log to load
    harness
        .wait_until(|h| h.screen_to_string().contains("Commits:"))
        .unwrap();

    // Move cursor to a commit line (down from header)
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.process_async_and_render().unwrap();

    // Press Enter to show commit detail
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for commit detail to load
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            // git show output includes "commit", "Author:", "Date:"
            screen.contains("Author:") && screen.contains("Date:")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("Commit detail screen:\n{screen}");
}

/// Test going back from commit detail to git log
#[test]
fn test_git_log_back_from_commit_detail() {
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_log_plugin();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git log
    trigger_git_log(&mut harness);

    // Wait for git log to load
    harness
        .wait_until(|h| h.screen_to_string().contains("Commits:"))
        .unwrap();

    // Move to commit and show detail
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.process_async_and_render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for commit detail
    harness
        .wait_until(|h| h.screen_to_string().contains("Author:"))
        .unwrap();

    let screen_detail = harness.screen_to_string();
    println!("Commit detail:\n{screen_detail}");

    // Press q to go back to git log
    harness
        .send_key(KeyCode::Char('q'), KeyModifiers::NONE)
        .unwrap();
    harness.process_async_and_render().unwrap();

    // Wait for git log to reappear
    harness
        .wait_until(|h| h.screen_to_string().contains("Commits:"))
        .unwrap();

    let screen_log = harness.screen_to_string();
    println!("Back to git log:\n{screen_log}");
}

/// Test closing git log with q
#[test]
fn test_git_log_close() {
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_log_plugin();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git log
    trigger_git_log(&mut harness);

    // Wait for git log to load
    harness
        .wait_until(|h| h.screen_to_string().contains("Commits:"))
        .unwrap();

    let screen_before = harness.screen_to_string();
    assert!(screen_before.contains("Commits:"));

    // Press q to close git log
    harness
        .send_key(KeyCode::Char('q'), KeyModifiers::NONE)
        .unwrap();
    harness.process_async_and_render().unwrap();

    // Git log should be closed
    harness.sleep(std::time::Duration::from_millis(100));
    harness.render().unwrap();

    let screen_after = harness.screen_to_string();
    println!("After closing:\n{screen_after}");

    // Should no longer show git log
    harness.assert_screen_not_contains("Commits:");
}

/// Test diff coloring in commit detail
#[test]
fn test_git_log_diff_coloring() {
    // Use the typical project setup which creates files and commits
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_log_plugin();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git log
    trigger_git_log(&mut harness);

    // Wait for git log to load
    harness
        .wait_until(|h| h.screen_to_string().contains("Commits:"))
        .unwrap();

    // Move to the commit and show detail
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.process_async_and_render().unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for commit detail (git show output includes Author:)
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Author:")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("Commit detail with diff:\n{screen}");

    // The commit detail should show commit info from git show output
    // Note: The exact coloring is applied via overlays which aren't visible in screen text
    assert!(
        screen.contains("Author:") || screen.contains("Date:"),
        "Should show commit info"
    );
}

/// REPRODUCTION TEST: Opening different commits after closing should open the correct commit
/// This tests the bug where after opening a commit with Enter, quitting with q, navigating
/// to a different commit and pressing Enter would open the first commit again instead of
/// the newly selected one.
#[test]
fn test_git_log_open_different_commits_sequentially() {
    let repo = GitTestRepo::new();

    // Create multiple commits with distinct, identifiable messages
    repo.create_file("file1.txt", "Content for first file");
    repo.git_add(&["file1.txt"]);
    repo.git_commit("FIRST_UNIQUE_COMMIT_AAA");

    repo.create_file("file2.txt", "Content for second file");
    repo.git_add(&["file2.txt"]);
    repo.git_commit("SECOND_UNIQUE_COMMIT_BBB");

    repo.create_file("file3.txt", "Content for third file");
    repo.git_add(&["file3.txt"]);
    repo.git_commit("THIRD_UNIQUE_COMMIT_CCC");

    repo.setup_git_log_plugin();

    // The harness sets the working directory for the editor, and the plugin
    // uses editor.getCwd() to get it for git commands - no need to change
    // process-wide CWD which would cause race conditions in parallel tests.
    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Trigger git log
    trigger_git_log(&mut harness);

    // Wait for git log to load
    harness
        .wait_until(|h| h.screen_to_string().contains("Commits:"))
        .unwrap();

    let screen_log = harness.screen_to_string();
    println!("Git log with commits:\n{screen_log}");

    // Verify all commits are visible
    assert!(
        screen_log.contains("THIRD_UNIQUE_COMMIT_CCC"),
        "Should show third commit"
    );
    assert!(
        screen_log.contains("SECOND_UNIQUE_COMMIT_BBB"),
        "Should show second commit"
    );
    assert!(
        screen_log.contains("FIRST_UNIQUE_COMMIT_AAA"),
        "Should show first commit"
    );

    // Navigate down to the first commit line (header is line 1, commits start at line 2)
    // Most recent commit (THIRD) is at the top
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.process_async_and_render().unwrap();

    // Open the first commit (THIRD_UNIQUE_COMMIT_CCC - most recent)
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for commit detail
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Author:") && screen.contains("THIRD_UNIQUE_COMMIT_CCC")
        })
        .unwrap();

    let screen_first_detail = harness.screen_to_string();
    println!("First commit detail (should be THIRD):\n{screen_first_detail}");

    // Press q to go back to git log
    harness
        .send_key(KeyCode::Char('q'), KeyModifiers::NONE)
        .unwrap();
    harness.process_async_and_render().unwrap();

    // Wait for git log to reappear
    harness
        .wait_until(|h| h.screen_to_string().contains("Commits:"))
        .unwrap();

    let screen_back_to_log = harness.screen_to_string();
    println!("Back to git log:\n{screen_back_to_log}");

    // Now navigate DOWN to a DIFFERENT commit (SECOND_UNIQUE_COMMIT_BBB)
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.process_async_and_render().unwrap();

    let screen_after_nav = harness.screen_to_string();
    println!("After navigating down:\n{screen_after_nav}");

    // Open the second commit - THIS IS THE BUG: it should open SECOND, not THIRD
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();

    // Wait for commit detail
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Author:")
        })
        .unwrap();

    let screen_second_detail = harness.screen_to_string();
    println!("Second commit detail (should be SECOND):\n{screen_second_detail}");

    // CRITICAL ASSERTION: The bug is that it opens the first commit again instead of the second
    // This should show SECOND_UNIQUE_COMMIT_BBB, NOT THIRD_UNIQUE_COMMIT_CCC
    assert!(
        screen_second_detail.contains("SECOND_UNIQUE_COMMIT_BBB"),
        "BUG: After navigating to a different commit and pressing Enter, it should open SECOND_UNIQUE_COMMIT_BBB, but got:\n{screen_second_detail}"
    );
    assert!(
        !screen_second_detail.contains("THIRD_UNIQUE_COMMIT_CCC"),
        "BUG: Should NOT show THIRD commit when SECOND was selected:\n{screen_second_detail}"
    );
}

// =============================================================================
// Git Blame Tests
// =============================================================================

/// Helper to trigger git blame via command palette
fn trigger_git_blame(harness: &mut EditorTestHarness) {
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Git Blame").unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
}

/// Test git blame opens and shows blame blocks with headers
// TODO: Fix git blame tests on Windows - they fail due to git command output differences
#[test]
#[cfg_attr(target_os = "windows", ignore)]
fn test_git_blame_shows_blocks_with_headers() {
    init_tracing_from_env();

    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_blame_plugin();

    // Change to repo directory so git commands work correctly
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Open file directly using the harness method
    let file_path = repo.path.join("src/main.rs");
    harness.open_file(&file_path).unwrap();

    // Wait until file is loaded (logical event)
    harness
        .wait_until(|h| {
            let content = h.get_buffer_content().unwrap();
            content.contains("fn main")
        })
        .unwrap();

    // Trigger git blame
    trigger_git_blame(&mut harness);

    // Wait until git blame view appears (logical event)
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            // Should show block headers with ── (commit info injected via view transform)
            screen.contains("──") && screen.contains("Initial commit")
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("Git blame screen:\n{screen}");

    assert!(screen.contains("──"), "Should show block header separator");
    assert!(
        screen.contains("Initial commit"),
        "Should show commit summary in header"
    );
}

/// Test git blame cursor navigation
// TODO: Fix git blame tests on Windows - they fail due to git command output differences
#[test]
#[cfg_attr(target_os = "windows", ignore)]
fn test_git_blame_cursor_navigation() {
    let repo = GitTestRepo::new();

    // Create a file with multiple commits to have multiple blame blocks
    repo.create_file("test.txt", "Line 1\nLine 2\n");
    repo.git_add(&["test.txt"]);
    repo.git_commit("First commit");

    repo.create_file("test.txt", "Line 1\nLine 2\nLine 3\nLine 4\n");
    repo.git_add(&["test.txt"]);
    repo.git_commit("Second commit");

    repo.setup_git_blame_plugin();

    // Change to repo directory
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Open file directly
    let file_path = repo.path.join("test.txt");
    harness.open_file(&file_path).unwrap();

    // Wait until file is loaded
    harness
        .wait_until(|h| h.get_buffer_content().unwrap().contains("Line 1"))
        .unwrap();

    // Trigger git blame
    trigger_git_blame(&mut harness);

    // Wait until blame view appears (block headers with ──)
    harness
        .wait_until(|h| h.screen_to_string().contains("──"))
        .unwrap();

    // Navigate down using j key
    harness
        .send_key(KeyCode::Char('j'), KeyModifiers::NONE)
        .unwrap();
    harness.process_async_and_render().unwrap();

    // Navigate down using Down arrow
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.process_async_and_render().unwrap();

    // Navigate up using k key
    harness
        .send_key(KeyCode::Char('k'), KeyModifiers::NONE)
        .unwrap();
    harness.process_async_and_render().unwrap();

    let screen = harness.screen_to_string();
    println!("After navigation:\n{screen}");

    // Git blame should still be visible (showing block headers)
    assert!(screen.contains("──"));
}

/// Test git blame close with q
// TODO: Fix git blame tests on Windows - they fail due to git command output differences
#[test]
#[cfg_attr(target_os = "windows", ignore)]
fn test_git_blame_close() {
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_blame_plugin();

    // Change to repo directory
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Open file directly
    let file_path = repo.path.join("src/main.rs");
    harness.open_file(&file_path).unwrap();

    // Wait until file is loaded
    harness
        .wait_until(|h| h.get_buffer_content().unwrap().contains("fn main"))
        .unwrap();

    // Trigger git blame
    trigger_git_blame(&mut harness);

    // Wait until blame view appears (block headers with ──)
    harness
        .wait_until(|h| h.screen_to_string().contains("──"))
        .unwrap();

    let screen_before = harness.screen_to_string();
    assert!(screen_before.contains("──"));

    // Press q to close git blame
    harness
        .send_key(KeyCode::Char('q'), KeyModifiers::NONE)
        .unwrap();

    // Wait until blame view is closed (back to original file without headers)
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            // Original file should be visible without blame headers
            screen.contains("fn main") && !screen.contains("──")
        })
        .unwrap();

    let screen_after = harness.screen_to_string();
    println!("After closing:\n{screen_after}");

    // Should no longer show git blame headers
    harness.assert_screen_not_contains("──");
}

/// Test git blame go back in history with 'b' key
// TODO: Fix git blame tests on Windows - they fail due to git command output differences
#[test]
#[cfg_attr(target_os = "windows", ignore)]
fn test_git_blame_go_back_in_history() {
    let repo = GitTestRepo::new();

    // Create initial file
    repo.create_file("test.txt", "Original line 1\nOriginal line 2\n");
    repo.git_add(&["test.txt"]);
    repo.git_commit("First commit");

    // Modify file (this creates a second commit that we can blame back to)
    repo.create_file("test.txt", "Original line 1\nModified line 2\nNew line 3\n");
    repo.git_add(&["test.txt"]);
    repo.git_commit("Second commit");

    repo.setup_git_blame_plugin();

    // Change to repo directory
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Open file directly
    let file_path = repo.path.join("test.txt");
    harness.open_file(&file_path).unwrap();

    // Wait until file is loaded
    harness
        .wait_until(|h| h.get_buffer_content().unwrap().contains("line"))
        .unwrap();

    // Trigger git blame
    trigger_git_blame(&mut harness);

    // Wait until blame view appears (block headers with ──)
    harness
        .wait_until(|h| h.screen_to_string().contains("──"))
        .unwrap();

    // Navigate to a line from the second commit
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
    harness.process_async_and_render().unwrap();

    let screen_before = harness.screen_to_string();
    println!("Before pressing 'b':\n{screen_before}");

    // Press 'b' to go back in history
    harness
        .send_key(KeyCode::Char('b'), KeyModifiers::NONE)
        .unwrap();

    // Wait until we see the depth indicator in status or content changes
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            // After going back, the blame headers should still be visible
            // and we might see "depth:" in the status or different file content
            screen.contains("──") && (screen.contains("depth:") || screen.contains("First commit"))
        })
        .unwrap();

    let screen_after = harness.screen_to_string();
    println!("After pressing 'b':\n{screen_after}");

    // We should still be in git blame view with block headers
    assert!(
        screen_after.contains("──"),
        "Should still show blame block headers after going back"
    );
}

/// Test git blame with multiple commits shows different authors/dates
// TODO: Fix git blame tests on Windows - they fail due to git command output differences
#[test]
#[cfg_attr(target_os = "windows", ignore)]
fn test_git_blame_shows_different_commits() {
    let repo = GitTestRepo::new();

    // Create file with one commit
    repo.create_file("multi.txt", "Line from first commit\n");
    repo.git_add(&["multi.txt"]);
    repo.git_commit("First commit");

    // Add more lines in a second commit
    repo.create_file(
        "multi.txt",
        "Line from first commit\nLine from second commit\n",
    );
    repo.git_add(&["multi.txt"]);
    repo.git_commit("Second commit");

    repo.setup_git_blame_plugin();

    // Change to repo directory
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Open file directly
    let file_path = repo.path.join("multi.txt");
    harness.open_file(&file_path).unwrap();

    // Wait until file is loaded
    harness
        .wait_until(|h| h.get_buffer_content().unwrap().contains("Line from"))
        .unwrap();

    // Trigger git blame
    trigger_git_blame(&mut harness);

    // Wait until blame view appears with multiple blocks
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            // Should show at least two block headers (different commits)
            // The blocks are separated by ── lines
            let header_count = screen.matches("──").count();
            header_count >= 2
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("Git blame with multiple commits:\n{screen}");

    // Should show both commit messages
    assert!(
        screen.contains("First commit") || screen.contains("Second commit"),
        "Should show commit summaries"
    );
}

/// Test git blame line numbers are correct - headers should NOT have line numbers
/// and content lines should have sequential line numbers matching the source file
// TODO: Fix git blame tests on Windows - they fail due to git command output differences
#[test]
#[cfg_attr(target_os = "windows", ignore)]
fn test_git_blame_line_numbers_correct() {
    let repo = GitTestRepo::new();

    // Create file with multiple commits for different blame blocks
    repo.create_file(
        "numbered.txt",
        "Line 1 from first commit\nLine 2 from first commit\n",
    );
    repo.git_add(&["numbered.txt"]);
    repo.git_commit("First commit");

    // Add more lines in second commit
    repo.create_file("numbered.txt", "Line 1 from first commit\nLine 2 from first commit\nLine 3 from second commit\nLine 4 from second commit\n");
    repo.git_add(&["numbered.txt"]);
    repo.git_commit("Second commit");

    repo.setup_git_blame_plugin();

    // Change to repo directory
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Open file directly
    let file_path = repo.path.join("numbered.txt");
    harness.open_file(&file_path).unwrap();

    // Wait until file is loaded
    harness
        .wait_until(|h| h.get_buffer_content().unwrap().contains("Line 1"))
        .unwrap();

    // Trigger git blame
    trigger_git_blame(&mut harness);

    // Wait until blame view appears with multiple blocks
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.matches("──").count() >= 2
        })
        .unwrap();

    let screen = harness.screen_to_string();
    println!("Git blame with line numbers:\n{screen}");

    // The screen should show:
    // - Header lines WITHOUT line numbers (just spaces or blank in gutter)
    // - Content lines WITH line numbers 1, 2, 3, 4

    // Check that line numbers 1-4 are present (for the 4 content lines)
    // Line numbers appear at the start of lines in the gutter
    assert!(
        screen.contains("1")
            && screen.contains("2")
            && screen.contains("3")
            && screen.contains("4"),
        "Should show line numbers 1-4 for content lines"
    );

    // The header lines (──) should not be preceded by a line number
    // This is harder to check directly, but we can verify the structure
    // by checking that we have more lines than line numbers
    let total_lines = screen.lines().count();
    let header_count = screen.matches("──").count();

    // With 4 content lines and 2 headers, we should have at least 6 lines
    assert!(
        total_lines >= 6,
        "Should have at least 6 lines (4 content + 2 headers), got {total_lines}"
    );
    assert!(
        header_count >= 2,
        "Should have at least 2 header lines, got {header_count}"
    );
}

/// Test git blame scrolling - scroll to bottom and verify rendering is correct
// TODO: Fix git blame tests on Windows - they fail due to git command output differences
#[test]
#[cfg_attr(target_os = "windows", ignore)]
fn test_git_blame_scroll_to_bottom() {
    let repo = GitTestRepo::new();

    // Create file with many lines to require scrolling
    let mut content = String::new();
    for i in 1..=50 {
        content.push_str(&format!("Line {} content\n", i));
    }
    repo.create_file("scrolltest.txt", &content);
    repo.git_add(&["scrolltest.txt"]);
    repo.git_commit("Add scrollable file");

    repo.setup_git_blame_plugin();

    // Change to repo directory
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        30, // Smaller height to force scrolling
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Open file directly
    let file_path = repo.path.join("scrolltest.txt");
    harness.open_file(&file_path).unwrap();

    // Wait until file is loaded
    harness
        .wait_until(|h| h.get_buffer_content().unwrap().contains("Line 1"))
        .unwrap();

    // Trigger git blame
    trigger_git_blame(&mut harness);

    // Wait until blame view appears
    harness
        .wait_until(|h| h.screen_to_string().contains("──"))
        .unwrap();

    let screen_top = harness.screen_to_string();
    println!("Git blame at top:\n{screen_top}");

    // Scroll to bottom using Ctrl+End (go to end in read-only blame view)
    harness
        .send_key(KeyCode::End, KeyModifiers::CONTROL)
        .unwrap();
    harness.process_async_and_render().unwrap();
    harness.render().unwrap();

    let screen_bottom = harness.screen_to_string();
    println!("Git blame at bottom:\n{screen_bottom}");

    // At the bottom, we should see:
    // 1. The last lines of the file (e.g., "Line 50 content")
    // 2. Still have proper rendering (not corrupted)
    // 3. Still be in blame view (showing ── header or content)

    assert!(
        screen_bottom.contains("Line 50")
            || screen_bottom.contains("Line 49")
            || screen_bottom.contains("Line 48"),
        "Should show last lines of file after scrolling to bottom"
    );

    // Should not show the first lines anymore (we scrolled down)
    // Line 1 should be scrolled out of view in a 30-line terminal
    // (though with headers, exact behavior depends on header count)

    // Verify rendering is not corrupted - should still have normal text
    assert!(
        screen_bottom.contains("content"),
        "Should still show file content properly after scrolling"
    );
}

/// Blame view should remain scrollable with many virtual header lines
// TODO: Fix git blame tests on Windows - they fail due to git command output differences
#[test]
#[cfg_attr(target_os = "windows", ignore)]
fn test_git_blame_scroll_with_many_virtual_lines() {
    use std::time::Duration;

    let repo = GitTestRepo::new();

    // Small file (few real lines)
    let content = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\n";
    repo.create_file("scroll_many_virtual.txt", content);
    repo.git_add(&["scroll_many_virtual.txt"]);
    repo.git_commit("Add file with few lines");
    repo.setup_git_blame_plugin();

    // Change to repo directory
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    // Small viewport to stress scrolling with virtual lines from blame headers
    let mut harness = EditorTestHarness::with_config_and_working_dir(
        80,
        20,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Open file
    let file_path = repo.path.join("scroll_many_virtual.txt");
    harness.open_file(&file_path).unwrap();
    harness.render().unwrap();

    // Trigger git blame to insert virtual header lines
    trigger_git_blame(&mut harness);

    // Wait for blame view
    harness
        .wait_until(|h| h.screen_to_string().contains("──"))
        .unwrap();

    // Scroll down repeatedly with Down arrow; should make progress even with many virtual lines
    for _ in 0..40 {
        harness.send_key(KeyCode::Down, KeyModifiers::NONE).unwrap();
        harness.process_async_and_render().unwrap();
        harness.sleep(Duration::from_millis(5));
    }
    harness.render().unwrap();

    let screen = harness.screen_to_string();
    println!("Blame after scrolling with virtual lines:\n{screen}");

    // Expect bottom lines to be visible despite virtual header lines
    assert!(
        screen.contains("Line 5") || screen.contains("Line 4"),
        "Should see tail lines after scrolling with many virtual lines"
    );
}

// =============================================================================
// View Transform Tests - Minimal reproduction of byte 0 header bug
// =============================================================================

/// Helper to trigger test view marker via command palette
fn trigger_test_view_marker(harness: &mut EditorTestHarness) {
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness.type_text("Test View Marker").unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
}

/// Helper to trigger test view marker with many virtual lines via command palette
fn trigger_test_view_marker_many_virtual_lines(harness: &mut EditorTestHarness) {
    harness
        .send_key(KeyCode::Char('p'), KeyModifiers::CONTROL)
        .unwrap();
    harness.render().unwrap();
    harness
        .type_text("Test View Marker (Many Virtual Lines)")
        .unwrap();
    harness
        .send_key(KeyCode::Enter, KeyModifiers::NONE)
        .unwrap();
    harness.render().unwrap();
}

/// MINIMAL REPRODUCTION: View transform header at byte 0 should be visible
///
/// This is the simplest possible test for the bug described in docs/BLAME.md:
/// - A view transform injects a header at byte offset 0
/// - The header text should be visible on screen
/// - Currently, the header row exists (blank gutter) but text is empty
///
/// Expected screen output:
/// ```
///       │ == HEADER AT BYTE 0 ==    <- Row 1: blank gutter (no line num), header text
///     1 │ Line 1                    <- Row 2: line 1
///     2 │ Line 2                    <- Row 3: line 2
///     3 │ Line 3                    <- Row 4: line 3
/// ```
///
/// Actual buggy output:
/// ```
///       │                           <- Row 1: blank gutter, EMPTY content (BUG!)
///       │ Line 1                    <- Row 2: blank gutter (wrong! should be line 1)
///     2 │ Line 2                    <- Row 3: line 2
///     3 │ Line 3                    <- Row 4: line 3
/// ```
#[test]
fn test_view_transform_header_at_byte_zero() {
    init_tracing_from_env();

    let repo = GitTestRepo::new();

    // Create a simple file (just for the plugins directory setup)
    repo.create_file("test.txt", "placeholder");
    repo.git_add(&["test.txt"]);
    repo.git_commit("Initial commit");
    repo.setup_test_view_marker_plugin();

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Open the test file (needed to have a split to put our virtual buffer in)
    let file_path = repo.path.join("test.txt");
    harness.open_file(&file_path).unwrap();

    // Wait for file to load
    harness
        .wait_until(|h| !h.get_buffer_content().unwrap().is_empty())
        .unwrap();

    // Trigger the test view marker command
    trigger_test_view_marker(&mut harness);

    // Wait for the virtual buffer to be created
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Test view marker active") || screen.contains("*test-view-marker*")
        })
        .unwrap();

    // Wait for the view transform to be applied
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("HEADER AT BYTE 0")
        })
        .unwrap();

    let screen_after = harness.screen_to_string();
    println!("Screen after view marker:\n{screen_after}");
}

/// Ensure scrolling still works when a view transform injects many virtual lines
#[test]
fn test_view_transform_scroll_with_many_virtual_lines() {
    init_tracing_from_env();

    let repo = GitTestRepo::new();

    repo.create_file("test.txt", "placeholder");
    repo.git_add(&["test.txt"]);
    repo.git_commit("Initial commit");
    repo.setup_test_view_marker_plugin();

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        20,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Open the test file (so the virtual buffer has a split to attach to)
    let file_path = repo.path.join("test.txt");
    harness.open_file(&file_path).unwrap();
    harness
        .wait_until(|h| !h.get_buffer_content().unwrap().is_empty())
        .unwrap();

    // Launch the view marker that injects many virtual lines (120 pads + header before Line 1)
    trigger_test_view_marker_many_virtual_lines(&mut harness);

    // Wait for the virtual buffer to be created and rendered
    // The cursor starts at Line 1 (byte 0), which is view line 121 (after 120 virtual pads + 1 header)
    // Auto-scroll should bring the cursor into view, showing the source lines
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("Line 1") || screen.contains("Line 2") || screen.contains("Line 3")
        })
        .unwrap();

    let initial_screen = harness.screen_to_string();
    println!("Initial screen (auto-scrolled to cursor):\n{initial_screen}");

    // Now scroll UP to verify we can see the virtual lines
    for _ in 0..150 {
        harness.send_key(KeyCode::Up, KeyModifiers::NONE).unwrap();
        harness.process_async_and_render().unwrap();
    }
    harness.render().unwrap();

    let screen_after_up = harness.screen_to_string();
    println!("Screen after scrolling up through virtual lines:\n{screen_after_up}");

    // After scrolling up, we should see the header or virtual pads
    assert!(
        screen_after_up.contains("HEADER AT BYTE 0") || screen_after_up.contains("Virtual pad"),
        "Scrolling up should reveal header or virtual pad lines"
    );
}

/// Test scrolling with a single virtual line (header only, no pads)
#[test]
fn test_view_transform_scroll_with_single_virtual_line() {
    init_tracing_from_env();

    let repo = GitTestRepo::new();

    repo.create_file("test.txt", "placeholder");
    repo.git_add(&["test.txt"]);
    repo.git_commit("Initial commit");
    repo.setup_test_view_marker_plugin();

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        20,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Open the test file
    let file_path = repo.path.join("test.txt");
    harness.open_file(&file_path).unwrap();
    harness
        .wait_until(|h| !h.get_buffer_content().unwrap().is_empty())
        .unwrap();

    // Launch the view marker that injects just a header (no pads)
    trigger_test_view_marker(&mut harness);

    // Wait for virtual buffer to render with header
    harness
        .wait_until(|h| h.screen_to_string().contains("HEADER AT BYTE 0"))
        .unwrap();

    let screen = harness.screen_to_string();
    println!("Screen with single virtual header line:\n{screen}");

    // Should also see source content below the header
    assert!(
        screen.contains("Line 1") || screen.contains("Line 2"),
        "Source content should be visible below header"
    );

    // Verify exact line order by extracting content lines from screen
    let content_lines: Vec<&str> = screen
        .lines()
        .filter(|l| l.contains("") && !l.contains("~"))
        .collect();

    println!("Content lines: {content_lines:?}");

    // Should have at least 4 lines: header, Line 1, Line 2, Line 3
    assert!(
        content_lines.len() >= 4,
        "Expected at least 4 content lines"
    );

    // Line 0: Header (no line number, just separator)
    assert!(
        content_lines[0].contains("│ == HEADER AT BYTE 0 =="),
        "Line 0 should be header without line number. Got: {}",
        content_lines[0]
    );

    // Line 1: "Line 1" with gutter showing "1"
    assert!(
        content_lines[1].contains("1 │ Line 1"),
        "Line 1 should show '1 │ Line 1'. Got: {}",
        content_lines[1]
    );

    // Line 2: "Line 2" with gutter showing "2"
    assert!(
        content_lines[2].contains("2 │ Line 2"),
        "Line 2 should show '2 │ Line 2'. Got: {}",
        content_lines[2]
    );

    // Line 3: "Line 3" with gutter showing "3"
    assert!(
        content_lines[3].contains("3 │ Line 3"),
        "Line 3 should show '3 │ Line 3'. Got: {}",
        content_lines[3]
    );
}

/// Test that original buffer does NOT show blame decorators
/// When blame is opened, ONLY the blame virtual buffer should have headers
// TODO: Fix git blame tests on Windows - they fail due to git command output differences
#[test]
#[cfg_attr(target_os = "windows", ignore)]
fn test_git_blame_original_buffer_not_decorated() {
    let repo = GitTestRepo::new();
    repo.setup_typical_project();
    repo.setup_git_blame_plugin();

    // Change to repo directory
    let original_dir = repo.change_to_repo_dir();
    let _guard = DirGuard::new(original_dir);

    let mut harness = EditorTestHarness::with_config_and_working_dir(
        120,
        40,
        Config::default(),
        repo.path.clone(),
    )
    .unwrap();

    // Open file directly
    let file_path = repo.path.join("src/main.rs");
    harness.open_file(&file_path).unwrap();

    // Wait until file is loaded
    harness
        .wait_until(|h| h.get_buffer_content().unwrap().contains("fn main"))
        .unwrap();

    // Capture screen BEFORE opening blame
    let screen_before_blame = harness.screen_to_string();
    println!("Screen before blame:\n{screen_before_blame}");

    // Original file should NOT have blame headers
    assert!(
        !screen_before_blame.contains("──"),
        "Original file should NOT have blame headers before opening blame"
    );

    // Trigger git blame
    trigger_git_blame(&mut harness);

    // Wait until blame view appears
    harness
        .wait_until(|h| h.screen_to_string().contains("──"))
        .unwrap();

    let screen_with_blame = harness.screen_to_string();
    println!("Screen with blame:\n{screen_with_blame}");

    // Blame view SHOULD have headers
    assert!(
        screen_with_blame.contains("──"),
        "Blame view should have headers"
    );

    // Close blame with q
    harness
        .send_key(KeyCode::Char('q'), KeyModifiers::NONE)
        .unwrap();

    // Wait until we're back to original file
    harness
        .wait_until(|h| {
            let screen = h.screen_to_string();
            screen.contains("fn main") && !screen.contains("──")
        })
        .unwrap();

    let screen_after_close = harness.screen_to_string();
    println!("Screen after closing blame:\n{screen_after_close}");

    // After closing, original file should NOT have blame headers
    assert!(
        !screen_after_close.contains("──"),
        "Original file should NOT have blame headers after closing blame"
    );
}