gitwig 2.0.3

a rust based tui, an alternative to sourcetree and gitui
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
use super::*;

impl App {
    pub fn set_error(&mut self, msg: String) {
        crate::debug_log::error(&msg);
        self.error_message = Some(msg);
    }

    pub fn status_height(&self) -> u16 {
        if self.status_expanded { 3 } else { 1 }
    }

    pub fn toggle_status_expanded(&mut self) {
        self.status_expanded = !self.status_expanded;
    }

    pub fn get_filtered_items(&self) -> Vec<(usize, &String)> {
        if let Some(ref query) = self.repo_search_query {
            let query_lower = query.to_lowercase();
            self.config
                .items
                .iter()
                .enumerate()
                .filter(|(_, item)| {
                    let file_name = std::path::Path::new(item)
                        .file_name()
                        .and_then(|s| s.to_str())
                        .unwrap_or(item.as_str())
                        .to_lowercase();
                    let full_path = item.to_lowercase();
                    file_name.contains(&query_lower) || full_path.contains(&query_lower)
                })
                .collect()
        } else {
            self.config.items.iter().enumerate().collect()
        }
    }

    pub fn get_items_len(&self) -> usize {
        if self.repo_search_query.is_some() {
            self.get_filtered_items().len()
        } else {
            self.config.items.len()
        }
    }

    pub fn get_selected_item(&self) -> Option<&String> {
        let orig_idx = self.get_selected_item_index()?;
        self.config.items.get(orig_idx)
    }

    pub fn get_selected_item_index(&self) -> Option<usize> {
        self.get_filtered_items().get(self.selected_index).map(|(orig_idx, _)| *orig_idx)
    }

    /// Ensure `selected_index` is a valid index into `config.items` (or filtered items).
    pub fn clamp_selection(&mut self) {
        let len = self.get_items_len();
        if len == 0 {
            self.selected_index = 0;
        } else if self.selected_index >= len {
            self.selected_index = len - 1;
        }
    }

    /// Ensure the scroll window doesn't extend past the end of the list.
    pub fn clamp_scroll(&mut self, visible_count: usize) {
        let max_scroll = self.get_items_len().saturating_sub(visible_count);
        if self.scroll_top > max_scroll {
            self.scroll_top = max_scroll;
        }
    }

    /// Clamp the help scroll value so it doesn't go out of bounds.
    pub fn clamp_help_scroll(&mut self, height: usize) {
        let (percent_y, lines_len) = match self.mode {
            Mode::Help => (70, crate::popups::help::get_help_lines_len(self)),
            Mode::DetailHelp => (55, crate::popups::detail_help::get_detail_help_lines_len(self)),
            _ => return,
        };
        let popup_height = (height * percent_y) / 100;
        let inner_height = popup_height.saturating_sub(2);
        let max_scroll = lines_len.saturating_sub(inner_height);
        if self.help_scroll > max_scroll {
            self.help_scroll = max_scroll;
        }
    }

    pub fn move_down(&mut self, visible_count: usize) {
        let len = self.get_items_len();
        if self.selected_index + 1 < len {
            self.selected_index += 1;
            let bottom = self.scroll_top + visible_count;
            if self.selected_index >= bottom {
                self.scroll_top = self.scroll_top.saturating_add(1);
            }
        }
    }

    pub fn move_up(&mut self) {
        if self.selected_index > 0 {
            self.selected_index -= 1;
            if self.selected_index < self.scroll_top {
                self.scroll_top = self.scroll_top.saturating_sub(1);
            }
        }
    }

    /// Jump the selection forward by one page (= `visible_count` items).
    /// The scroll window advances by the same amount so the newly selected
    /// item is always at the top of the visible area.
    pub fn page_down(&mut self, visible_count: usize) {
        let len = self.get_items_len();
        let last = len.saturating_sub(1);
        self.selected_index = (self.selected_index + visible_count).min(last);
        // Align scroll so the selection lands at the top of the viewport,
        // then let clamp_scroll cap it at the list end.
        self.scroll_top = self.selected_index;
    }

    /// Jump the selection backward by one page (= `visible_count` items).
    pub fn page_up(&mut self, visible_count: usize) {
        self.selected_index = self.selected_index.saturating_sub(visible_count);
        self.scroll_top = self.selected_index;
    }

    pub fn move_to_top(&mut self) {
        self.selected_index = 0;
        self.scroll_top = 0;
    }

    pub fn move_to_bottom(&mut self, visible_count: usize) {
        let len = self.get_items_len();
        if len > 0 {
            self.selected_index = len - 1;
            self.scroll_top = self.selected_index.saturating_sub(visible_count - 1);
        }
    }

    pub fn is_fzf_installed(&self) -> bool {
        if let Some(forced) = self.force_fzf_missing {
            return !forced;
        }
        std::process::Command::new("fzf")
            .arg("--version")
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .is_ok()
    }

    pub fn open_help(&mut self) {
        self.help_scroll = 0;
        self.mode = Mode::Help;
    }

    pub fn open_about(&mut self) {
        self.mode = Mode::About;
    }

    /// Re-runs the cheap filesystem inspection for the selected item and
    /// updates its status indicator. Surfaces a transient "Refreshed" /
    /// "Refresh failed" message in the status bar so the user knows the
    /// keystroke landed (the indicator alone may not visibly change).
    pub fn refresh_selected_status(&mut self) {
        crate::debug_log::info("Refreshing selected repository status");
        let Some(orig_idx) = self.get_selected_item_index() else {
            return;
        };
        let Some(item) = self.config.items.get(orig_idx) else {
            return;
        };
        let new_status = repo::inspect_summary(item);
        if let Some(slot) = self.statuses.get_mut(orig_idx) {
            *slot = new_status;
        }
        self.status_message = Some("Refreshed".to_string());
    }

    pub fn sort_items_in_place(&mut self) {
        let mut zipped: Vec<(String, ItemStatus)> = match self.config.sort_by {
            SortOrder::Custom => {
                let mut status_map: std::collections::HashMap<String, ItemStatus> =
                    self.config.items.drain(..).zip(self.statuses.drain(..)).collect();
                let mut z: Vec<(String, ItemStatus)> = self
                    .original_items
                    .iter()
                    .map(|item| {
                        let status =
                            status_map.remove(item).unwrap_or_else(|| repo::inspect_summary(item));
                        (item.clone(), status)
                    })
                    .collect();
                if self.config.sort_reverse {
                    z.reverse();
                }
                z
            }
            SortOrder::Alphabetical => {
                let mut z: Vec<(String, ItemStatus)> =
                    self.config.items.drain(..).zip(self.statuses.drain(..)).collect();
                z.sort_by(|a, b| a.0.cmp(&b.0));
                if self.config.sort_reverse {
                    z.reverse();
                }
                z
            }
            SortOrder::RecentVisit => {
                let visits = &self.config.visits;
                let mut z: Vec<(String, ItemStatus)> =
                    self.config.items.drain(..).zip(self.statuses.drain(..)).collect();
                z.sort_by(|a, b| {
                    let time_a = visits.get(&a.0).copied().unwrap_or(0);
                    let time_b = visits.get(&b.0).copied().unwrap_or(0);
                    time_b.cmp(&time_a) // Descending
                });
                if self.config.sort_reverse {
                    z.reverse();
                }
                z
            }
            SortOrder::LatestChanges => {
                let mut z: Vec<(String, ItemStatus)> =
                    self.config.items.drain(..).zip(self.statuses.drain(..)).collect();
                z.sort_by(|a, b| {
                    let time_a = repo::get_latest_change_time(&a.0);
                    let time_b = repo::get_latest_change_time(&b.0);
                    time_b.cmp(&time_a) // Descending
                });
                if self.config.sort_reverse {
                    z.reverse();
                }
                z
            }
        };

        // Stable-partition pinned items to the top
        zipped.sort_by_key(|(item, _)| !self.config.pinned.contains(item));

        let (items, statuses): (Vec<String>, Vec<ItemStatus>) = zipped.into_iter().unzip();
        self.config.items = items;
        self.statuses = statuses;
    }

    pub fn cycle_sort_order(&mut self) {
        self.config.sort_by = match self.config.sort_by {
            SortOrder::Custom => SortOrder::Alphabetical,
            SortOrder::Alphabetical => SortOrder::RecentVisit,
            SortOrder::RecentVisit => SortOrder::LatestChanges,
            SortOrder::LatestChanges => SortOrder::Custom,
        };

        let selected_item = self.get_selected_item().cloned();

        self.sort_items_in_place();

        if let Some(item) = selected_item {
            let filtered = self.get_filtered_items();
            if let Some(pos) = filtered.iter().position(|(_, x)| *x == &item) {
                self.selected_index = pos;
            }
        }

        self.persist("Sort mode updated");
    }

    pub fn toggle_sort_reverse(&mut self) {
        self.config.sort_reverse = !self.config.sort_reverse;

        let selected_item = self.get_selected_item().cloned();

        self.sort_items_in_place();

        if let Some(item) = selected_item {
            let filtered = self.get_filtered_items();
            if let Some(pos) = filtered.iter().position(|(_, x)| *x == &item) {
                self.selected_index = pos;
            }
        }

        self.persist("Sort direction updated");
    }

    pub fn toggle_pin_selected(&mut self) {
        let Some(selected_item) = self.get_selected_item().cloned() else {
            return;
        };
        if self.config.pinned.contains(&selected_item) {
            self.config.pinned.remove(&selected_item);
            self.status_message = Some("Unpinned repository".to_string());
        } else {
            self.config.pinned.insert(selected_item.clone());
            self.status_message = Some("Pinned repository".to_string());
        }

        self.sort_items_in_place();

        let filtered = self.get_filtered_items();
        if let Some(pos) = filtered.iter().position(|(_, x)| *x == &selected_item) {
            self.selected_index = pos;
        }

        let msg = self.status_message.as_deref().unwrap_or("Saved").to_string();
        self.persist(&msg);
    }

    /// Snapshot the selected item's filesystem/git state and enter the
    /// Detail view. The snapshot is held in `current_detail` for as long
    /// as the view is open; closing clears it.
    pub fn open_detail(&mut self) {
        if let Some(item) = self.get_selected_item().cloned() {
            crate::debug_log::info(format!("Opening detail view for repository: {}", item));
            // Update visit time
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();
            self.config.visits.insert(item.clone(), now);
            let _ = save_config(&self.config, &self.config_path);

            if self.config.sort_by == SortOrder::RecentVisit {
                self.sort_items_in_place();
                let filtered = self.get_filtered_items();
                if let Some(pos) = filtered.iter().position(|(_, x)| *x == &item) {
                    self.selected_index = pos;
                }
            }

            let cached_valid = if let Some(cached) = self.detail_cache.get(&item) {
                cached.loaded_at.elapsed().as_secs() < self.config.detail_cache_ttl_secs
            } else {
                false
            };

            let tx = self.detail_tx.clone();
            let item_clone = item.clone();
            let graph_max_commits = self.config.graph_max_commits;
            let enable_commit_signatures = self.config.enable_commit_signatures;

            if cached_valid {
                if let Some(cached) = self.detail_cache.get(&item).cloned() {
                    let cached_commits_count = match &cached.detail {
                        repo::ItemDetail::Repo { info, .. } => info.commits.len(),
                        _ => 200,
                    };
                    self.commit_list.limit = if self.config.max_commits > 0 {
                        cached_commits_count.max(self.config.max_commits)
                    } else {
                        0
                    };
                    self.current_detail = Some(cached.detail);
                    self.rebuild_visible_files();
                }

                let max_commits = self.commit_list.limit;
                // Silent background refresh
                std::thread::spawn(move || {
                    let detail = repo::inspect_detail(
                        &item_clone,
                        max_commits,
                        graph_max_commits,
                        enable_commit_signatures,
                    );
                    let _ = tx.send((item_clone, detail));
                });
            } else {
                self.commit_list.limit = self.config.max_commits;
                self.loading_repo_path = Some(item.clone());
                let max_commits = self.commit_list.limit;
                std::thread::spawn(move || {
                    let detail = repo::inspect_detail(
                        &item_clone,
                        max_commits,
                        graph_max_commits,
                        enable_commit_signatures,
                    );
                    let _ = tx.send((item_clone, detail));
                });
            }

            self.detail_focus = DetailSection::Commits;
            self.commit_list.selection = 0;
            self.status_list.file_selection = 0;
            self.status_list.staging_file_selection = 0;
            self.diff.file_diff.clear();
            self.diff.diff_scroll = 0;
            self.commit_list.details_scroll = 0;
            self.commit_input_scroll = 0;
            self.branch_list.local_branch_selection = 0;
            self.branch_list.remote_branch_selection = 0;
            self.tag_list.local_tag_selection = 0;
            self.tag_list.remote_tag_selection = 0;
            self.branch_list.remote_selection = 0;
            self.stash_list.stash_selection = 0;
            self.stash_list.stash_file_selection = 0;
            self.file_tree.file_list_selection = 0;
            self.file_tree.file_content_scroll = 0;
            self.file_tree.expanded_folders.clear();
            self.detail_tab = 0;
            self.graph_scroll = 0;
            self.inspect_full_diff = false;
            self.commit_popup.maximized = false;
            self.mode = Mode::Detail;
        }
    }

    /// Resync the selected item's filesystem/git state inside the Detail view,
    /// clamping selection indices to their new totals.
    /// Resync the selected item's filesystem/git state inside the Detail view asynchronously.
    pub fn resync_detail(&mut self) {
        if let Some(item) = self.get_selected_item().cloned() {
            crate::debug_log::info("Resyncing repository details");
            let path = std::path::PathBuf::from(&item);
            repo::invalidate_ref_map_cache(&path);

            if let Some(repo::ItemDetail::Repo { info, .. }) = &mut self.current_detail {
                info.local_branches = repo::TabData::NotLoaded;
                info.remote_branches = repo::TabData::NotLoaded;
                info.local_tags = repo::TabData::NotLoaded;
                info.remote_tags = repo::TabData::NotLoaded;
                info.files = repo::TabData::NotLoaded;
                info.stashes = repo::TabData::NotLoaded;
                info.graph_lines = repo::TabData::NotLoaded;
                info.committer_stats = repo::TabData::NotLoaded;
                info.remote_tags_loaded = false;
                info.remote_tags_attempted = false;
                info.tab_loaded_at = [None; 8];
            }

            self.loading_repo_path = Some(item.clone());
            let tx = self.detail_tx.clone();
            let max_commits = self.commit_list.limit;
            let graph_max_commits = self.config.graph_max_commits;
            let enable_commit_signatures = self.config.enable_commit_signatures;
            std::thread::spawn(move || {
                let detail = repo::inspect_detail(
                    &item,
                    max_commits,
                    graph_max_commits,
                    enable_commit_signatures,
                );
                let _ = tx.send((item, detail));
            });
        }
    }

    pub fn update_cache_from_current_detail(&mut self) {
        if let Some(detail) = &self.current_detail {
            let path_str = match detail {
                repo::ItemDetail::Repo { resolved, .. }
                | repo::ItemDetail::Missing { resolved, .. }
                | repo::ItemDetail::Directory { resolved, .. }
                | repo::ItemDetail::Error { resolved, .. } => {
                    resolved.to_string_lossy().to_string()
                }
            };
            self.detail_cache.insert(
                path_str,
                DetailCache { detail: detail.clone(), loaded_at: std::time::Instant::now() },
            );
        }
    }

    /// Apply a loaded detail snapshot, clamping selection indices to their new totals.
    pub fn apply_detail_snapshot(&mut self, detail: repo::ItemDetail) {
        let mut merged_detail = detail;
        if let Some(repo::ItemDetail::Repo { resolved: old_resolved, info: old_info }) =
            &self.current_detail
        {
            if let repo::ItemDetail::Repo { resolved: new_resolved, info: new_info } =
                &mut merged_detail
            {
                if old_resolved == new_resolved {
                    if new_info.remotes.is_not_loaded() {
                        new_info.remotes = old_info.remotes.clone();
                    }
                    if new_info.graph_lines.is_not_loaded() {
                        new_info.graph_lines = old_info.graph_lines.clone();
                    }
                    if new_info.local_branches.is_not_loaded() {
                        new_info.local_branches = old_info.local_branches.clone();
                    }
                    if new_info.remote_branches.is_not_loaded() {
                        new_info.remote_branches = old_info.remote_branches.clone();
                    }
                    if new_info.local_tags.is_not_loaded() {
                        new_info.local_tags = old_info.local_tags.clone();
                    }
                    if new_info.remote_tags.is_not_loaded() {
                        new_info.remote_tags = old_info.remote_tags.clone();
                    }
                    new_info.remote_tags_loaded = old_info.remote_tags_loaded;
                    new_info.remote_tags_attempted = old_info.remote_tags_attempted;
                    if new_info.files.is_not_loaded() {
                        new_info.files = old_info.files.clone();
                    }
                    if new_info.stashes.is_not_loaded() {
                        new_info.stashes = old_info.stashes.clone();
                    }
                    if new_info.committer_stats.is_not_loaded() {
                        new_info.committer_stats = old_info.committer_stats.clone();
                        new_info.committer_stats_limit_reached =
                            old_info.committer_stats_limit_reached;
                    }
                    new_info.tab_loaded_at = old_info.tab_loaded_at;
                    new_info.tab_loading = old_info.tab_loading;
                }
            }
        }

        self.current_detail = Some(merged_detail);
        self.ensure_selected_commit_files_loaded();
        self.update_cache_from_current_detail();
        self.rebuild_visible_files();

        // Extract all lengths first to avoid borrow-checker conflicts
        let mut info_lengths = None;
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let commits_len = info.commits.len();
            let local_branches_len = info.local_branches.len();
            let remote_branches_len = info.remote_branches.len();
            let local_tags_len = info.local_tags.len();
            let remote_tags_len = info.remote_tags.len();
            let remotes_len = info.remotes.len();
            let stashes_len = info.stashes.len();
            let staged_len = info.changes.staged.len();
            let unstaged_len = info.changes.unstaged.len();

            let commit_files_len =
                info.commits.get(self.commit_list.selection).map(|c| c.files.len()).unwrap_or(0);

            info_lengths = Some((
                commits_len,
                local_branches_len,
                remote_branches_len,
                local_tags_len,
                remote_tags_len,
                remotes_len,
                stashes_len,
                staged_len,
                unstaged_len,
                commit_files_len,
            ));
        }

        if let Some((
            commits_len,
            local_branches_len,
            remote_branches_len,
            local_tags_len,
            remote_tags_len,
            remotes_len,
            stashes_len,
            staged_len,
            unstaged_len,
            commit_files_len,
        )) = info_lengths
        {
            // 1. Commit selection
            if commits_len == 0 {
                self.commit_list.selection = 0;
            } else if self.commit_list.selection >= commits_len {
                self.commit_list.selection = commits_len - 1;
            }

            // 2. File list selection (Files tab)
            let visible_files_len = self.file_tree.visible_files.len();
            if visible_files_len == 0 {
                self.file_tree.file_list_selection = 0;
            } else if self.file_tree.file_list_selection >= visible_files_len {
                self.file_tree.file_list_selection = visible_files_len - 1;
            }

            // 3. Local branches selection
            if local_branches_len == 0 {
                self.branch_list.local_branch_selection = 0;
            } else if self.branch_list.local_branch_selection >= local_branches_len {
                self.branch_list.local_branch_selection = local_branches_len - 1;
            }

            // 4. Remote branches selection
            if remote_branches_len == 0 {
                self.branch_list.remote_branch_selection = 0;
            } else if self.branch_list.remote_branch_selection >= remote_branches_len {
                self.branch_list.remote_branch_selection = remote_branches_len - 1;
            }

            // 5. Local tags selection
            if local_tags_len == 0 {
                self.tag_list.local_tag_selection = 0;
            } else if self.tag_list.local_tag_selection >= local_tags_len {
                self.tag_list.local_tag_selection = local_tags_len - 1;
            }

            // 6. Remote tags selection
            if remote_tags_len == 0 {
                self.tag_list.remote_tag_selection = 0;
            } else if self.tag_list.remote_tag_selection >= remote_tags_len {
                self.tag_list.remote_tag_selection = remote_tags_len - 1;
            }

            // 7. Remotes selection
            if remotes_len == 0 {
                self.branch_list.remote_selection = 0;
            } else if self.branch_list.remote_selection >= remotes_len {
                self.branch_list.remote_selection = remotes_len - 1;
            }

            // 8. Stashes selection
            if stashes_len == 0 {
                self.stash_list.stash_selection = 0;
            } else if self.stash_list.stash_selection >= stashes_len {
                self.stash_list.stash_selection = stashes_len - 1;
            }

            // 9. Files/Diff selection in Workspace/Commits details
            // Workspace stage/unstage file lists
            if self.is_uncommitted_selected() {
                // Staged files vs Unstaged files selection
                let active_len = if self.detail_focus == DetailSection::Staged {
                    staged_len
                } else if self.detail_focus == DetailSection::Unstaged {
                    unstaged_len
                } else {
                    0
                };
                if active_len == 0 {
                    self.status_list.staging_file_selection = 0;
                } else if self.status_list.staging_file_selection >= active_len {
                    self.status_list.staging_file_selection = active_len - 1;
                }
            } else {
                // Commits file selection
                if commit_files_len == 0 {
                    self.status_list.file_selection = 0;
                } else if self.status_list.file_selection >= commit_files_len {
                    self.status_list.file_selection = commit_files_len - 1;
                }
            }
        }

        self.diff.diff_scroll = 0;
        if self.is_uncommitted_selected() {
            self.refresh_staging_diff();
        } else {
            self.refresh_file_diff();
        }
    }

    /// Trigger asynchronous loading of a tab's lazy data if it is not yet loaded or stale.
    #[allow(clippy::collapsible_match)]
    pub fn trigger_tab_load_if_needed(&mut self, tab_idx: usize) {
        let Some(repo::ItemDetail::Repo { resolved, info }) = &mut self.current_detail else {
            return;
        };
        let path = resolved.clone();
        let tx = self.tab_tx.clone();
        let commit_limit = self.config.max_commits;
        let graph_max_commits = self.config.graph_max_commits;
        let tab_ttl = self.config.tab_ttl_secs;

        let should_trigger = |info: &repo::RepoInfo, tab_idx: usize, is_not_loaded: bool| -> bool {
            if info.tab_loading[tab_idx] {
                return false;
            }
            if is_not_loaded {
                return true;
            }
            if let Some(loaded_at) = info.tab_loaded_at[tab_idx] {
                loaded_at.elapsed().as_secs() >= tab_ttl
            } else {
                true
            }
        };

        match tab_idx {
            1 => {
                let is_not_loaded = info.files.is_not_loaded();
                crate::debug_log::info(format!(
                    "trigger_tab_load_if_needed(1): is_not_loaded={}, tab_loading={}",
                    is_not_loaded, info.tab_loading[tab_idx]
                ));
                if should_trigger(info, tab_idx, is_not_loaded) {
                    crate::debug_log::info(
                        "trigger_tab_load_if_needed(1): spawning load_tab_files thread",
                    );
                    info.tab_loading[tab_idx] = true;
                    if is_not_loaded {
                        info.files = repo::TabData::Loading;
                    }
                    std::thread::spawn(move || {
                        let res = repo::load_tab_files(&path);
                        let _ = tx.send((
                            path.to_string_lossy().to_string(),
                            tab_idx,
                            repo::TabPayload::Files(res),
                        ));
                    });
                }
            }
            2 => {
                let is_not_loaded = info.graph_lines.is_not_loaded();
                if should_trigger(info, tab_idx, is_not_loaded) {
                    info.tab_loading[tab_idx] = true;
                    if is_not_loaded {
                        info.graph_lines = repo::TabData::Loading;
                    }
                    let tx_clone = tx.clone();
                    let path_str = path.to_string_lossy().to_string();
                    std::thread::spawn(move || {
                        let res = repo::load_tab_graph_stream(
                            &path,
                            graph_max_commits,
                            path_str.clone(),
                            tab_idx,
                            tx_clone,
                        );
                        let _ = tx.send((path_str, tab_idx, repo::TabPayload::Graph(res)));
                    });
                }
            }
            3 => {
                let is_not_loaded = info.local_branches.is_not_loaded();
                if should_trigger(info, tab_idx, is_not_loaded) {
                    info.tab_loading[tab_idx] = true;
                    if is_not_loaded {
                        info.local_branches = repo::TabData::Loading;
                        info.remote_branches = repo::TabData::Loading;
                    }
                    std::thread::spawn(move || {
                        let (local_res, remote_res) = repo::load_tab_branches(&path);
                        let _ = tx.send((
                            path.to_string_lossy().to_string(),
                            tab_idx,
                            repo::TabPayload::Branches { local: local_res, remote: remote_res },
                        ));
                    });
                }
            }
            4 => {
                let is_not_loaded = info.local_tags.is_not_loaded();
                if should_trigger(info, tab_idx, is_not_loaded) {
                    info.tab_loading[tab_idx] = true;
                    if is_not_loaded {
                        info.local_tags = repo::TabData::Loading;
                        info.remote_tags = repo::TabData::Loading;
                    }
                    std::thread::spawn(move || {
                        let (local_res, remote_res) = repo::load_tab_tags(&path);
                        let _ = tx.send((
                            path.to_string_lossy().to_string(),
                            tab_idx,
                            repo::TabPayload::Tags { local: local_res, remote: remote_res },
                        ));
                    });
                }
            }
            5 => {
                let is_not_loaded = info.remotes.is_not_loaded();
                if should_trigger(info, tab_idx, is_not_loaded) {
                    info.tab_loading[tab_idx] = true;
                    if is_not_loaded {
                        info.remotes = repo::TabData::Loading;
                    }
                    std::thread::spawn(move || {
                        let res = repo::load_tab_remotes(&path);
                        let _ = tx.send((
                            path.to_string_lossy().to_string(),
                            tab_idx,
                            repo::TabPayload::Remotes(res),
                        ));
                    });
                }
            }
            6 => {
                let is_not_loaded = info.stashes.is_not_loaded();
                if should_trigger(info, tab_idx, is_not_loaded) {
                    info.tab_loading[tab_idx] = true;
                    if is_not_loaded {
                        info.stashes = repo::TabData::Loading;
                    }
                    std::thread::spawn(move || {
                        let res = repo::load_tab_stashes(&path);
                        let _ = tx.send((
                            path.to_string_lossy().to_string(),
                            tab_idx,
                            repo::TabPayload::Stashes(res),
                        ));
                    });
                }
            }
            7 => {
                let is_not_loaded = info.committer_stats.is_not_loaded();
                if should_trigger(info, tab_idx, is_not_loaded) {
                    info.tab_loading[tab_idx] = true;
                    if is_not_loaded {
                        info.committer_stats = repo::TabData::Loading;
                    }
                    std::thread::spawn(move || {
                        let res = repo::load_tab_overview(&path, commit_limit);
                        let _ = tx.send((
                            path.to_string_lossy().to_string(),
                            tab_idx,
                            repo::TabPayload::Overview(res),
                        ));
                    });
                }
            }
            _ => {}
        }
    }

    /// Advance focus to the next detail panel (Tab key).
    pub fn cycle_detail_focus(&mut self, reverse: bool) {
        if self.detail_tab == 3 {
            self.detail_focus = match self.detail_focus {
                DetailSection::LocalBranches => DetailSection::RemoteBranches,
                _ => DetailSection::LocalBranches,
            };
            return;
        }
        if self.detail_tab == 4 {
            self.detail_focus = match self.detail_focus {
                DetailSection::LocalTags => DetailSection::RemoteTags,
                _ => DetailSection::LocalTags,
            };
            return;
        }
        if self.detail_tab == 1 {
            self.detail_focus = match self.detail_focus {
                DetailSection::Files => DetailSection::FileContent,
                _ => DetailSection::Files,
            };
            return;
        }
        if self.detail_tab == 6 {
            self.detail_focus = if reverse {
                match self.detail_focus {
                    DetailSection::Stashes => DetailSection::StagingDetails,
                    DetailSection::StagingDetails => DetailSection::StashedFiles,
                    _ => DetailSection::Stashes,
                }
            } else {
                match self.detail_focus {
                    DetailSection::Stashes => DetailSection::StashedFiles,
                    DetailSection::StashedFiles => DetailSection::StagingDetails,
                    _ => DetailSection::Stashes,
                }
            };
            return;
        }
        if self.detail_tab == 0 {
            let mut next_focus =
                if reverse { self.detail_focus.prev() } else { self.detail_focus.next() };
            for _ in 0..10 {
                let skip = match next_focus {
                    DetailSection::Staged => {
                        if self.is_uncommitted_selected() {
                            self.is_staged_empty()
                        } else {
                            self.is_selected_commit_empty()
                        }
                    }
                    DetailSection::Unstaged => {
                        self.is_unstaged_empty() || !self.is_uncommitted_selected()
                    }
                    DetailSection::Conflicts => {
                        self.is_conflicted_empty() || !self.is_uncommitted_selected()
                    }
                    DetailSection::CommitDetails => self.is_uncommitted_selected(),
                    DetailSection::StagingDetails => {
                        if self.is_uncommitted_selected() {
                            self.is_staged_empty() && self.is_unstaged_empty()
                        } else {
                            self.is_selected_commit_empty()
                        }
                    }
                    DetailSection::ConflictDiff => {
                        self.is_conflicted_empty() || !self.is_uncommitted_selected()
                    }
                    _ => false,
                };
                if skip {
                    next_focus = if reverse { next_focus.prev() } else { next_focus.next() };
                } else {
                    break;
                }
            }
            self.detail_focus = next_focus;
        } else {
            self.detail_focus =
                if reverse { self.detail_focus.prev() } else { self.detail_focus.next() };
        }
        if self.detail_focus == DetailSection::Staged
            || self.detail_focus == DetailSection::Unstaged
            || self.detail_focus == DetailSection::Conflicts
        {
            self.last_staging_focus = self.detail_focus;
        }
        // Reset staging selection and pre-load diff when landing on Staged/Unstaged/Conflicts.
        match self.detail_focus {
            DetailSection::Staged | DetailSection::Unstaged | DetailSection::Conflicts => {
                self.diff.diff_scroll = 0;
                if self.is_uncommitted_selected() {
                    if self.detail_focus == DetailSection::Conflicts {
                        self.status_list.conflict_file_selection = 0;
                    } else {
                        self.status_list.staging_file_selection = 0;
                    }
                    self.refresh_staging_diff();
                } else {
                    self.status_list.file_selection = 0;
                    self.refresh_file_diff();
                }
            }
            DetailSection::CommitDetails => {
                self.commit_list.details_scroll = 0;
            }
            DetailSection::StagingDetails | DetailSection::ConflictDiff => {
                self.diff.diff_scroll = 0;
            }
            _ => {}
        }
    }

    /// Move local branch selection up.
    pub fn local_branch_up(&mut self) {
        self.branch_list.local_branch_selection =
            self.branch_list.local_branch_selection.saturating_sub(1);
    }

    /// Move local branch selection down.
    pub fn local_branch_down(&mut self) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.local_branches.len();
            if total > 0 && self.branch_list.local_branch_selection + 1 < total {
                self.branch_list.local_branch_selection += 1;
            }
        }
    }

    /// Scroll local branch selection up by page.
    pub fn local_branch_page_up(&mut self, page: usize) {
        self.branch_list.local_branch_selection =
            self.branch_list.local_branch_selection.saturating_sub(page);
    }

    /// Scroll local branch selection down by page.
    pub fn local_branch_page_down(&mut self, page: usize) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.local_branches.len();
            if total > 0 {
                self.branch_list.local_branch_selection =
                    (self.branch_list.local_branch_selection + page).min(total.saturating_sub(1));
            }
        }
    }

    /// Move remote branch selection up.
    pub fn remote_branch_up(&mut self) {
        self.branch_list.remote_branch_selection =
            self.branch_list.remote_branch_selection.saturating_sub(1);
    }

    /// Move remote branch selection down.
    pub fn remote_branch_down(&mut self) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.remote_branches.len();
            if total > 0 && self.branch_list.remote_branch_selection + 1 < total {
                self.branch_list.remote_branch_selection += 1;
            }
        }
    }

    /// Scroll remote branch selection up by page.
    pub fn remote_branch_page_up(&mut self, page: usize) {
        self.branch_list.remote_branch_selection =
            self.branch_list.remote_branch_selection.saturating_sub(page);
    }

    /// Scroll remote branch selection down by page.
    pub fn remote_branch_page_down(&mut self, page: usize) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.remote_branches.len();
            if total > 0 {
                self.branch_list.remote_branch_selection =
                    (self.branch_list.remote_branch_selection + page).min(total.saturating_sub(1));
            }
        }
    }

    /// Move file selection up in the Files tab.
    pub fn file_list_up(&mut self) {
        self.file_tree.file_list_selection = self.file_tree.file_list_selection.saturating_sub(1);
        self.file_tree.file_content_scroll = 0;
    }

    /// Move file selection down in the Files tab.
    pub fn file_list_down(&mut self) {
        let total = self.file_tree.visible_files.len();
        if total > 0 && self.file_tree.file_list_selection + 1 < total {
            self.file_tree.file_list_selection += 1;
            self.file_tree.file_content_scroll = 0;
        }
    }

    /// Scroll file selection up by page.
    pub fn file_list_page_up(&mut self, page: usize) {
        self.file_tree.file_list_selection =
            self.file_tree.file_list_selection.saturating_sub(page);
        self.file_tree.file_content_scroll = 0;
    }

    /// Scroll file selection down by page.
    pub fn file_list_page_down(&mut self, page: usize) {
        let total = self.file_tree.visible_files.len();
        if total > 0 {
            self.file_tree.file_list_selection =
                (self.file_tree.file_list_selection + page).min(total.saturating_sub(1));
            self.file_tree.file_content_scroll = 0;
        }
    }

    pub fn local_branch_to_top(&mut self) {
        self.branch_list.local_branch_selection = 0;
    }

    pub fn local_branch_to_bottom(&mut self) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.local_branches.len();
            if total > 0 {
                self.branch_list.local_branch_selection = total - 1;
            }
        }
    }

    pub fn remote_branch_to_top(&mut self) {
        self.branch_list.remote_branch_selection = 0;
    }

    pub fn remote_branch_to_bottom(&mut self) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.remote_branches.len();
            if total > 0 {
                self.branch_list.remote_branch_selection = total - 1;
            }
        }
    }

    pub fn file_list_to_top(&mut self) {
        self.file_tree.file_list_selection = 0;
        self.file_tree.file_content_scroll = 0;
    }

    pub fn file_list_to_bottom(&mut self) {
        let total = self.file_tree.visible_files.len();
        if total > 0 {
            self.file_tree.file_list_selection = total - 1;
            self.file_tree.file_content_scroll = 0;
        }
    }

    fn get_logs_matching_indices(&self) -> Vec<usize> {
        if !self.in_logs_ui || self.commit_list.search_query.is_none() {
            return Vec::new();
        }
        match &self.current_detail {
            Some(ItemDetail::Repo { info, .. }) => info
                .commits
                .iter()
                .enumerate()
                .filter(|(_, c)| self.commit_matches_query(c))
                .map(|(i, _)| i)
                .collect(),
            _ => Vec::new(),
        }
    }

    fn get_logs_nav_index(&self, direction: LogsNavDirection) -> Option<usize> {
        let matching_indices = self.get_logs_matching_indices();
        if matching_indices.is_empty() {
            return None;
        }

        let pos_opt = matching_indices.iter().position(|&idx| idx >= self.commit_list.selection);

        match direction {
            LogsNavDirection::Down => {
                if let Some(pos) = pos_opt {
                    if matching_indices[pos] == self.commit_list.selection {
                        if pos + 1 < matching_indices.len() {
                            Some(matching_indices[pos + 1])
                        } else {
                            Some(matching_indices[pos])
                        }
                    } else {
                        Some(matching_indices[pos])
                    }
                } else {
                    matching_indices.last().copied()
                }
            }
            LogsNavDirection::Up => {
                if let Some(pos) = pos_opt {
                    if pos > 0 {
                        Some(matching_indices[pos - 1])
                    } else {
                        Some(matching_indices[0])
                    }
                } else {
                    matching_indices.last().copied()
                }
            }
            LogsNavDirection::PageDown(page) => {
                if let Some(pos) = pos_opt {
                    let target_pos = if matching_indices[pos] == self.commit_list.selection {
                        pos + page
                    } else {
                        pos + page - 1
                    };
                    let final_pos = target_pos.min(matching_indices.len() - 1);
                    Some(matching_indices[final_pos])
                } else {
                    matching_indices.last().copied()
                }
            }
            LogsNavDirection::PageUp(page) => {
                if let Some(pos) = pos_opt {
                    let target_pos = pos.saturating_sub(page);
                    Some(matching_indices[target_pos])
                } else {
                    let last_pos = matching_indices.len() - 1;
                    let target_pos = last_pos.saturating_sub(page);
                    Some(matching_indices[target_pos])
                }
            }
        }
    }

    /// Move commit selection up one row.
    pub fn detail_commit_up(&mut self) {
        if let Some(next_idx) = self.get_logs_nav_index(LogsNavDirection::Up) {
            self.commit_list.selection = next_idx;
        } else {
            self.commit_list.selection = self.commit_list.selection.saturating_sub(1);
        }
        self.status_list.file_selection = 0;
        self.diff.diff_scroll = 0;
        self.refresh_file_diff();
    }

    /// Move commit selection down one row, clamped to the last visible row.
    pub fn detail_commit_down(&mut self) {
        if let Some(next_idx) = self.get_logs_nav_index(LogsNavDirection::Down) {
            self.commit_list.selection = next_idx;
        } else {
            let total = self.commit_total();
            if total > 0 && self.commit_list.selection + 1 < total {
                self.commit_list.selection += 1;
            }
        }
        self.status_list.file_selection = 0;
        self.diff.diff_scroll = 0;
        self.refresh_file_diff();
    }

    /// Jump commit selection up by `page` rows.
    pub fn detail_commit_page_up(&mut self, page: usize) {
        if let Some(next_idx) = self.get_logs_nav_index(LogsNavDirection::PageUp(page)) {
            self.commit_list.selection = next_idx;
        } else {
            self.commit_list.selection = self.commit_list.selection.saturating_sub(page);
        }
        self.status_list.file_selection = 0;
        self.diff.diff_scroll = 0;
        self.refresh_file_diff();
    }

    /// Jump commit selection down by `page` rows, clamped to the last row.
    pub fn detail_commit_page_down(&mut self, page: usize) {
        if let Some(next_idx) = self.get_logs_nav_index(LogsNavDirection::PageDown(page)) {
            self.commit_list.selection = next_idx;
        } else {
            let total = self.commit_total();
            if total > 0 {
                self.commit_list.selection = (self.commit_list.selection + page).min(total - 1);
            }
        }
        self.status_list.file_selection = 0;
        self.diff.diff_scroll = 0;
        self.refresh_file_diff();
    }

    /// Move file selection up one row in the Changed Files panel.
    pub fn detail_file_up(&mut self) {
        self.status_list.file_selection = self.status_list.file_selection.saturating_sub(1);
        self.diff.diff_scroll = 0;
        self.refresh_file_diff();
    }

    /// Move file selection down one row in the Changed Files panel.
    pub fn detail_file_down(&mut self) {
        let total = self.file_total();
        if total > 0 && self.status_list.file_selection + 1 < total {
            self.status_list.file_selection += 1;
        }
        self.diff.diff_scroll = 0;
        self.refresh_file_diff();
    }

    /// Move staging-area file selection up one row (Staged or Unstaged panel).
    pub fn staging_file_up(&mut self) {
        self.status_list.staging_file_selection =
            self.status_list.staging_file_selection.saturating_sub(1);
        self.diff.diff_scroll = 0;
        self.refresh_staging_diff();
    }

    /// Move staging-area file selection down one row (Staged or Unstaged panel).
    pub fn staging_file_down(&mut self) {
        let total = self.staging_file_total();
        if total > 0 && self.status_list.staging_file_selection + 1 < total {
            self.status_list.staging_file_selection += 1;
        }
        self.diff.diff_scroll = 0;
        self.refresh_staging_diff();
    }

    /// Move conflict-area file selection up one row.
    pub fn conflict_file_up(&mut self) {
        self.status_list.conflict_file_selection =
            self.status_list.conflict_file_selection.saturating_sub(1);
        self.diff.diff_scroll = 0;
        self.refresh_staging_diff();
    }

    /// Move conflict-area file selection down one row.
    pub fn conflict_file_down(&mut self) {
        let total = match &self.current_detail {
            Some(ItemDetail::Repo { info, .. }) => info.changes.conflicted.len(),
            _ => 0,
        };
        if total > 0 && self.status_list.conflict_file_selection + 1 < total {
            self.status_list.conflict_file_selection += 1;
        }
        self.diff.diff_scroll = 0;
        self.refresh_staging_diff();
    }

    pub fn diff_hunk_up(&mut self) {
        if self.diff.diff_hunk_selection > 0 {
            self.diff.diff_hunk_selection -= 1;
            self.scroll_to_selected_hunk();
        }
    }

    pub fn diff_hunk_down(&mut self) {
        let hunk_count = self.get_diff_hunk_ranges().len();
        if self.diff.diff_hunk_selection + 1 < hunk_count {
            self.diff.diff_hunk_selection += 1;
            self.scroll_to_selected_hunk();
        }
    }

    pub fn scroll_to_selected_hunk(&mut self) {
        let ranges = self.get_diff_hunk_ranges();
        if let Some(range) = ranges.get(self.diff.diff_hunk_selection) {
            self.diff.diff_scroll = range.start;
        }
    }

    pub fn diff_line_up(&mut self) {
        if self.diff.diff_line_selection > 0 {
            self.diff.diff_line_selection -= 1;
            let ranges = self.get_diff_hunk_ranges();
            for (idx, range) in ranges.iter().enumerate() {
                if range.contains(&self.diff.diff_line_selection) {
                    self.diff.diff_hunk_selection = idx;
                    break;
                }
            }
            if self.diff.diff_line_selection < self.diff.diff_scroll {
                self.diff.diff_scroll = self.diff.diff_line_selection;
            }
        }
    }

    pub fn diff_line_down(&mut self) {
        if self.diff.diff_line_selection + 1 < self.diff.file_diff.len() {
            self.diff.diff_line_selection += 1;
            let ranges = self.get_diff_hunk_ranges();
            for (idx, range) in ranges.iter().enumerate() {
                if range.contains(&self.diff.diff_line_selection) {
                    self.diff.diff_hunk_selection = idx;
                    break;
                }
            }
            if self.diff.diff_line_selection >= self.diff.diff_scroll + 18 {
                self.diff.diff_scroll = self.diff.diff_line_selection.saturating_sub(17);
            }
        }
    }

    pub fn refresh_detail_for_line_action(&mut self) {
        let prev_line_idx = self.diff.diff_line_selection;
        self.refresh_detail();

        let new_len = self.diff.file_diff.len();
        if new_len == 0 {
            self.diff.diff_line_selection = 0;
            self.diff.diff_hunk_selection = 0;
            self.diff.diff_scroll = 0;
            return;
        }

        self.diff.diff_line_selection = prev_line_idx.min(new_len - 1);
        let ranges = self.get_diff_hunk_ranges();
        for (idx, range) in ranges.iter().enumerate() {
            if range.contains(&self.diff.diff_line_selection) {
                self.diff.diff_hunk_selection = idx;
                break;
            }
        }

        if self.diff.diff_line_selection < self.diff.diff_scroll {
            self.diff.diff_scroll = self.diff.diff_line_selection;
        } else if self.diff.diff_line_selection >= self.diff.diff_scroll + 18 {
            self.diff.diff_scroll = self.diff.diff_line_selection.saturating_sub(17);
        }
    }

    pub fn get_file_content_line_count(&self) -> usize {
        if let Some(repo::ItemDetail::Repo { resolved, info }) = &self.current_detail {
            if let Some(selected_item) =
                self.file_tree.visible_files.get(self.file_tree.file_list_selection)
            {
                if selected_item.is_dir {
                    let prefix = if selected_item.full_path.is_empty() {
                        "".to_string()
                    } else {
                        format!("{}/", selected_item.full_path)
                    };
                    let mut direct_children = std::collections::BTreeSet::new();
                    for f_path in info.files.iter() {
                        if f_path.starts_with(&prefix) {
                            let relative = &f_path[prefix.len()..];
                            if let Some(idx) = relative.find('/') {
                                let subdir = &relative[..idx];
                                direct_children.insert((subdir.to_string(), true));
                            } else {
                                direct_children.insert((relative.to_string(), false));
                            }
                        }
                    }
                    if direct_children.is_empty() { 1 } else { direct_children.len() }
                } else {
                    let file_path = resolved.join(&selected_item.full_path);
                    match std::fs::File::open(&file_path) {
                        Ok(file) => {
                            use std::io::Read;
                            let mut buffer = Vec::new();
                            if file.take(100_000).read_to_end(&mut buffer).is_ok() {
                                if let Ok(s) = String::from_utf8(buffer) {
                                    s.lines().count()
                                } else {
                                    1
                                }
                            } else {
                                1
                            }
                        }
                        Err(_) => 1,
                    }
                }
            } else {
                1
            }
        } else {
            1
        }
    }

    /// Scroll the file content panel up by one line.
    pub fn file_content_scroll_up(&mut self) {
        self.file_tree.file_content_scroll = self.file_tree.file_content_scroll.saturating_sub(1);
    }

    /// Scroll the file content panel down by one line.
    pub fn file_content_scroll_down(&mut self) {
        let max = self.get_file_content_line_count().saturating_sub(1);
        if self.file_tree.file_content_scroll < max {
            self.file_tree.file_content_scroll += 1;
        }
    }

    /// Scroll the file content panel up by `page` lines.
    pub fn file_content_scroll_page_up(&mut self, page: usize) {
        self.file_tree.file_content_scroll =
            self.file_tree.file_content_scroll.saturating_sub(page);
    }

    /// Scroll the file content panel down by `page` lines.
    pub fn file_content_scroll_page_down(&mut self, page: usize) {
        let max = self.get_file_content_line_count().saturating_sub(1);
        self.file_tree.file_content_scroll = (self.file_tree.file_content_scroll + page).min(max);
    }

    /// Scroll the graph view up by one line.
    pub fn graph_scroll_up(&mut self) {
        self.graph_scroll = self.graph_scroll.saturating_sub(1);
    }

    /// Scroll the graph view down by one line.
    pub fn graph_scroll_down(&mut self) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let max = info.graph_lines.len().saturating_sub(1);
            if self.graph_scroll < max {
                self.graph_scroll += 1;
            }
        }
    }

    /// Scroll the graph view up by a page.
    pub fn graph_scroll_page_up(&mut self, page: usize) {
        self.graph_scroll = self.graph_scroll.saturating_sub(page);
    }

    /// Scroll the graph view down by a page.
    pub fn graph_scroll_page_down(&mut self, page: usize) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let max = info.graph_lines.len().saturating_sub(1);
            self.graph_scroll = (self.graph_scroll + page).min(max);
        }
    }

    /// Scroll the commit details panel up by one line.
    pub fn commit_details_scroll_up(&mut self) {
        self.commit_list.details_scroll = self.commit_list.details_scroll.saturating_sub(1);
    }

    /// Scroll the commit details panel down by one line.
    pub fn commit_details_scroll_down(&mut self) {
        self.commit_list.details_scroll = self.commit_list.details_scroll.saturating_add(1);
    }

    /// Total number of rows in the Commits panel (dirty row + real commits).
    /// Total number of rows in the Commits panel (dirty row + real commits).
    pub fn commit_total(&self) -> usize {
        match &self.current_detail {
            Some(ItemDetail::Repo { info, .. }) => {
                if self.in_logs_ui {
                    return info.commits.len();
                }
                let dirty = !info.changes.staged.is_empty()
                    || !info.changes.unstaged.is_empty()
                    || !info.changes.untracked.is_empty()
                    || !info.changes.conflicted.is_empty();
                let show_dirty = if dirty {
                    if let Some(ref query) = self.commit_list.search_query {
                        "<uncommitted>".contains(&query.to_lowercase())
                    } else {
                        true
                    }
                } else {
                    false
                };
                let filtered_len = self.get_filtered_commits().len();
                filtered_len + usize::from(show_dirty)
            }
            _ => 0,
        }
    }

    pub fn get_selected_commit(&self) -> Option<&crate::repo::CommitEntry> {
        match &self.current_detail {
            Some(ItemDetail::Repo { info, .. }) => {
                let dirty = !info.changes.staged.is_empty()
                    || !info.changes.unstaged.is_empty()
                    || !info.changes.untracked.is_empty()
                    || !info.changes.conflicted.is_empty();
                let show_dirty = if dirty {
                    if let Some(ref query) = self.commit_list.search_query {
                        "<uncommitted>".contains(&query.to_lowercase())
                    } else {
                        true
                    }
                } else {
                    false
                };
                if show_dirty && self.commit_list.selection == 0 {
                    return None;
                }
                let idx = if show_dirty {
                    self.commit_list.selection.saturating_sub(1)
                } else {
                    self.commit_list.selection
                };
                if self.in_logs_ui {
                    info.commits.get(idx)
                } else {
                    self.get_filtered_commits().get(idx).copied()
                }
            }
            _ => None,
        }
    }

    /// Total files in the currently-selected commit's Changed Files panel.
    pub fn file_total(&self) -> usize {
        self.get_selected_commit().map(|c| c.files.len()).unwrap_or(0)
    }

    pub fn is_uncommitted_selected(&self) -> bool {
        if self.in_logs_ui {
            return false;
        }
        match &self.current_detail {
            Some(ItemDetail::Repo { info, .. }) => {
                let dirty = !info.changes.staged.is_empty()
                    || !info.changes.unstaged.is_empty()
                    || !info.changes.untracked.is_empty()
                    || !info.changes.conflicted.is_empty();
                let show_dirty = if dirty {
                    if let Some(ref query) = self.commit_list.search_query {
                        "<uncommitted>".contains(&query.to_lowercase())
                    } else {
                        true
                    }
                } else {
                    false
                };
                show_dirty && self.commit_list.selection == 0
            }
            _ => false,
        }
    }

    pub fn has_uncommitted_changes(&self) -> bool {
        !self.is_staged_empty() || !self.is_unstaged_empty() || !self.is_conflicted_empty()
    }

    pub fn is_selected_commit_empty(&self) -> bool {
        self.get_selected_commit().map(|c| c.files.is_empty()).unwrap_or(true)
    }

    pub fn ensure_selected_commit_files_loaded(&mut self) {
        let target_oid = self.get_selected_commit().map(|c| c.oid.clone());
        if let Some(oid) = target_oid {
            if let Some(repo::ItemDetail::Repo { resolved, info }) = &mut self.current_detail {
                if let Some(c) = info.commits.iter_mut().find(|c| c.oid == oid) {
                    if c.files.is_empty() {
                        if let Ok(files) = repo::get_commit_files(resolved, &oid) {
                            c.files = files;
                        }
                    }
                }
            }
        }
    }

    pub fn refresh_detail(&mut self) {
        self.resync_detail();
    }

    pub(super) fn clamp_conflict_selection(&mut self) {
        if let Some(ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.changes.conflicted.len();
            if total == 0 {
                self.status_list.conflict_file_selection = 0;
                if self.detail_focus == DetailSection::Conflicts
                    || self.detail_focus == DetailSection::ConflictDiff
                {
                    self.detail_focus = DetailSection::Unstaged;
                }
            } else if self.status_list.conflict_file_selection >= total {
                self.status_list.conflict_file_selection = total.saturating_sub(1);
            }
        }
    }

    pub fn close_detail(&mut self) {
        self.current_detail = None;
        self.commit_list.search_query = None;
        self.loading_repo_path = None;
        self.mode = Mode::Normal;
    }

    pub fn get_filtered_commits(&self) -> Vec<&crate::repo::CommitEntry> {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            if let Some(ref query) = self.commit_list.search_query {
                let q = query.to_lowercase();
                info.commits
                    .iter()
                    .filter(|c| {
                        c.id.to_lowercase().contains(&q)
                            || c.author.to_lowercase().contains(&q)
                            || c.when.to_lowercase().contains(&q)
                            || c.summary.to_lowercase().contains(&q)
                    })
                    .collect()
            } else {
                info.commits.iter().collect()
            }
        } else {
            Vec::new()
        }
    }

    pub fn commit_matches_query(&self, commit: &crate::repo::CommitEntry) -> bool {
        if let Some(ref query) = self.commit_list.search_query {
            if query.is_empty() {
                return false;
            }
            let q = query.to_lowercase();
            let mut matches = false;
            if self.search_columns_sha && commit.id.to_lowercase().contains(&q) {
                matches = true;
            }
            if self.search_columns_message && commit.summary.to_lowercase().contains(&q) {
                matches = true;
            }
            if self.search_columns_author && commit.author.to_lowercase().contains(&q) {
                matches = true;
            }
            if self.search_columns_date && commit.when.to_lowercase().contains(&q) {
                matches = true;
            }
            matches
        } else {
            false
        }
    }

    pub fn clamp_commit_selection(&mut self) {
        let total = self.commit_total();
        if total == 0 {
            self.commit_list.selection = 0;
        } else if self.commit_list.selection >= total {
            self.commit_list.selection = total - 1;
        }
    }

    #[allow(dead_code)]
    pub fn start_commit_search(&mut self) {
        self.input_buffer = self.commit_list.search_query.clone().unwrap_or_default();
        self.mode = Mode::CommitSearchInput;
    }

    pub fn commit_search_input_change(&mut self) {
        self.commit_list.search_query =
            if self.input_buffer.is_empty() { None } else { Some(self.input_buffer.clone()) };
        self.clamp_commit_selection();
        self.status_list.file_selection = 0;
        self.diff.diff_scroll = 0;
        self.refresh_file_diff();
    }

    /// Opens the shortcut help overlay inside the detail view.
    pub fn open_detail_help(&mut self) {
        self.help_scroll = 0;
        self.mode = Mode::DetailHelp;
    }

    /// Closes the detail help overlay and returns to the normal detail view.
    pub fn close_detail_help(&mut self) {
        self.mode = Mode::Detail;
    }

    /// Enters the commit input mode if there are staged changes to commit.
    pub fn start_commit(&mut self) {
        let has_staged = match &self.current_detail {
            Some(ItemDetail::Repo { info, .. }) => info.summary.staged > 0,
            _ => false,
        };
        let has_head = match &self.current_detail {
            Some(ItemDetail::Repo { info, .. }) => info.head.is_some(),
            _ => false,
        };
        if has_staged || has_head {
            self.commit_popup.input_buffer.clear();
            self.commit_popup.editing = true;
            self.commit_popup.amend = false;
            self.commit_input_scroll = 0;
            self.commit_popup.maximized = false;
            self.mode = Mode::CommitInput;
        } else {
            self.status_message = Some("No staged changes to commit".to_string());
        }
    }

    /// Enters the commit input mode for amending the last commit, pre-populating its message.
    pub fn start_commit_amend(&mut self) {
        let has_head = match &self.current_detail {
            Some(ItemDetail::Repo { info, .. }) => info.head.is_some(),
            _ => false,
        };
        if has_head {
            self.commit_popup.input_buffer.clear();
            if let Some(ItemDetail::Repo { resolved, .. }) = &self.current_detail {
                if let Some(last_msg) = repo::get_last_commit_message(resolved) {
                    self.commit_popup.input_buffer = last_msg;
                }
            }
            self.commit_popup.editing = true;
            self.commit_popup.amend = true;
            self.commit_input_scroll = 0;
            self.commit_popup.maximized = false;
            self.mode = Mode::CommitInput;
        } else {
            self.status_message = Some("No commit to amend".to_string());
        }
    }

    /// Transitions from editing the message to confirming the commit.
    pub fn commit_done_editing(&mut self) {
        self.commit_popup.editing = false;
    }

    /// Transitions back to editing the message from confirm state.
    pub fn commit_start_editing(&mut self) {
        self.commit_popup.editing = true;
    }

    pub fn toggle_commit_amend(&mut self) {
        self.commit_popup.amend = !self.commit_popup.amend;
        if self.commit_popup.amend && self.commit_popup.input_buffer.trim().is_empty() {
            if let Some(ItemDetail::Repo { resolved, .. }) = &self.current_detail {
                if let Some(last_msg) = repo::get_last_commit_message(resolved) {
                    self.input_buffer = last_msg;
                }
            }
        }
    }

    pub fn toggle_commit_popup_maximized(&mut self) {
        self.commit_popup.maximized = !self.commit_popup.maximized;
    }

    pub fn commit_input_scroll_up(&mut self) {
        self.commit_input_scroll = self.commit_input_scroll.saturating_sub(1);
    }

    pub fn commit_input_scroll_down(&mut self) {
        self.commit_input_scroll = self.commit_input_scroll.saturating_add(1);
    }

    pub fn toggle_or_edit_setting(&mut self) {
        match self.settings_selected_index {
            0 => {
                self.settings_editing = true;
                self.input_buffer = self.config.poll_interval_ms.to_string();
            }
            1 => {
                self.config.sort_by = match self.config.sort_by {
                    SortOrder::Custom => SortOrder::Alphabetical,
                    SortOrder::Alphabetical => SortOrder::RecentVisit,
                    SortOrder::RecentVisit => SortOrder::LatestChanges,
                    SortOrder::LatestChanges => SortOrder::Custom,
                };
                if self.config.sort_by != SortOrder::Custom {
                    self.sort_items_in_place();
                }
                self.persist("Sort mode updated");
            }
            2 => {
                self.config.sort_reverse = !self.config.sort_reverse;
                if self.config.sort_by != SortOrder::Custom {
                    self.sort_items_in_place();
                }
                self.persist("Sort direction updated");
            }
            3 => {
                self.settings_theme_list = self.get_available_themes();
                self.settings_theme_index = self
                    .settings_theme_list
                    .iter()
                    .position(|t| t == &self.config.theme_name)
                    .unwrap_or(0);
                self.settings_editing = true;
            }
            4 => {
                self.settings_editing = true;
                self.input_buffer = self.config.fzf.max_depth.to_string();
            }
            5 => {
                self.settings_editing = true;
                self.input_buffer = self.config.fzf.start_dir.clone();
            }
            6 => {
                self.settings_editing = true;
                self.input_buffer = self.config.max_commits.to_string();
            }
            7 => {
                self.settings_editing = true;
                self.input_buffer = self.config.page_size.to_string();
            }
            8 => {
                self.settings_editing = true;
                self.input_buffer = self.config.fzf.excludes.join(",");
            }
            9 => {
                self.settings_editing = true;
                self.input_buffer = self.config.git_app.clone();
            }
            10 => {
                self.config.fzf.git_only = !self.config.fzf.git_only;
                self.persist("FZF Git Only updated");
            }
            11 => {
                self.config.fzf.enabled = !self.config.fzf.enabled;
                self.persist("Use FZF updated");
            }
            12 => {
                self.config.compatibility_mode = !self.config.compatibility_mode;
                self.persist("Compatibility Mode updated");
            }
            13 => {
                self.config.resync_on_tab_change = !self.config.resync_on_tab_change;
                self.persist("Resync on Tab Change updated");
            }
            _ => {}
        }
    }

    pub fn commit_settings_edit(&mut self) {
        let trimmed = self.input_buffer.trim();
        match self.settings_selected_index {
            0 => {
                if let Ok(val) = trimmed.parse::<u64>() {
                    if val >= 10 {
                        self.config.poll_interval_ms = val;
                        self.persist("Poll interval updated");
                        self.settings_editing = false;
                        self.commit_popup.input_buffer.clear();
                    } else {
                        self.status_message =
                            Some("Poll interval must be at least 10ms".to_string());
                    }
                } else {
                    self.status_message = Some("Invalid integer".to_string());
                }
            }
            3 => {
                if self.settings_theme_index < self.settings_theme_list.len() {
                    let selected_theme =
                        self.settings_theme_list[self.settings_theme_index].clone();
                    self.config.theme_name = selected_theme.clone();
                    let themes_dir =
                        self.config_path.parent().unwrap_or(&self.config_path).join("themes");
                    let theme_path = themes_dir.join(format!("{}.theme", selected_theme));
                    if theme_path.exists() {
                        if let Ok(theme_contents) = std::fs::read_to_string(&theme_path) {
                            if let Ok(theme) =
                                toml::from_str::<crate::config::ThemeConfig>(&theme_contents)
                            {
                                self.config.theme = theme;
                                crate::ui::update_theme(&self.config.theme);
                                self.persist("Theme updated");
                                self.settings_editing = false;
                                return;
                            }
                        }
                    }
                    crate::ui::update_theme(&self.config.theme);
                    self.settings_editing = false;
                    self.persist("Theme updated");
                }
            }
            4 => {
                if let Ok(val) = trimmed.parse::<usize>() {
                    self.config.fzf.max_depth = val;
                    self.persist("FZF max depth updated");
                    self.settings_editing = false;
                    self.commit_popup.input_buffer.clear();
                } else {
                    self.status_message = Some("Invalid integer".to_string());
                }
            }
            5 => {
                self.config.fzf.start_dir = trimmed.to_string();
                self.persist("FZF start directory updated");
                self.settings_editing = false;
                self.commit_popup.input_buffer.clear();
            }
            6 => {
                if let Ok(val) = trimmed.parse::<usize>() {
                    self.config.max_commits = val;
                    self.persist("Max commits updated");
                    self.settings_editing = false;
                    self.commit_popup.input_buffer.clear();
                } else {
                    self.status_message = Some("Invalid integer".to_string());
                }
            }
            7 => {
                if let Ok(val) = trimmed.parse::<usize>() {
                    if val >= 1 {
                        self.config.page_size = val;
                        self.persist("Page size updated");
                        self.settings_editing = false;
                        self.commit_popup.input_buffer.clear();
                    } else {
                        self.status_message = Some("Page size must be at least 1".to_string());
                    }
                } else {
                    self.status_message = Some("Invalid integer".to_string());
                }
            }
            8 => {
                self.config.fzf.excludes = trimmed
                    .split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect();
                self.persist("FZF exclude folders updated");
                self.settings_editing = false;
                self.commit_popup.input_buffer.clear();
            }
            9 => {
                let trimmed_app = trimmed.to_string();
                if !trimmed_app.is_empty() {
                    self.config.git_app = trimmed_app;
                    self.persist("Preferred Git Client updated");
                    self.settings_editing = false;
                    self.commit_popup.input_buffer.clear();
                } else {
                    self.status_message = Some("Preferred Git Client cannot be empty".to_string());
                }
            }
            _ => {}
        }
    }

    pub fn cancel_settings_edit(&mut self) {
        self.settings_editing = false;
        self.commit_popup.input_buffer.clear();
    }

    pub fn get_available_themes(&self) -> Vec<String> {
        let mut themes = vec!["default".to_string()];
        let themes_dir = self.config_path.parent().unwrap_or(&self.config_path).join("themes");
        if themes_dir.exists() {
            if let Ok(entries) = std::fs::read_dir(themes_dir) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if path.is_file() && path.extension().is_some_and(|ext| ext == "theme") {
                        if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                            let theme_name = stem.to_string();
                            if theme_name != "default" && !themes.contains(&theme_name) {
                                themes.push(theme_name);
                            }
                        }
                    }
                }
            }
        }
        themes.sort();
        themes
    }

    pub fn cancel_input(&mut self) {
        self.commit_popup.input_buffer.clear();
        self.mode = Mode::Normal;
    }

    pub fn input_char(&mut self, c: char) {
        self.input_buffer.push(c);
    }

    pub fn input_backspace(&mut self) {
        self.input_buffer.pop();
    }

    pub(super) fn canonical_path(p: &std::path::Path) -> PathBuf {
        match std::fs::canonicalize(p) {
            Ok(canon) => canon,
            Err(_) => p.to_path_buf(),
        }
    }

    pub fn start_bulk_add(&mut self) {
        crate::debug_log::info("Initiating bulk repository add");
        if !self.config.fzf.enabled {
            self.mode = Mode::BulkAddInput;
            self.commit_popup.input_buffer.clear();
        } else if !self.is_fzf_installed() {
            self.mode = Mode::BulkAddInput;
            self.commit_popup.input_buffer.clear();
            self.status_message =
                Some("fzf is not installed. Falling back to manual bulk add.".to_string());
        } else {
            self.pending_bulk_fzf = true;
        }
    }

    pub fn commit_bulk_add(&mut self) {
        let trimmed = self.input_buffer.trim().to_string();
        self.commit_popup.input_buffer.clear();
        self.mode = Mode::Normal;
        if !trimmed.is_empty() {
            self.bulk_add_path(trimmed);
        }
    }

    pub fn bulk_add_path(&mut self, path: String) {
        let trimmed = path.trim().to_string();
        if trimmed.is_empty() {
            return;
        }

        let base_path = repo::expand_tilde(&trimmed);
        if !base_path.exists() {
            self.set_error(format!("Directory does not exist: {}", trimmed));
            return;
        }
        if !base_path.is_dir() {
            self.set_error(format!("Path is not a directory: {}", trimmed));
            return;
        }

        let entries = match std::fs::read_dir(&base_path) {
            Ok(read) => read,
            Err(e) => {
                self.set_error(format!("Failed to read directory: {}", e));
                return;
            }
        };

        let mut added_paths = Vec::new();
        let git_only = self.config.fzf.git_only;

        for entry_opt in entries {
            let entry = match entry_opt {
                Ok(e) => e,
                Err(_) => continue,
            };
            let path = entry.path();
            if path.is_dir() {
                let show_dir = if git_only { path.join(".git").exists() } else { true };
                if show_dir {
                    if let Some(sub_name) = path.file_name().and_then(|n| n.to_str()) {
                        let mut base_str = trimmed.clone();
                        if !base_str.ends_with(std::path::MAIN_SEPARATOR) {
                            base_str.push(std::path::MAIN_SEPARATOR);
                        }
                        let path_to_add = format!("{}{}", base_str, sub_name);
                        added_paths.push(path_to_add);
                    }
                }
            }
        }

        added_paths.sort();

        if added_paths.is_empty() {
            self.status_message = Some("No matching directories found to add".to_string());
            return;
        }

        let mut newly_added_count = 0;
        let mut first_new_path = None;
        for path_str in added_paths {
            let trimmed_path = path_str.trim().to_string();
            let new_expanded = repo::expand_tilde(&trimmed_path);
            let new_canonical = Self::canonical_path(&new_expanded);

            let already_exists = self.config.items.iter().any(|item| {
                let item_expanded = repo::expand_tilde(item);
                item.trim() == trimmed_path
                    || item_expanded == new_expanded
                    || Self::canonical_path(&item_expanded) == new_canonical
            });

            if !already_exists {
                let status = repo::inspect_summary(&trimmed_path);
                self.statuses.push(status);
                self.config.items.push(trimmed_path.clone());
                self.original_items.push(trimmed_path.clone());
                if first_new_path.is_none() {
                    first_new_path = Some(trimmed_path);
                }
                newly_added_count += 1;
            }
        }

        if newly_added_count > 0 {
            self.sort_items_in_place();
            self.repo_search_query = None;
            if let Some(ref target) = first_new_path {
                if let Some(pos) = self.config.items.iter().position(|x| x == target) {
                    self.selected_index = pos;
                }
            }
            self.persist(&format!("Added {} directories", newly_added_count));
        } else {
            self.status_message = Some("All discovered directories were already added".to_string());
        }
    }

    pub fn start_import_clone(&mut self) {
        let url = self.import_url.trim().to_string();
        let dest = self.import_dest.trim().to_string();
        let name = self.import_name.trim().to_string();

        if url.is_empty() || dest.is_empty() {
            self.set_error("Source URL and Destination path cannot be empty".to_string());
            self.mode = Mode::Normal;
            return;
        }

        let mut dest_path = repo::expand_tilde(&dest);
        if !name.is_empty() {
            dest_path.push(&name);
        }
        let dest_str = dest_path.to_string_lossy().to_string();

        self.fetching = true;
        self.status_message = Some(format!("Cloning {}...", url));
        self.mode = Mode::Normal;

        let tx = self.tx.clone();
        std::thread::spawn(move || {
            let res = (|| -> Result<String, String> {
                let dest_expanded = repo::expand_tilde(&dest_str);
                let _ = std::fs::create_dir_all(&dest_expanded);

                let mut cmd = std::process::Command::new("git");
                cmd.env("GIT_TERMINAL_PROMPT", "0")
                    .env("GIT_SSH_COMMAND", "ssh -o StrictHostKeyChecking=accept-new");
                cmd.arg("clone").arg(&url).arg(&dest_expanded);

                let output = cmd.output().map_err(|e| e.to_string())?;
                if output.status.success() {
                    Ok(format!("CLONE_SUCCESS:{}", dest_str))
                } else {
                    let err = String::from_utf8_lossy(&output.stderr).trim().to_string();
                    Err(format!("Clone failed: {}", err))
                }
            })();

            match res {
                Ok(msg) => {
                    let _ = tx.send(msg);
                }
                Err(e) => {
                    let _ = tx.send(format!("Failed to clone: {}", e));
                }
            }
        });
    }

    pub fn close_dialog(&mut self) {
        self.mode = Mode::Normal;
    }

    /// Persists `self.config` and records a status message (success or
    /// the save error) for the next render.
    pub(super) fn persist(&mut self, success_msg: &str) {
        self.status_message = match save_config(&self.config, &self.config_path) {
            Ok(()) => Some(success_msg.to_string()),
            Err(e) => Some(format!("Save failed: {}", e)),
        };
        self.setup_watcher();
    }

    /// Rebuilds the flattened list of visible tree nodes in the Files tab.
    pub fn rebuild_visible_files(&mut self) {
        let mut visible_files = Vec::new();
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let mut root = TempNode {
                name: "".to_string(),
                full_path: "".to_string(),
                is_dir: true,
                children: std::collections::BTreeMap::new(),
            };

            for file_path in info.files.iter() {
                let parts: Vec<&str> = file_path.split('/').collect();
                let mut current = &mut root;
                let mut accumulated = String::new();
                for (i, part) in parts.iter().enumerate() {
                    if !accumulated.is_empty() {
                        accumulated.push('/');
                    }
                    accumulated.push_str(part);

                    let is_last = i == parts.len() - 1;
                    let entry =
                        current.children.entry((*part).to_string()).or_insert_with(|| TempNode {
                            name: (*part).to_string(),
                            full_path: accumulated.clone(),
                            is_dir: !is_last,
                            children: std::collections::BTreeMap::new(),
                        });
                    current = entry;
                }
            }

            fn flatten_tree(
                node: &TempNode,
                depth: usize,
                expanded_folders: &std::collections::HashSet<String>,
                out: &mut Vec<FileTreeItem>,
            ) {
                let mut child_nodes: Vec<&TempNode> = node.children.values().collect();
                child_nodes.sort_by(|a, b| match (a.is_dir, b.is_dir) {
                    (true, false) => std::cmp::Ordering::Less,
                    (false, true) => std::cmp::Ordering::Greater,
                    _ => a.name.cmp(&b.name),
                });

                for child in child_nodes {
                    let is_expanded = child.is_dir && expanded_folders.contains(&child.full_path);
                    out.push(FileTreeItem {
                        name: child.name.clone(),
                        full_path: child.full_path.clone(),
                        is_dir: child.is_dir,
                        depth,
                        is_expanded,
                    });
                    if is_expanded {
                        flatten_tree(child, depth + 1, expanded_folders, out);
                    }
                }
            }

            flatten_tree(&root, 0, &self.file_tree.expanded_folders, &mut visible_files);
        }
        self.file_tree.visible_files = visible_files;
    }

    /// Expand the selected folder in the Files tab.

    pub fn toggle_folder_expanded(&mut self) {
        if let Some(item) =
            self.file_tree.visible_files.get(self.file_tree.file_list_selection).cloned()
        {
            if item.is_dir {
                if self.file_tree.expanded_folders.contains(&item.full_path) {
                    self.collapse_selected_folder();
                } else {
                    self.expand_selected_folder();
                }
            } else {
                self.detail_focus = DetailSection::FileContent;
            }
        }
    }

    pub fn collapse_all_folders(&mut self) {
        self.file_tree.expanded_folders.clear();
        self.rebuild_visible_files();
    }

    pub fn expand_selected_folder(&mut self) {
        if let Some(item) = self.file_tree.visible_files.get(self.file_tree.file_list_selection) {
            if item.is_dir {
                self.file_tree.expanded_folders.insert(item.full_path.clone());
                self.rebuild_visible_files();
            }
        }
    }

    /// Collapse the selected folder in the Files tab.
    pub fn collapse_selected_folder(&mut self) {
        if let Some(item) = self.file_tree.visible_files.get(self.file_tree.file_list_selection) {
            if item.is_dir {
                self.file_tree.expanded_folders.remove(&item.full_path);
                self.rebuild_visible_files();
            }
        }
    }

    /// Shift panel focus to the left.
    pub fn move_focus_left(&mut self) {
        if self.detail_tab == 3 {
            self.detail_focus = DetailSection::LocalBranches;
        }
    }

    /// Shift panel focus to the right.
    pub fn move_focus_right(&mut self) {
        if self.detail_tab == 3 {
            self.detail_focus = DetailSection::RemoteBranches;
        }
    }

    /// Sets the default active panel focus when switching tabs.
    pub fn set_default_focus_for_tab(&mut self) {
        match self.detail_tab {
            0 => self.detail_focus = DetailSection::Commits,
            1 => {
                self.detail_focus = DetailSection::Files;
                self.file_tree.file_content_scroll = 0;
            }
            3 => self.detail_focus = DetailSection::LocalBranches,
            4 => {
                self.detail_focus = DetailSection::LocalTags;
            }
            5 => {
                self.detail_focus = DetailSection::Remotes;
                let remote_name =
                    if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
                        info.remotes
                            .get(self.branch_list.remote_selection)
                            .or_else(|| info.remotes.first())
                            .map(|r| r.name.clone())
                    } else {
                        None
                    };
                if let Some(name) = remote_name {
                    self.fetch_remote(&name);
                }
            }
            6 => {
                self.detail_focus = DetailSection::Stashes;
                self.stash_list.stash_file_selection = 0;
                self.refresh_file_diff();
            }
            _ => {}
        }
    }

    pub fn remote_picker_up(&mut self) {
        self.remote_picker_selection = self.remote_picker_selection.saturating_sub(1);
    }

    pub fn remote_picker_down(&mut self) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.remotes.len();
            if total > 0 && self.remote_picker_selection + 1 < total {
                self.remote_picker_selection += 1;
            }
        }
    }

    pub fn local_tag_up(&mut self) {
        self.tag_list.local_tag_selection = self.tag_list.local_tag_selection.saturating_sub(1);
    }

    pub fn local_tag_down(&mut self) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.local_tags.len();
            if total > 0 && self.tag_list.local_tag_selection + 1 < total {
                self.tag_list.local_tag_selection += 1;
            }
        }
    }

    pub fn local_tag_page_up(&mut self, page: usize) {
        self.tag_list.local_tag_selection = self.tag_list.local_tag_selection.saturating_sub(page);
    }

    pub fn local_tag_page_down(&mut self, page: usize) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.local_tags.len();
            if total > 0 {
                self.tag_list.local_tag_selection =
                    (self.tag_list.local_tag_selection + page).min(total.saturating_sub(1));
            }
        }
    }

    pub fn remote_up(&mut self) {
        self.branch_list.remote_selection = self.branch_list.remote_selection.saturating_sub(1);
    }

    pub fn remote_down(&mut self) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.remotes.len();
            if total > 0 && self.branch_list.remote_selection + 1 < total {
                self.branch_list.remote_selection += 1;
            }
        }
    }

    pub fn remote_page_up(&mut self, page: usize) {
        self.branch_list.remote_selection = self.branch_list.remote_selection.saturating_sub(page);
    }

    pub fn remote_page_down(&mut self, page: usize) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.remotes.len();
            if total > 0 {
                self.branch_list.remote_selection =
                    (self.branch_list.remote_selection + page).min(total.saturating_sub(1));
            }
        }
    }

    pub fn stash_up(&mut self) {
        self.stash_list.stash_selection = self.stash_list.stash_selection.saturating_sub(1);
        self.stash_list.stash_file_selection = 0;
        self.refresh_file_diff();
    }

    pub fn stash_down(&mut self) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.stashes.len();
            if total > 0 && self.stash_list.stash_selection + 1 < total {
                self.stash_list.stash_selection += 1;
                self.stash_list.stash_file_selection = 0;
                self.refresh_file_diff();
            }
        }
    }

    pub fn stash_page_up(&mut self, page: usize) {
        self.stash_list.stash_selection = self.stash_list.stash_selection.saturating_sub(page);
        self.stash_list.stash_file_selection = 0;
        self.refresh_file_diff();
    }

    pub fn stash_page_down(&mut self, page: usize) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.stashes.len();
            if total > 0 {
                self.stash_list.stash_selection =
                    (self.stash_list.stash_selection + page).min(total.saturating_sub(1));
                self.stash_list.stash_file_selection = 0;
                self.refresh_file_diff();
            }
        }
    }

    pub fn stash_file_up(&mut self) {
        self.stash_list.stash_file_selection =
            self.stash_list.stash_file_selection.saturating_sub(1);
        self.refresh_file_diff();
    }

    pub fn stash_file_down(&mut self) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            if let Some(stash) = info.stashes.get(self.stash_list.stash_selection) {
                let total = stash.files.len();
                if total > 0 && self.stash_list.stash_file_selection + 1 < total {
                    self.stash_list.stash_file_selection += 1;
                    self.refresh_file_diff();
                }
            }
        }
    }

    pub fn stash_file_page_up(&mut self, page: usize) {
        self.stash_list.stash_file_selection =
            self.stash_list.stash_file_selection.saturating_sub(page);
        self.refresh_file_diff();
    }

    pub fn stash_file_page_down(&mut self, page: usize) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            if let Some(stash) = info.stashes.get(self.stash_list.stash_selection) {
                let total = stash.files.len();
                if total > 0 {
                    self.stash_list.stash_file_selection =
                        (self.stash_list.stash_file_selection + page).min(total.saturating_sub(1));
                    self.refresh_file_diff();
                }
            }
        }
    }

    pub fn local_tag_to_top(&mut self) {
        self.tag_list.local_tag_selection = 0;
    }

    pub fn local_tag_to_bottom(&mut self) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.local_tags.len();
            if total > 0 {
                self.tag_list.local_tag_selection = total - 1;
            }
        }
    }

    pub fn remote_to_top(&mut self) {
        self.branch_list.remote_selection = 0;
    }

    pub fn remote_to_bottom(&mut self) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.remotes.len();
            if total > 0 {
                self.branch_list.remote_selection = total - 1;
            }
        }
    }

    pub fn stash_to_top(&mut self) {
        self.stash_list.stash_selection = 0;
        self.stash_list.stash_file_selection = 0;
        self.refresh_file_diff();
    }

    pub fn stash_to_bottom(&mut self) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let total = info.stashes.len();
            if total > 0 {
                self.stash_list.stash_selection = total - 1;
                self.stash_list.stash_file_selection = 0;
                self.refresh_file_diff();
            }
        }
    }

    pub fn stash_file_to_top(&mut self) {
        self.stash_list.stash_file_selection = 0;
        self.refresh_file_diff();
    }

    pub fn stash_file_to_bottom(&mut self) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            if let Some(stash) = info.stashes.get(self.stash_list.stash_selection) {
                let total = stash.files.len();
                if total > 0 {
                    self.stash_list.stash_file_selection = total - 1;
                    self.refresh_file_diff();
                }
            }
        }
    }

    pub fn graph_scroll_to_top(&mut self) {
        self.graph_scroll = 0;
    }

    pub fn graph_scroll_to_bottom(&mut self) {
        if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let max = info.graph_lines.len().saturating_sub(1);
            self.graph_scroll = max;
        }
    }

    pub fn file_content_scroll_to_top(&mut self) {
        self.file_tree.file_content_scroll = 0;
    }

    pub fn file_content_scroll_to_bottom(&mut self) {
        let max = self.get_file_content_line_count().saturating_sub(1);
        self.file_tree.file_content_scroll = max;
    }

    pub fn detail_commit_to_top(&mut self) {
        if self.in_logs_ui && self.commit_list.search_query.is_some() {
            let matching_indices = self.get_logs_matching_indices();
            if let Some(&first) = matching_indices.first() {
                self.commit_list.selection = first;
            }
        } else {
            self.commit_list.selection = 0;
        }
        self.status_list.file_selection = 0;
        self.diff.diff_scroll = 0;
        self.refresh_file_diff();
    }

    pub fn detail_commit_to_bottom(&mut self) {
        if self.in_logs_ui && self.commit_list.search_query.is_some() {
            let matching_indices = self.get_logs_matching_indices();
            if let Some(&last) = matching_indices.last() {
                self.commit_list.selection = last;
            }
        } else {
            let total = self.commit_total();
            if total > 0 {
                self.commit_list.selection = total - 1;
            }
        }
        self.status_list.file_selection = 0;
        self.diff.diff_scroll = 0;
        self.refresh_file_diff();
    }

    pub fn yank_selected_commit_hash(&mut self) {
        if self.is_uncommitted_selected() {
            self.status_message = Some("Cannot yank uncommitted changes".to_string());
            return;
        }
        let hash_to_copy = if let Some(repo::ItemDetail::Repo { info, .. }) = &self.current_detail {
            let dirty = !info.changes.staged.is_empty()
                || !info.changes.unstaged.is_empty()
                || !info.changes.untracked.is_empty()
                || !info.changes.conflicted.is_empty();
            let commit_idx = if dirty {
                self.commit_list.selection.saturating_sub(1)
            } else {
                self.commit_list.selection
            };
            info.commits.get(commit_idx).map(|commit| commit.oid.clone())
        } else {
            None
        };

        if let Some(hash) = hash_to_copy {
            match copy_to_clipboard(&hash) {
                Ok(()) => {
                    self.status_message = Some(format!("Copied hash {:.7} to clipboard", hash));
                }
                Err(e) => {
                    self.status_message = Some(format!("Failed to copy to clipboard: {}", e));
                }
            }
        }
    }

    pub fn help_scroll_up(&mut self) {
        self.help_scroll = self.help_scroll.saturating_sub(1);
    }

    pub fn help_scroll_down(&mut self) {
        self.help_scroll = self.help_scroll.saturating_add(1);
    }

    pub fn help_scroll_page_up(&mut self, amount: usize) {
        self.help_scroll = self.help_scroll.saturating_sub(amount);
    }

    pub fn help_scroll_page_down(&mut self, amount: usize) {
        self.help_scroll = self.help_scroll.saturating_add(amount);
    }

    pub fn help_scroll_to_top(&mut self) {
        self.help_scroll = 0;
    }

    pub fn help_scroll_to_bottom(&mut self) {
        self.help_scroll = usize::MAX;
    }
}