gitwig 2.4.8

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
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
//! Application state and the main run loop.
//!
//! `App` owns everything mutable about a session: the current config, where
//! to persist it back to, where the cursor is, what mode we're in, and any
//! transient status message. The drawing layer (`ui`) reads `App` but never
//! mutates it. Key handling (`input`) calls back into `App` methods so the
//! state-mutation logic stays in one place.

use std::error::Error;
use std::path::PathBuf;

use crossterm::event::{self, Event};
use ratatui::Terminal;
use ratatui::layout::{Margin, Rect};

use crate::config::{Config, SortOrder, save_config};
use crate::input;
use crate::repo::{self, ItemDetail, ItemStatus};
use crate::ui;
use crate::ui_detail::DetailAreas;

/// Height of each item row inside the bordered list area.
/// Borders (top + bottom) take 2 rows; the remaining 2 inner rows hold
/// the item path and the branch name respectively.
pub const ITEM_HEIGHT: u16 = 4;

/// What operation the remote picker was opened for.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum RemotePickerAction {
    PushBranch,
    PushTag,
    PushAllTags,
    DeleteRemoteTag,
    FetchRemote,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum GlobalFilter {
    Dirty,
    Ahead,
    Stale,
}

/// Interaction modes for the item list.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mode {
    /// Browsing the list.
    Normal,
    #[allow(dead_code)]
    Adding,
    /// Typing replacement text for the selected item.
    Editing,
    /// Asking the user to confirm deletion of the selected item.
    ConfirmDelete,
    /// Showing the full shortcut reference as a centered overlay.
    Help,
    /// Showing the full-screen detail view for the selected item.
    Detail,
    /// Showing the shortcut reference overlay inside the detail view.
    DetailHelp,
    /// Typing a commit message.
    CommitInput,
    /// Typing a branch name to create.
    BranchCreateInput,
    /// Typing a tag name to create.
    TagCreateInput,
    /// Confirming deletion of a branch.
    BranchDeleteConfirm,
    /// Confirming push of a branch.
    BranchPushConfirm,
    /// Confirming deletion of a tag.
    TagDeleteConfirm,
    /// Confirming push of a tag.
    TagPushConfirm,
    /// Confirming push of all tags.
    TagPushAllConfirm,
    /// Confirming deletion of a stash.
    StashDeleteConfirm,
    /// Confirming apply of a stash.
    StashApplyConfirm,
    /// Typing a stash name/message to create.
    StashCreateInput,
    /// Showing the stashing UI panel with options and file list.
    StashingUI,
    /// Picking a remote when multiple are available.
    RemotePicker,
    /// Typing a search query for commits.
    #[allow(dead_code)]
    CommitSearchInput,
    /// Confirming merge of a branch.
    BranchMergeConfirm,
    /// Confirming rebase onto a branch.
    BranchRebaseConfirm,
    /// Confirming interactive rebase onto a branch.
    BranchInteractiveRebaseConfirm,
    /// Confirming discarding changes in a file.
    DiscardChangesConfirm,
    /// Inspecting a selected commit.
    Inspect,
    /// Settings page.
    Settings,
    /// Debug logs view.
    DebugLogs,
    /// Typing an import URL.
    ImportUrlInput,
    /// Typing an import destination path.
    ImportDestInput,
    /// Typing an import name.
    ImportNameInput,
    /// Typing a directory to bulk add its subdirectories.
    BulkAddInput,
    /// Choosing which columns to filter on.
    SearchColumnPicker,
    /// Typing a remote name to add.
    RemoteAddNameInput,
    /// Typing a remote URL to add.
    RemoteAddUrlInput,
    /// Confirming deletion of a remote.
    RemoteDeleteConfirm,
    /// logs UI with commits only.
    Logs,
    /// Search input in the logs UI.
    LogsSearchInput,
    /// Confirming checkout of a branch.
    BranchCheckoutConfirm,
    /// Confirming checkout of a tag.
    TagCheckoutConfirm,
    /// Confirming checkout of a commit.
    CommitCheckoutConfirm,
    /// Search input for repositories on the home page.
    RepoSearchInput,
    /// Confirming aborting of a merge.
    MergeAbortConfirm,
    /// Confirming continuation of a merge.
    MergeContinueConfirm,
    /// Showing the about popup / creator profile.
    About,
    /// Confirming cherry-pick of a commit.
    CherryPickConfirm,
    /// Confirming revert of a commit.
    RevertConfirm,
    /// Per-file history view.
    FileHistory,
    /// Editing repository labels.
    LabelInput,
    /// Choosing custom settings for the repository inside Overview.
    RepoSettings,
    /// Confirming self-update of the application.
    UpdateConfirm,
    /// Typing a branch name for a new worktree.
    WorktreeAddBranchInput,
    /// Typing a path for a new worktree.
    WorktreeAddPathInput,
    /// Typing a lock reason for a worktree.
    WorktreeLockReasonInput,
    /// Confirming removal options of a worktree.
    WorktreeRemoveConfirm,
    /// Showing the repository overview in a full window popup.
    Overview,
    /// Typing a URL for a new submodule.
    SubmoduleAddUrlInput,
    /// Typing a path for a new submodule.
    SubmoduleAddPathInput,
    /// Confirming deletion of a submodule.
    SubmoduleDeleteConfirm,
    /// Showing the signs and symbols legend popup.
    Legend,
    /// Floating popup with ranked fuzzy matches for repository navigation.
    RepoJump,
    /// Floating popup for built-in repository scanning and selection.
    RepoScanPicker,
    /// Floating popup for built-in directory scanning for bulk adding.
    BulkAddScanPicker,
    /// Floating popup for fuzzy branch search.
    BranchSearchInput,
    /// Floating popup for fuzzy file search fallback.
    FileSearchInput,
    ForgeCommentPathInput,
    ForgeCommentLineInput,
    ForgeCommentBodyInput,
    /// Floating popup for fuzzy commit search in logs view.
    CommitFuzzySearch,
    /// Floating popup for fuzzy tag search.
    TagSearchInput,
    /// Prompting for labels when adding a single repository.
    AddRepoLabelInput,
    /// Prompting for labels when bulk adding repositories.
    BulkAddRepoLabelInput,
    /// Prompting for labels when adding a cloned repository.
    CloneRepoLabelInput,
    /// Searching across all tracked repositories.
    GlobalSearch,
    /// Popup shown when the selected item is not a git repository.
    NotGitRepo,
}

/// Which panel in the detail view currently has keyboard focus.
/// Tab cycles through them in order.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum DetailSection {
    Commits,
    Staged,
    Unstaged,
    Conflicts,
    CommitDetails,
    StagingDetails,
    ConflictDiff,
    LocalBranches,
    RemoteBranches,
    LocalTags,
    RemoteTags,
    Files,
    FileContent,
    Remotes,
    Stashes,
    StashedFiles,
    Worktrees,
    Submodules,
    Reflog,
    ForgeIssues,
    ForgeIssueDetails,
    ForgePRs,
    ForgePRDetails,
}

/// Resizable splitter identifier.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Splitter {
    InspectHorizontal,  // Left panel vs Right (Diff) panel
    InspectVertical,    // Top sub-panel vs Bottom sub-panel in left panel
    WorkspaceMain,      // Commits list vs staging/files details (vertical split, top/bottom)
    FilesHorizontal,    // Files view: left (tree) vs right (preview)
    BranchesHorizontal, // Branches view: left (local) vs right (remote)
    StashesHorizontal,  // Stashes view: left (lists) vs right (diff)
    StashesVertical,    // Stashes view: top list vs bottom files list
    OverviewHorizontal, // Overview view: left (info) vs right (stats)
    ForgeVertical,      // Forge view: top (issues list) vs bottom (details)
    ForgePRVertical,    // Forge PR view: top (PRs list) vs bottom (details)
    CommitPopupWidth,   // Dragging vertical border of commit popup
    CommitPopupHeight,  // Dragging horizontal border of commit popup
    CommitPopupBoth,    // Dragging corner of commit popup
}

impl DetailSection {
    /// Advance to the next section in the cycle.
    pub fn next(self) -> Self {
        match self {
            Self::Commits => Self::Staged,
            Self::Staged => Self::Unstaged,
            Self::Unstaged => Self::Conflicts,
            Self::Conflicts => Self::CommitDetails,
            Self::CommitDetails => Self::StagingDetails,
            Self::StagingDetails => Self::ConflictDiff,
            Self::ConflictDiff => Self::Commits,
            Self::LocalBranches => Self::RemoteBranches,
            Self::RemoteBranches => Self::LocalBranches,
            Self::LocalTags => Self::RemoteTags,
            Self::RemoteTags => Self::LocalTags,
            Self::Files => Self::FileContent,
            Self::FileContent => Self::Files,
            Self::Remotes => Self::Remotes,
            Self::Stashes => Self::Stashes,
            Self::StashedFiles => Self::StashedFiles,
            Self::Worktrees => Self::Worktrees,
            Self::Submodules => Self::Submodules,
            Self::Reflog => Self::Reflog,
            Self::ForgeIssues => Self::ForgeIssueDetails,
            Self::ForgeIssueDetails => Self::ForgeIssues,
            Self::ForgePRs => Self::ForgePRDetails,
            Self::ForgePRDetails => Self::ForgePRs,
        }
    }

    /// Move back to the previous section in the cycle.
    pub fn prev(self) -> Self {
        match self {
            Self::Commits => Self::ConflictDiff,
            Self::Staged => Self::Commits,
            Self::Unstaged => Self::Staged,
            Self::Conflicts => Self::Unstaged,
            Self::CommitDetails => Self::Conflicts,
            Self::StagingDetails => Self::CommitDetails,
            Self::ConflictDiff => Self::StagingDetails,
            Self::LocalBranches => Self::RemoteBranches,
            Self::RemoteBranches => Self::LocalBranches,
            Self::LocalTags => Self::RemoteTags,
            Self::RemoteTags => Self::LocalTags,
            Self::Files => Self::FileContent,
            Self::FileContent => Self::Files,
            Self::Remotes => Self::Remotes,
            Self::Stashes => Self::Stashes,
            Self::StashedFiles => Self::StashedFiles,
            Self::Worktrees => Self::Worktrees,
            Self::Submodules => Self::Submodules,
            Self::Reflog => Self::Reflog,
            Self::ForgeIssues => Self::ForgeIssueDetails,
            Self::ForgeIssueDetails => Self::ForgeIssues,
            Self::ForgePRs => Self::ForgePRDetails,
            Self::ForgePRDetails => Self::ForgePRs,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum OverviewFocus {
    #[default]
    Overview,
    Stats,
}

#[derive(Debug, Clone)]
pub struct DetailCache {
    pub detail: repo::ItemDetail,
    pub loaded_at: std::time::Instant,
}

#[derive(Debug, Clone)]
pub struct SearchResult {
    pub repo_name: String,
    pub repo_path: String,
    pub file_rel_path: String,
    pub line_number: usize,
    pub line_content: String,
}

/// All mutable session state.
pub struct App {
    pub config: Config,
    pub config_path: PathBuf,
    pub overview_scroll: usize,
    pub stats_scroll: usize,
    pub overview_focus: OverviewFocus,
    /// Filesystem classification per item, parallel to `config.items`.
    /// Recomputed on add/edit/delete so it never drifts from the list.
    pub statuses: Vec<ItemStatus>,
    pub selected_index: usize,
    pub scroll_top: usize,
    pub mode: Mode,
    pub input_buffer: String,
    pub status_message: Option<String>,
    pub error_message: Option<String>,
    pub current_detail: Option<ItemDetail>,
    /// Cache of repository detail views mapped by their path.
    pub detail_cache: std::collections::HashMap<String, DetailCache>,
    /// Which panel is focused inside the detail view.
    pub detail_focus: DetailSection,
    pub queue: crate::queue::Queue,
    pub file_tree: crate::components::file_tree::FileTreeComponent,
    pub branch_list: crate::components::branch_list::BranchListComponent,
    pub tag_list: crate::components::tag_list::TagListComponent,
    pub stash_list: crate::components::stash_list::StashListComponent,
    /// Selected row index inside the Commits panel (0 = top row).
    pub commit_list: crate::components::commit_list::CommitListComponent,
    pub commit_popup: crate::popups::commit::CommitPopup,
    pub confirm_popup: crate::popups::confirm::ConfirmPopup,
    pub generic_input_popup: crate::popups::commit::GenericInputPopup,
    /// Dynamic commit limit for pagination

    /// Active query for filtering commits in the commits panel

    /// Active query for filtering repositories in the home page list
    pub repo_search_query: Option<String>,
    /// Selected file index inside the Changed Files panel (real commits).

    /// Selected file index inside the Staged/Unstaged sub-panels (uncommitted view).

    /// Cached unified-diff lines for the currently selected file.
    pub diff: crate::components::diff::DiffComponent,
    /// Vertical scroll offset for the diff panel (StagingDetails focus).

    /// Selected hunk index for stage/unstage by hunk (StagingDetails focus).

    /// Whether we are selecting lines (true) or hunks (false) in StagingDetails.

    /// Selected line index in the file_diff.

    /// Selected conflict file index in Conflicts panel.

    /// Vertical scroll offset for the commit details panel (CommitDetails focus).

    /// Vertical scroll offset for the commit input popup.
    pub commit_input_scroll: usize,
    /// Selected local branch index in Branches tab.
    /// Selected remote branch index in Branches tab.
    /// Selected local tag index in Tags/Branches tabs.
    /// Selected remote tag index in Tags/Branches tabs.
    /// Selected remote index in Remotes tab.
    /// Selected stash index in Stashes tab.
    /// Selected file index in the Stashes tab stashed files list.
    /// Scroll offset for the help overlays.
    pub help_scroll: usize,
    pub legend_scroll: usize,
    pub collapsed_groups: std::collections::HashSet<String>,
    pub repo_jump_selection: usize,
    /// Panel bounding boxes recorded after each draw, used for mouse hit-testing.
    pub detail_areas: DetailAreas,
    /// Main panel item bounding boxes recorded after each draw, used for mouse hit-testing.
    pub main_areas: Vec<Rect>,
    pub global_filter: Option<GlobalFilter>,
    pub global_summary_area: Option<Rect>,

    pub status_list: crate::components::status_list::StatusListComponent,

    /// Timestamp and selected index of the last mouse click for double-click detection.
    pub last_click: Option<(std::time::Instant, usize)>,
    /// Active tab in the detail view (0 = Details, 1 = Files, 2 = Graph, 3 = Branches, 4 = Tags, 5 = Remotes, 6 = Stashes, 7 = Worktrees, 8 = Submodules, 9 = Reflog, 10 = ForgeIssues, 11 = ForgePRs).
    pub detail_tab: usize,
    pub advanced_tabs: bool,
    /// Selected file index in the Files tab.
    /// Vertical scroll offset for the file content preview in Files tab.
    /// Set of expanded folder paths.
    /// Flattened visible files inside the Files tab.
    /// Vertical scroll offset for the git history graph view (Graph tab).
    pub graph_scroll: usize,
    pub graph_selection: usize,
    /// Whether the status bar is expanded.
    pub status_expanded: bool,
    /// Whether the settings panel focus is on the sidebar categories.
    pub settings_focus_sidebar: bool,
    /// Sender for background task events.
    pub tx: std::sync::mpsc::Sender<String>,
    /// Receiver for background task events.
    pub rx: std::sync::mpsc::Receiver<String>,
    pub global_search_rx: std::sync::mpsc::Receiver<Vec<SearchResult>>,
    pub global_search_tx: std::sync::mpsc::Sender<Vec<SearchResult>>,
    pub global_search_query: String,
    pub global_search_results: Vec<SearchResult>,
    pub global_search_selection: usize,
    pub global_search_running: bool,
    pub global_search_focus_input: bool,
    /// Whether a background fetch is active.
    pub fetching: bool,
    /// Store the latest version if an update is available.
    pub update_available: Option<String>,
    /// Whether the update check was triggered manually.
    pub update_check_manual: bool,
    /// Number of active background (implicit) network actions.
    pub implicit_network_count: usize,
    /// Stored previous mode to restore after confirmation/popups.
    pub previous_mode: Option<Mode>,
    pub scanned_repos: Vec<(String, String)>,
    pub repo_scan_selection: usize,
    pub repo_scan_active: bool,
    pub repo_scan_count: usize,
    pub branch_search_selection: usize,
    pub file_search_selection: usize,
    pub commit_search_selection: usize,
    pub tag_search_selection: usize,
    /// Row selection index for the repository settings popup.
    pub repo_settings_selected_index: usize,
    /// Whether we are currently text-editing a repository setting.
    pub repo_settings_editing: bool,
    /// Temporary text input buffer for repository settings.
    pub repo_settings_input: String,
    /// Loaded user/default keybindings configuration.
    pub keybindings: crate::keybindings::KeybindingsConfig,
    /// Whether external Git application launch is pending.
    pub pending_git_app: bool,
    /// Whether terminal launch is pending.
    pub pending_terminal: bool,
    /// Whether terminal editor launch is pending with a file path.
    pub pending_editor_file: Option<String>,
    /// Whether interactive rebase is pending.
    pub pending_interactive_rebase: Option<(PathBuf, String)>,
    /// Repository paths currently being fetched in bulk.
    pub bulk_fetching: std::collections::HashSet<String>,
    /// Results of the latest bulk fetch (path -> Ok(msg) or Err(err)).
    pub bulk_fetch_results: std::collections::HashMap<String, Result<String, String>>,
    /// Timestamp when the last bulk fetch was completed.
    pub bulk_fetch_completed_at: Option<std::time::Instant>,
    /// Repository paths currently selected for batch operations.
    pub multi_selected: std::collections::HashSet<String>,
    /// Whether we are currently viewing logs UI.
    pub in_logs_ui: bool,
    /// Cached resolved ThemeConfigs for repositories.
    /// Keyed by repository absolute path.
    pub repo_theme_cache: std::collections::HashMap<String, crate::config::ThemeConfig>,
    /// Whether we are in full-screen diff mode under inspect view.
    pub inspect_full_diff: bool,
    /// Selection in search column picker.
    pub search_column_selection: usize,
    /// Columns to include in search.
    pub search_columns_sha: bool,
    pub search_columns_message: bool,
    pub search_columns_author: bool,
    pub search_columns_date: bool,
    /// Target branch name and remote flag for deletion/creation actions.
    pub branch_action_target: Option<(String, bool)>,
    pub commit_action_target_oid: Option<String>,
    /// Target commit OID for tag creation.
    pub tag_action_target_oid: Option<String>,
    /// Target tag name and remote flag for deletion action.
    pub tag_delete_target: Option<(String, bool)>,
    /// Target tag name for checkout action.
    pub tag_checkout_target: Option<String>,
    pub commit_checkout_target: Option<String>,
    /// Target tag name for push action.
    pub tag_push_target: Option<String>,
    /// Target file path and staged flag for discard/revert action.
    pub discard_target: Option<(String, bool)>,
    /// Target commit (hash, summary) for cherry-pick.
    pub cherry_pick_target: Option<(String, String)>,
    /// Selected destination branch index for the cherry-pick popup.
    pub cherry_pick_dest_selection: usize,
    /// List of local branch names available for cherry-pick destination.
    pub cherry_pick_dest_branches: Vec<String>,
    /// Target commit (hash, summary) for revert.
    pub revert_target: Option<(String, String)>,
    /// Simulated fetch progress percentage.
    pub fetch_progress: u16,
    /// Option to delete the stash after applying.
    pub stash_apply_delete_after: bool,
    /// Option to stash untracked files.
    pub stash_untracked: bool,
    /// Option to keep the index after stashing.
    pub stash_keep_index: bool,
    /// Track the targeted stash by (commit_id, message) for validation on confirm
    pub stash_action_target: Option<(String, String)>,
    /// Selection index in the Stashing UI file list.
    pub stashing_ui_selection: usize,
    /// Preserved original order of repository items from the config.
    pub original_items: Vec<String>,
    /// Which action the remote picker was opened for.
    pub remote_picker_action: Option<RemotePickerAction>,
    /// Selected row in the remote picker popup.
    pub remote_picker_selection: usize,
    /// Percentage width of the left panel in the Inspect view (default: 40).
    pub inspect_horizontal_split_pct: u16,
    /// Percentage height of the top left sub-panel in the Inspect view (default: 50).
    pub inspect_vertical_split_pct: u16,
    /// Percentage height of the commits list in the Workspace tab (default: 50).
    pub workspace_main_split_pct: u16,
    /// Percentage width of the files tree in the Files tab (default: 45).
    pub files_horizontal_split_pct: u16,
    /// Percentage width of the local branches list in the Branches tab (default: 50).
    pub branches_horizontal_split_pct: u16,
    /// Percentage width of the left list column in the Stashes tab (default: 35).
    pub stashes_horizontal_split_pct: u16,
    /// Percentage height of the top stashes list in the Stashes tab (default: 50).
    pub stashes_vertical_split_pct: u16,
    /// Percentage width of the left overview panel in the Overview tab (default: 50).
    pub overview_horizontal_split_pct: u16,
    /// Percentage height of the top issues list in the Forge tab (default: 50).
    pub forge_vertical_split_pct: u16,
    /// Percentage height of the top PRs list in the Forge PRs tab (default: 50).
    pub forge_pr_vertical_split_pct: u16,
    /// Percentage width of the commit message popup (default: 80).
    pub commit_popup_width_pct: u16,
    /// Percentage height of the commit message popup (default: 45).
    pub commit_popup_height_pct: u16,
    /// Active drag splitter if dragging is in progress.
    pub active_drag_splitter: Option<Splitter>,
    pub settings_selected_index: usize,
    pub settings_editing: bool,
    pub settings_theme_list: Vec<String>,
    pub settings_theme_index: usize,
    pub debug_log_scroll: usize,
    pub debug_log_search_query: Option<String>,
    pub debug_log_search_editing: bool,
    pub import_url: String,
    pub import_dest: String,
    pub import_name: String,
    pub remote_add_name: String,
    pub remote_add_url: String,
    pub remote_action_target: Option<String>,
    pub last_staging_focus: DetailSection,
    pub loading_repo_path: Option<String>,
    pub detail_tx: std::sync::mpsc::Sender<(String, repo::ItemDetail)>,
    pub detail_rx: std::sync::mpsc::Receiver<(String, repo::ItemDetail)>,
    pub tab_tx: std::sync::mpsc::Sender<(String, usize, repo::TabPayload)>,
    pub tab_rx: std::sync::mpsc::Receiver<(String, usize, repo::TabPayload)>,
    pub file_history_revisions: Vec<repo::FileRevision>,
    pub file_history_selection: usize,
    pub file_history_diff: Vec<repo::DiffLine>,
    pub file_history_diff_scroll: usize,
    pub file_history_path: String,
    pub file_history_focus: usize,
    pub worktree_selection: usize,
    pub submodule_selection: usize,
    pub reflog_selection: usize,
    pub forge_issue_selection: usize,
    pub forge_pr_selection: usize,
    pub forge_issues_assigned_only: bool,
    pub forge_comment_path: String,
    pub forge_comment_line: u32,
    pub forge_pr_comments: Option<Vec<repo::ForgePRComment>>,
    pub forge_pr_comments_loading: bool,
    pub worktree_add_branch: String,
    pub worktree_add_path: String,
    pub worktree_lock_reason: String,
    pub worktree_remove_delete_folder: bool,
    pub worktree_remove_force: bool,
    pub submodule_add_url: String,
    pub submodule_add_path: String,
    pub submodule_delete_target: Option<String>,
    pub cpu_tracker: std::sync::Mutex<Option<(f64, std::time::Instant, f64, f64)>>,
    pub watcher: Option<notify::RecommendedWatcher>,
    pub status_refresh_tx: std::sync::mpsc::Sender<Vec<(usize, String, ItemStatus)>>,
    pub status_refresh_rx: std::sync::mpsc::Receiver<Vec<(usize, String, ItemStatus)>>,
    pub last_background_refresh: std::time::Instant,
    pub last_background_fetch_all: std::time::Instant,
    pub background_refresh_running: bool,
    pub graph_visible_height: std::cell::Cell<usize>,
    pub pending_add_repo: Option<String>,
    pub pending_bulk_add_repo: Option<String>,
}

#[derive(Clone, Debug)]
pub struct FileTreeItem {
    pub name: String,
    pub full_path: String,
    pub is_dir: bool,
    pub depth: usize,
    pub is_expanded: bool,
}

struct TempNode {
    name: String,
    full_path: String,
    is_dir: bool,
    children: std::collections::BTreeMap<String, TempNode>,
}

enum LogsNavDirection {
    Up,
    Down,
    PageUp(usize),
    PageDown(usize),
}

mod actions;
mod git;
mod navigation;
pub use navigation::HomeRow;
#[cfg(test)]
mod tests;
mod workspace;

impl App {
    pub fn resolve_repo_themes(&mut self) {
        self.repo_theme_cache.clear();
        let themes_dir = self.config_path.parent().unwrap_or(&self.config_path).join("themes");
        if !themes_dir.exists() {
            return;
        }
        for (repo_path, repo_cfg) in &self.config.repo_configs {
            if let Some(theme_name) = &repo_cfg.theme {
                let theme_path = themes_dir.join(format!("{}.theme", theme_name));
                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.repo_theme_cache.insert(repo_path.clone(), theme);
                        }
                    }
                }
            }
        }
    }

    pub fn setup_watcher(&mut self) {
        use notify::{RecursiveMode, Watcher};

        self.watcher = None;

        let tx = self.tx.clone();
        let excludes = self.config.scan.excludes.clone();
        let mut watcher =
            match notify::recommended_watcher(move |res: Result<notify::Event, notify::Error>| {
                if let Ok(event) = res {
                    for path in event.paths {
                        let path_str = path.to_string_lossy();
                        if excludes.iter().any(|ex| path_str.contains(ex)) {
                            continue;
                        }
                        let clean_path =
                            path_str.replace("\\.git\\", "/.git/").replace("\\.git", "/.git");
                        if let Some(pos) = clean_path.find("/.git") {
                            let repo_root = &clean_path[..pos];
                            if !path_str.ends_with(".lock")
                                && (path_str.contains("/.git/refs/")
                                    || path_str.ends_with("/.git/index")
                                    || path_str.ends_with("/.git/HEAD"))
                            {
                                let _ = tx.send(format!("REFRESH_REPO:{}", repo_root));
                            }
                        }
                    }
                }
            }) {
                Ok(w) => w,
                Err(e) => {
                    crate::debug_log::warn(format!("Failed to initialize file watcher: {}", e));
                    return;
                }
            };

        for item in &self.config.items {
            let canon = match std::fs::canonicalize(item) {
                Ok(c) => c,
                Err(_) => PathBuf::from(item),
            };
            let git_dir = canon.join(".git");
            if git_dir.exists() && git_dir.is_dir() {
                if let Err(e) = watcher.watch(&git_dir, RecursiveMode::Recursive) {
                    crate::debug_log::warn(format!(
                        "Failed to watch repository {:?}: {}",
                        git_dir, e
                    ));
                }
            }
        }

        for watch_dir in &self.config.watch_dirs {
            let expanded = repo::expand_tilde(watch_dir);
            let canon = match std::fs::canonicalize(&expanded) {
                Ok(c) => c,
                Err(_) => PathBuf::from(&expanded),
            };
            if canon.exists() && canon.is_dir() {
                if let Err(e) = watcher.watch(&canon, RecursiveMode::Recursive) {
                    crate::debug_log::warn(format!("Failed to watch directory {:?}: {}", canon, e));
                }
            }
        }

        self.watcher = Some(watcher);
    }

    pub fn trigger_initial_status_load(&self) {
        let paths: Vec<(usize, String)> = self.config.items.iter().cloned().enumerate().collect();
        let tx = self.status_refresh_tx.clone();

        std::thread::spawn(move || {
            let num_workers = 4.min(paths.len());
            if num_workers == 0 {
                return;
            }

            let paths = std::sync::Arc::new(paths);
            let mut handles = Vec::new();

            for worker_id in 0..num_workers {
                let paths = std::sync::Arc::clone(&paths);
                let tx = tx.clone();
                let handle = std::thread::spawn(move || {
                    let mut updates = Vec::new();
                    let total = paths.len();
                    let mut i = worker_id;
                    while i < total {
                        if let Some((idx, path)) = paths.get(i) {
                            let status = repo::inspect_summary(path);
                            updates.push((*idx, path.clone(), status));
                        }
                        i += num_workers;
                    }
                    if !updates.is_empty() {
                        let _ = tx.send(updates);
                    }
                });
                handles.push(handle);
            }

            for handle in handles {
                let _ = handle.join();
            }
        });
    }

    pub fn drain_queue(&mut self) {
        while let Some(ev) = self.queue.pop() {
            match ev {
                crate::queue::InternalEvent::ClosePopup => self.mode = Mode::Detail,

                crate::queue::InternalEvent::ConfirmYes => match self.mode {
                    Mode::BranchDeleteConfirm => self.confirm_branch_delete(),
                    Mode::BranchPushConfirm => self.confirm_branch_push(),
                    Mode::BranchMergeConfirm => self.confirm_branch_merge(),
                    Mode::MergeAbortConfirm => self.confirm_abort_merge(),
                    Mode::MergeContinueConfirm => self.confirm_continue_merge(),
                    Mode::BranchRebaseConfirm => self.confirm_branch_rebase(),
                    Mode::BranchInteractiveRebaseConfirm => {
                        self.confirm_branch_interactive_rebase()
                    }
                    Mode::DiscardChangesConfirm => self.confirm_discard_changes(),
                    Mode::RevertConfirm => self.confirm_revert(),
                    Mode::TagDeleteConfirm => self.confirm_tag_delete(),
                    Mode::TagPushConfirm => self.confirm_tag_push(),
                    Mode::TagPushAllConfirm => self.confirm_tag_push_all(),
                    Mode::StashDeleteConfirm => self.confirm_stash_delete(),
                    Mode::BranchCheckoutConfirm => self.confirm_branch_checkout(),
                    Mode::TagCheckoutConfirm => self.confirm_tag_checkout(),
                    Mode::CommitCheckoutConfirm => self.confirm_commit_checkout(),
                    Mode::RemoteDeleteConfirm => self.confirm_remote_delete(),
                    Mode::UpdateConfirm => self.trigger_self_update(),
                    Mode::SubmoduleDeleteConfirm => self.confirm_submodule_delete(),
                    _ => {}
                },
                crate::queue::InternalEvent::ConfirmNo => match self.mode {
                    Mode::BranchDeleteConfirm => self.cancel_branch_delete(),
                    Mode::BranchPushConfirm => self.cancel_branch_push(),
                    Mode::BranchMergeConfirm => self.cancel_branch_merge(),
                    Mode::MergeAbortConfirm => {
                        self.mode = Mode::Detail;
                    }
                    Mode::MergeContinueConfirm => {
                        self.mode = Mode::Detail;
                    }
                    Mode::BranchRebaseConfirm => self.cancel_branch_rebase(),
                    Mode::BranchInteractiveRebaseConfirm => self.cancel_branch_interactive_rebase(),
                    Mode::DiscardChangesConfirm => self.cancel_discard_changes(),
                    Mode::RevertConfirm => self.cancel_revert(),
                    Mode::TagDeleteConfirm => self.cancel_tag_delete(),
                    Mode::TagPushConfirm => self.cancel_tag_push(),
                    Mode::TagPushAllConfirm => self.cancel_tag_push_all(),
                    Mode::StashDeleteConfirm => self.cancel_stash_delete(),
                    Mode::BranchCheckoutConfirm => self.cancel_branch_checkout(),
                    Mode::TagCheckoutConfirm => self.cancel_tag_checkout(),
                    Mode::CommitCheckoutConfirm => self.cancel_commit_checkout(),
                    Mode::RemoteDeleteConfirm => {
                        self.remote_action_target = None;
                        self.mode = Mode::Detail;
                    }
                    Mode::SubmoduleDeleteConfirm => self.cancel_submodule_delete(),
                    Mode::UpdateConfirm => {
                        self.mode = self.previous_mode.take().unwrap_or(Mode::Normal);
                    }
                    _ => {
                        self.mode = Mode::Detail;
                    }
                },
                crate::queue::InternalEvent::InputChar(c) => self.input_char(c),
                crate::queue::InternalEvent::InputBackspace => self.input_backspace(),
                crate::queue::InternalEvent::InputEnter => match self.mode {
                    Mode::BranchCreateInput => self.commit_branch_create(),
                    Mode::TagCreateInput => self.commit_tag_create(),
                    Mode::StashCreateInput => self.commit_stash_create(),
                    Mode::RemoteAddNameInput => self.commit_remote_add_name(),
                    Mode::RemoteAddUrlInput => self.commit_remote_add_url(),
                    Mode::WorktreeAddBranchInput => self.commit_worktree_add_branch(),
                    Mode::WorktreeAddPathInput => self.commit_worktree_add_path(),
                    Mode::WorktreeLockReasonInput => self.commit_worktree_lock_reason(),
                    Mode::WorktreeRemoveConfirm => self.commit_worktree_remove(),
                    Mode::SubmoduleAddUrlInput => self.commit_submodule_add_url(),
                    Mode::SubmoduleAddPathInput => self.commit_submodule_add_path(),
                    _ => {}
                },
                crate::queue::InternalEvent::InputEsc => {
                    self.input_buffer.clear();
                    match self.mode {
                        Mode::BranchCreateInput => self.cancel_branch_create(),
                        Mode::TagCreateInput => {
                            self.tag_action_target_oid = None;
                            self.mode = Mode::Detail;
                        }
                        _ => {
                            self.mode = Mode::Detail;
                        }
                    }
                }
                // simplified
                crate::queue::InternalEvent::Commit => {
                    self.commit_git_changes();
                }
                crate::queue::InternalEvent::SearchColumnPicker => {
                    self.search_column_selection = 0;
                    self.mode = Mode::SearchColumnPicker;
                }
                crate::queue::InternalEvent::StartCommit => self.start_commit(),
                crate::queue::InternalEvent::StartCommitAmend => self.start_commit_amend(),
                crate::queue::InternalEvent::StartTagCreate => self.start_tag_create(),
                crate::queue::InternalEvent::RunInteractiveRebase => self.run_interactive_rebase(),
                crate::queue::InternalEvent::RequestCherryPick => self.request_cherry_pick(),
                crate::queue::InternalEvent::YankSelectedCommitHash => {
                    self.yank_selected_commit_hash()
                }
                crate::queue::InternalEvent::RequestRevert => self.request_revert(),
                crate::queue::InternalEvent::InspectCommit => {
                    self.mode = Mode::Inspect;
                    if self.is_uncommitted_selected() {
                        self.detail_focus = DetailSection::Staged;
                        self.last_staging_focus = DetailSection::Staged;
                        self.status_list.staging_file_selection = 0;
                    } else {
                        self.detail_focus = DetailSection::Staged;
                        self.last_staging_focus = DetailSection::Staged;
                        self.status_list.file_selection = 0;
                    }
                    self.diff.diff_scroll = 0;
                    self.refresh_file_diff();
                }
                crate::queue::InternalEvent::CommitSelectionUp => self.detail_commit_up(),
                crate::queue::InternalEvent::CommitSelectionDown => self.detail_commit_down(),
                crate::queue::InternalEvent::CommitSelectionPageUp => {
                    let page = self.get_current_page_size();
                    self.detail_commit_page_up(page);
                }

                crate::queue::InternalEvent::CommitSelectionTop => self.detail_commit_to_top(),
                crate::queue::InternalEvent::CommitSelectionBottom => {
                    self.detail_commit_to_bottom()
                }
                crate::queue::InternalEvent::LoadMoreCommits => {
                    if self.commit_list.limit > 0 {
                        let add_amount = if self.get_current_max_commits() > 0 {
                            self.get_current_max_commits()
                        } else {
                            200
                        };
                        self.commit_list.limit = self.commit_list.limit.saturating_add(add_amount);
                        self.resync_detail();
                        self.status_message = Some("Loading more commits...".to_string());
                    }
                }
                crate::queue::InternalEvent::CommitDetailsUp => {
                    self.commit_list.details_scroll_up()
                }
                crate::queue::InternalEvent::CommitDetailsDown => {
                    self.commit_list.details_scroll_down()
                }
                crate::queue::InternalEvent::StagingFileUp => {
                    if self.is_uncommitted_selected() {
                        self.staging_file_up()
                    } else {
                        self.detail_file_up()
                    }
                }
                crate::queue::InternalEvent::StagingFileDown => {
                    if self.is_uncommitted_selected() {
                        self.staging_file_down()
                    } else {
                        self.detail_file_down()
                    }
                }
                crate::queue::InternalEvent::ConflictFileUp => self.conflict_file_up(),
                crate::queue::InternalEvent::ConflictFileDown => self.conflict_file_down(),
                crate::queue::InternalEvent::StageSelectedFile => self.stage_selected_file(),
                crate::queue::InternalEvent::UnstageSelectedFile => self.unstage_selected_file(),
                crate::queue::InternalEvent::ResolveConflictOurs => self.resolve_conflict_ours(),
                crate::queue::InternalEvent::ResolveConflictTheirs => {
                    self.resolve_conflict_theirs()
                }
                crate::queue::InternalEvent::MarkConflictResolved => self.mark_conflict_resolved(),
                crate::queue::InternalEvent::MergeAbortConfirm => {
                    self.mode = Mode::MergeAbortConfirm
                }
                crate::queue::InternalEvent::MergeContinueConfirm => {
                    self.mode = Mode::MergeContinueConfirm
                }
                crate::queue::InternalEvent::StageSelectedHunk => self.stage_selected_hunk(),
                crate::queue::InternalEvent::UnstageSelectedHunk => self.unstage_selected_hunk(),
                crate::queue::InternalEvent::StageAllChanges => self.stage_all_changes(),
                crate::queue::InternalEvent::UnstageAllChanges => self.unstage_all_changes(),
                crate::queue::InternalEvent::RequestDiscardChanges => {
                    self.request_discard_changes()
                }
                crate::queue::InternalEvent::RequestDiscardAllChanges => {
                    self.request_discard_all_changes()
                }
                crate::queue::InternalEvent::StartStashCreate => self.start_stash_create(),
                crate::queue::InternalEvent::DiffScrollUp => self.diff.diff_scroll_up(),
                crate::queue::InternalEvent::DiffScrollDown => self.diff.diff_scroll_down(),
                crate::queue::InternalEvent::DiffScrollPageUp => {
                    let page = self.get_current_page_size();
                    self.diff.diff_scroll_page_up(page);
                }
                crate::queue::InternalEvent::DiffScrollPageDown => {
                    let page = self.get_current_page_size();
                    self.diff.diff_scroll_page_down(page);
                }
                crate::queue::InternalEvent::DiffScrollTop => self.diff.diff_scroll_to_top(),
                crate::queue::InternalEvent::DiffScrollBottom => self.diff.diff_scroll_to_bottom(),

                // FileTree
                crate::queue::InternalEvent::FileTreeUp => {
                    self.file_list_up();
                    self.refresh_blame_if_shown();
                }
                crate::queue::InternalEvent::FileTreeDown => {
                    self.file_list_down();
                    self.refresh_blame_if_shown();
                }
                crate::queue::InternalEvent::FileTreePageUp => {
                    let p = self.get_current_page_size();
                    self.file_list_page_up(p);
                    self.refresh_blame_if_shown();
                }
                crate::queue::InternalEvent::FileTreePageDown => {
                    let p = self.get_current_page_size();
                    self.file_list_page_down(p);
                    self.refresh_blame_if_shown();
                }
                crate::queue::InternalEvent::FileTreeTop => {
                    self.file_list_to_top();
                    self.refresh_blame_if_shown();
                }
                crate::queue::InternalEvent::FileTreeBottom => {
                    self.file_list_to_bottom();
                    self.refresh_blame_if_shown();
                }
                crate::queue::InternalEvent::FileContentUp => {
                    self.file_content_scroll_up();
                }
                crate::queue::InternalEvent::FileContentDown => {
                    self.file_content_scroll_down();
                }
                crate::queue::InternalEvent::FileContentPageUp => {
                    let p = self.get_current_page_size();
                    self.file_content_scroll_page_up(p);
                }
                crate::queue::InternalEvent::FileContentPageDown => {
                    let p = self.get_current_page_size();
                    self.file_content_scroll_page_down(p);
                }
                crate::queue::InternalEvent::FileContentTop => {
                    self.file_content_scroll_to_top();
                }
                crate::queue::InternalEvent::FileContentBottom => {
                    self.file_content_scroll_to_bottom();
                }
                crate::queue::InternalEvent::ToggleFolderExpanded => self.toggle_folder_expanded(),
                crate::queue::InternalEvent::CollapseAllFolders => self.collapse_all_folders(),
                crate::queue::InternalEvent::RequestDiscardFile => self.request_discard_changes(),

                // BranchList
                crate::queue::InternalEvent::LocalBranchUp => self.local_branch_up(),
                crate::queue::InternalEvent::LocalBranchDown => self.local_branch_down(),
                crate::queue::InternalEvent::LocalBranchPageUp => {
                    let p = self.get_current_page_size();
                    self.local_branch_page_up(p)
                }
                crate::queue::InternalEvent::LocalBranchPageDown => {
                    let p = self.get_current_page_size();
                    self.local_branch_page_down(p)
                }
                crate::queue::InternalEvent::LocalBranchTop => self.local_branch_to_top(),
                crate::queue::InternalEvent::LocalBranchBottom => self.local_branch_to_bottom(),
                crate::queue::InternalEvent::RemoteBranchUp => self.remote_branch_up(),
                crate::queue::InternalEvent::RemoteBranchDown => self.remote_branch_down(),
                crate::queue::InternalEvent::RemoteBranchPageUp => {
                    let p = self.get_current_page_size();
                    self.remote_branch_page_up(p)
                }
                crate::queue::InternalEvent::RemoteBranchPageDown => {
                    let p = self.get_current_page_size();
                    self.remote_branch_page_down(p)
                }
                crate::queue::InternalEvent::RemoteBranchTop => self.remote_branch_to_top(),
                crate::queue::InternalEvent::RemoteBranchBottom => self.remote_branch_to_bottom(),
                crate::queue::InternalEvent::CheckoutBranch => self.request_branch_checkout(),
                crate::queue::InternalEvent::RequestDeleteBranch => self.request_branch_delete(),
                crate::queue::InternalEvent::StartBranchCreate => self.start_branch_create(),
                crate::queue::InternalEvent::StartBranchMerge => self.request_branch_merge(),
                crate::queue::InternalEvent::StartBranchRebase => self.request_branch_rebase(),
                crate::queue::InternalEvent::RequestBranchPush => self.request_branch_push(),
                crate::queue::InternalEvent::FetchRemote => {
                    let remote_name = if let Some(crate::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);
                    }
                }
                crate::queue::InternalEvent::StartRemoteAdd => self.start_remote_add(),
                crate::queue::InternalEvent::RequestDeleteRemote => self.request_remote_delete(),

                // TagList
                crate::queue::InternalEvent::TagUp => self.local_tag_up(),
                crate::queue::InternalEvent::TagDown => self.local_tag_down(),
                crate::queue::InternalEvent::TagPageUp => {
                    let p = self.get_current_page_size();
                    self.local_tag_page_up(p)
                }
                crate::queue::InternalEvent::TagPageDown => {
                    let p = self.get_current_page_size();
                    self.local_tag_page_down(p)
                }
                crate::queue::InternalEvent::TagTop => self.local_tag_to_top(),
                crate::queue::InternalEvent::TagBottom => self.local_tag_to_bottom(),
                crate::queue::InternalEvent::CheckoutTag => self.request_tag_checkout(),
                crate::queue::InternalEvent::RequestDeleteTag => self.request_tag_delete(),
                crate::queue::InternalEvent::RequestPushTag => self.request_tag_push(),
                crate::queue::InternalEvent::RequestPushAllTags => self.request_tag_push_all(),
                crate::queue::InternalEvent::FetchRemoteTags => self.fetch_remote_tags(true),

                // StashList
                crate::queue::InternalEvent::StashUp => self.stash_up(),
                crate::queue::InternalEvent::StashDown => self.stash_down(),
                crate::queue::InternalEvent::StashPageUp => {
                    let p = self.get_current_page_size();
                    self.stash_page_up(p)
                }
                crate::queue::InternalEvent::StashPageDown => {
                    let p = self.get_current_page_size();
                    self.stash_page_down(p)
                }
                crate::queue::InternalEvent::StashTop => self.stash_to_top(),
                crate::queue::InternalEvent::StashBottom => self.stash_to_bottom(),
                crate::queue::InternalEvent::StashFileUp => self.stash_file_up(),
                crate::queue::InternalEvent::StashFileDown => self.stash_file_down(),
                crate::queue::InternalEvent::StashFilePageUp => {
                    let p = self.get_current_page_size();
                    self.stash_file_page_up(p)
                }
                crate::queue::InternalEvent::StashFilePageDown => {
                    let p = self.get_current_page_size();
                    self.stash_file_page_down(p)
                }
                crate::queue::InternalEvent::StashFileTop => self.stash_file_to_top(),
                crate::queue::InternalEvent::StashFileBottom => self.stash_file_to_bottom(),
                crate::queue::InternalEvent::RequestDeleteStash => self.request_stash_delete(),
                crate::queue::InternalEvent::RequestApplyStash => self.request_stash_apply(),

                crate::queue::InternalEvent::CommitSelectionPageDown => {
                    let page = self.get_current_page_size();
                    self.detail_commit_page_down(page);
                }
                _ => {}
            }
        }
    }

    pub fn sym(&self, key: &str) -> &'static str {
        self.config.sym(key)
    }

    pub fn is_bound(
        &self,
        action: crate::keybindings::Action,
        key: crossterm::event::KeyEvent,
    ) -> bool {
        self.keybindings.matches(action, key)
    }

    pub fn new(config: Config, config_path: PathBuf) -> Self {
        crate::debug_log::info("Initializing Gitwig application state");
        crate::ui::update_theme(&config.theme);
        let config_dir = config_path.parent().unwrap_or(&config_path);
        let keybindings = crate::keybindings::KeybindingsConfig::load(config_dir);
        let original_items = config.items.clone();
        let max_commits = config.max_commits;
        let statuses = vec![repo::ItemStatus::Loading; config.items.len()];
        let (tx, rx) = std::sync::mpsc::channel();
        let (detail_tx, detail_rx) = std::sync::mpsc::channel();
        let (tab_tx, tab_rx) = std::sync::mpsc::channel();
        let (status_refresh_tx, status_refresh_rx) = std::sync::mpsc::channel();
        let (global_search_tx, global_search_rx) = std::sync::mpsc::channel();
        let queue = crate::queue::Queue::default();
        let mut app = Self {
            queue: queue.clone(),
            original_items,
            config,
            config_path,
            statuses,
            selected_index: 0,
            scroll_top: 0,
            mode: Mode::Normal,
            input_buffer: String::new(),
            status_message: None,
            error_message: None,
            current_detail: None,
            detail_cache: std::collections::HashMap::new(),
            detail_focus: DetailSection::Commits,
            file_tree: crate::components::file_tree::FileTreeComponent::new(queue.clone()),
            branch_list: crate::components::branch_list::BranchListComponent::new(queue.clone()),
            tag_list: crate::components::tag_list::TagListComponent::new(queue.clone()),
            stash_list: crate::components::stash_list::StashListComponent::new(queue.clone()),
            commit_list: crate::components::commit_list::CommitListComponent {
                limit: max_commits,
                queue: queue.clone(),
                ..Default::default()
            },
            commit_popup: crate::popups::commit::CommitPopup::new(queue.clone()),
            confirm_popup: crate::popups::confirm::ConfirmPopup::new(queue.clone()),
            generic_input_popup: crate::popups::commit::GenericInputPopup::new(queue.clone()),

            repo_search_query: None,

            diff: crate::components::diff::DiffComponent::new(queue.clone()),

            commit_input_scroll: 0,
            help_scroll: 0,
            legend_scroll: 0,
            overview_scroll: 0,
            stats_scroll: 0,
            overview_focus: OverviewFocus::default(),
            collapsed_groups: std::collections::HashSet::new(),
            repo_jump_selection: 0,
            detail_areas: DetailAreas::default(),
            main_areas: Vec::new(),
            global_filter: None,
            global_summary_area: None,

            status_list: crate::components::status_list::StatusListComponent::new(queue.clone()),

            last_click: None,
            detail_tab: 0,
            advanced_tabs: false,
            graph_scroll: 0,
            graph_selection: 0,
            status_expanded: false,
            settings_focus_sidebar: true,
            tx,
            rx,
            global_search_rx,
            global_search_tx,
            global_search_query: String::new(),
            global_search_results: Vec::new(),
            global_search_selection: 0,
            global_search_running: false,
            global_search_focus_input: true,
            fetching: false,
            update_available: None,
            update_check_manual: false,
            implicit_network_count: 0,
            previous_mode: None,
            scanned_repos: Vec::new(),
            repo_scan_selection: 0,
            repo_scan_active: false,
            repo_scan_count: 0,
            branch_search_selection: 0,
            file_search_selection: 0,
            commit_search_selection: 0,
            tag_search_selection: 0,
            repo_settings_selected_index: 0,
            repo_settings_editing: false,
            repo_settings_input: String::new(),
            keybindings,
            pending_git_app: false,
            pending_terminal: false,
            pending_editor_file: None,
            pending_interactive_rebase: None,
            bulk_fetching: std::collections::HashSet::new(),
            bulk_fetch_results: std::collections::HashMap::new(),
            bulk_fetch_completed_at: None,
            multi_selected: std::collections::HashSet::new(),
            in_logs_ui: false,
            repo_theme_cache: std::collections::HashMap::new(),
            inspect_full_diff: false,
            search_column_selection: 0,
            search_columns_sha: true,
            search_columns_message: true,
            search_columns_author: true,
            search_columns_date: true,
            branch_action_target: None,
            commit_action_target_oid: None,
            tag_action_target_oid: None,
            tag_delete_target: None,
            tag_checkout_target: None,
            commit_checkout_target: None,
            tag_push_target: None,
            discard_target: None,
            cherry_pick_target: None,
            cherry_pick_dest_selection: 0,
            cherry_pick_dest_branches: Vec::new(),
            revert_target: None,
            fetch_progress: 0,
            stash_apply_delete_after: true,
            stash_untracked: true,
            stash_keep_index: false,
            stash_action_target: None,
            stashing_ui_selection: 0,
            remote_picker_action: None,
            remote_picker_selection: 0,
            inspect_horizontal_split_pct: 38,
            inspect_vertical_split_pct: 38,
            workspace_main_split_pct: 38,
            files_horizontal_split_pct: 38,
            branches_horizontal_split_pct: 50,
            stashes_horizontal_split_pct: 38,
            stashes_vertical_split_pct: 38,
            overview_horizontal_split_pct: 38,
            forge_vertical_split_pct: 50,
            forge_pr_vertical_split_pct: 50,
            commit_popup_width_pct: 80,
            commit_popup_height_pct: 45,
            active_drag_splitter: None,
            settings_selected_index: 0,
            settings_editing: false,
            settings_theme_list: Vec::new(),
            settings_theme_index: 0,
            debug_log_scroll: 0,
            debug_log_search_query: None,
            debug_log_search_editing: false,
            import_url: String::new(),
            import_dest: String::new(),
            import_name: String::new(),
            remote_add_name: String::new(),
            remote_add_url: String::new(),
            remote_action_target: None,
            last_staging_focus: DetailSection::Staged,
            loading_repo_path: None,
            detail_tx,
            detail_rx,
            tab_tx,
            tab_rx,
            file_history_revisions: Vec::new(),
            file_history_selection: 0,
            file_history_diff: Vec::new(),
            file_history_diff_scroll: 0,
            file_history_path: String::new(),
            file_history_focus: 0,
            worktree_selection: 0,
            submodule_selection: 0,
            reflog_selection: 0,
            forge_issue_selection: 0,
            forge_pr_selection: 0,
            forge_issues_assigned_only: true,
            forge_comment_path: String::new(),
            forge_comment_line: 1,
            forge_pr_comments: None,
            forge_pr_comments_loading: false,
            worktree_add_branch: String::new(),
            worktree_add_path: String::new(),
            worktree_lock_reason: String::new(),
            worktree_remove_delete_folder: false,
            worktree_remove_force: false,
            submodule_add_url: String::new(),
            submodule_add_path: String::new(),
            submodule_delete_target: None,
            cpu_tracker: std::sync::Mutex::new(None),
            watcher: None,
            status_refresh_tx,
            status_refresh_rx,
            last_background_refresh: std::time::Instant::now(),
            last_background_fetch_all: std::time::Instant::now(),
            background_refresh_running: false,
            graph_visible_height: std::cell::Cell::new(0),
            pending_add_repo: None,
            pending_bulk_add_repo: None,
        };

        if app.config.sort_by != SortOrder::Custom {
            app.sort_items_in_place();
        }

        // Detect update / initial setup
        let current_version = env!("CARGO_PKG_VERSION");
        let version_path = app.config_path.parent().unwrap_or(&app.config_path).join(".version");
        let mut is_first_run = false;

        let last_version = if version_path.exists() {
            std::fs::read_to_string(&version_path).map(|s| s.trim().to_string()).unwrap_or_default()
        } else {
            is_first_run = true;
            String::new()
        };

        if last_version != current_version {
            // 1. Back up config if it is an update and config exists
            if !is_first_run && app.config_path.exists() {
                let backup_path = app.config_path.with_extension("toml.bak");
                let _ = std::fs::copy(&app.config_path, backup_path);
                crate::debug_log::info(format!(
                    "Backed up configuration to {:?}",
                    app.config_path.with_extension("toml.bak")
                ));
            }

            // 2. Perform updates or auto-detections
            let gitui_installed = is_tool_installed("gitui");
            let lazygit_installed = is_tool_installed("lazygit");
            if app.config.git_app == "gitui" && !gitui_installed && lazygit_installed {
                app.config.git_app = "lazygit".to_string();
                crate::debug_log::info("Auto-configured git_app to lazygit as gitui was not found");
            }

            // 3. Write new version file
            let _ = std::fs::write(&version_path, current_version);

            // 4. Save config to persist migration changes
            app.persist("Configuration verification saved");

            // 5. Update UI status message to inform user
            if is_first_run {
                app.status_message = Some(format!("Welcome to Gitwig v{}!", current_version));
            } else {
                app.status_message = Some(format!(
                    "Gitwig updated to v{}! Configuration verified and backed up.",
                    current_version
                ));
            }
        }

        #[cfg(not(test))]
        {
            app.trigger_update_check_internal(false);
        }

        app.resolve_repo_themes();
        app.setup_watcher();
        app.trigger_initial_status_load();

        app
    }
}

/// Main event loop: compute layout, draw, poll input, repeat.
pub fn run<B: ratatui::backend::Backend>(
    terminal: &mut Terminal<B>,
    mut app: App,
) -> Result<(), Box<dyn Error>>
where
    <B as ratatui::backend::Backend>::Error: 'static,
{
    loop {
        // Trigger background status auto-refresh if 10 seconds have elapsed
        if !app.background_refresh_running
            && !app.config.items.is_empty()
            && app.last_background_refresh.elapsed() >= std::time::Duration::from_secs(10)
        {
            app.background_refresh_running = true;
            app.last_background_refresh = std::time::Instant::now();
            let paths = app.config.items.clone();
            let tx = app.status_refresh_tx.clone();
            std::thread::spawn(move || {
                let mut updates = Vec::new();
                for (idx, path) in paths.into_iter().enumerate() {
                    let status = repo::inspect_summary(&path);
                    updates.push((idx, path, status));
                }
                let _ = tx.send(updates);
            });
        }

        // Trigger scheduled background fetch for all repositories
        let auto_fetch_interval = app.config.auto_fetch_interval_mins;
        if auto_fetch_interval > 0
            && !app.config.items.is_empty()
            && app.last_background_fetch_all.elapsed()
                >= std::time::Duration::from_secs(auto_fetch_interval * 60)
        {
            app.last_background_fetch_all = std::time::Instant::now();
            app.bulk_fetch_all_implicit();
        }
        while let Ok(raw_msg) = app.rx.try_recv() {
            if let Some(repo_info) = raw_msg.strip_prefix("REPO_SCAN_FOUND:") {
                if let Some(pos) = repo_info.find("|||") {
                    let name = repo_info[..pos].to_string();
                    let path = repo_info[pos + 3..].to_string();
                    if !app.scanned_repos.iter().any(|(_, p)| p == &path) {
                        app.scanned_repos.push((name, path));
                    }
                }
                continue;
            }
            if raw_msg.starts_with("REPO_SCAN_COMPLETE:") {
                app.repo_scan_active = false;
                continue;
            }
            if let Some(count_str) = raw_msg.strip_prefix("REPO_SCAN_COUNT:") {
                if let Ok(count) = count_str.parse::<usize>() {
                    app.repo_scan_count = count;
                }
                continue;
            }

            if let Some(success_path) = raw_msg.strip_prefix("BULK_FETCH_SUCCESS:") {
                app.bulk_fetching.remove(success_path);
                if let Some(idx) = app.config.items.iter().position(|item| item == success_path) {
                    app.statuses[idx] = repo::inspect_summary(&app.config.items[idx]);
                }
                app.bulk_fetch_results
                    .insert(success_path.to_string(), Ok("Fetched successfully".to_string()));
                if app.bulk_fetching.is_empty() {
                    app.status_message = Some("Bulk fetch completed successfully".to_string());
                    app.bulk_fetch_completed_at = Some(std::time::Instant::now());
                }
                app.decrement_implicit_network();
                continue;
            }
            if let Some(error_data) = raw_msg.strip_prefix("BULK_FETCH_ERROR:") {
                if let Some(pos) = error_data.find("|||") {
                    let err_path = &error_data[..pos];
                    let err_msg = &error_data[pos + 3..];
                    app.bulk_fetching.remove(err_path);
                    app.bulk_fetch_results.insert(err_path.to_string(), Err(err_msg.to_string()));
                }
                if app.bulk_fetching.is_empty() {
                    app.status_message = Some("Bulk fetch completed".to_string());
                    app.bulk_fetch_completed_at = Some(std::time::Instant::now());
                }
                app.decrement_implicit_network();
                continue;
            }

            let (repo_path, msg) = if let Some(pos) = raw_msg.find("|||") {
                (Some(raw_msg[..pos].to_string()), raw_msg[pos + 3..].to_string())
            } else {
                (None, raw_msg)
            };

            let is_relevant = if let Some(ref path_str) = repo_path {
                if let Some(repo::ItemDetail::Repo { resolved, .. }) = &app.current_detail {
                    resolved.to_string_lossy() == *path_str
                } else {
                    false
                }
            } else {
                true
            };

            if is_relevant {
                if let Some(repo_path) = msg.strip_prefix("REFRESH_REPO:") {
                    let canon_target = std::fs::canonicalize(repo_path)
                        .unwrap_or_else(|_| PathBuf::from(repo_path));
                    let already_tracked = app.config.items.iter().position(|item| {
                        let canon_item =
                            std::fs::canonicalize(item).unwrap_or_else(|_| PathBuf::from(item));
                        canon_item == canon_target
                    });
                    if let Some(idx) = already_tracked {
                        app.statuses[idx] = repo::inspect_summary(&app.config.items[idx]);
                        if let Some(repo::ItemDetail::Repo { resolved, .. }) = &app.current_detail {
                            if resolved == &canon_target {
                                app.resync_detail();
                            }
                        }
                    } else {
                        // Check if it is inside one of the watched directories
                        let mut inside_watch_dir = false;
                        for watch_dir in &app.config.watch_dirs {
                            let expanded = repo::expand_tilde(watch_dir);
                            if let Ok(canon_watch) = std::fs::canonicalize(&expanded) {
                                if canon_target.starts_with(&canon_watch) {
                                    inside_watch_dir = true;
                                    break;
                                }
                            }
                        }
                        if inside_watch_dir {
                            let git_dir = canon_target.join(".git");
                            if git_dir.exists() && git_dir.is_dir() {
                                let path_str = repo_path.to_string();
                                app.auto_discover_add(path_str);
                                app.status_message =
                                    Some("Auto-discovered new repository".to_string());
                            }
                        }
                    }
                } else if let Some(latest_version) = msg.strip_prefix("UPDATE_CHECK:") {
                    let current_version = env!("CARGO_PKG_VERSION");
                    if is_newer_version(current_version, latest_version) {
                        app.update_available = Some(latest_version.to_string());
                        if app.update_check_manual {
                            app.status_message =
                                Some(format!("Update available: v{}", latest_version));
                        }
                    } else if app.update_check_manual {
                        app.status_message = Some("Gitwig is up to date".to_string());
                    }
                    if !app.update_check_manual {
                        app.decrement_implicit_network();
                    }
                    app.update_check_manual = false;
                } else if msg.starts_with("UPDATE_CHECK_FAILED:") {
                    if app.update_check_manual {
                        app.status_message = Some("Failed to check for updates".to_string());
                    }
                    if !app.update_check_manual {
                        app.decrement_implicit_network();
                    }
                    app.update_check_manual = false;
                } else if let Some(success_msg) = msg.strip_prefix("CHECKOUT_SUCCESS:") {
                    app.fetching = false;
                    app.status_message = Some(success_msg.to_string());
                    app.resync_detail();
                } else if let Some(err_msg) = msg.strip_prefix("CHECKOUT_ERROR:") {
                    app.fetching = false;
                    app.set_error(err_msg.to_string());
                } else if msg == "COMMENT_SUCCESS" {
                    app.fetching = false;
                    app.status_message = Some("Comment posted successfully".to_string());
                    app.load_comments_for_selected_pr();
                } else if let Some(err_msg) = msg.strip_prefix("COMMENT_ERROR:") {
                    app.fetching = false;
                    app.set_error(err_msg.to_string());
                } else if let Some(success_msg) = msg.strip_prefix("UPDATE_SUCCESS:") {
                    app.fetching = false;
                    app.status_message = Some(success_msg.to_string());
                } else if let Some(err_msg) = msg.strip_prefix("UPDATE_ERROR:") {
                    app.fetching = false;
                    app.set_error(err_msg.to_string());
                } else if let Some(dest_path) = msg.strip_prefix("CLONE_SUCCESS:") {
                    crate::debug_log::info(format!(
                        "Network Action: Cloning succeeded to {}",
                        dest_path
                    ));
                    app.fetching = false;
                    app.status_message = Some("Cloning completed successfully".to_string());
                    app.pending_add_repo = Some(dest_path.to_string());
                    app.input_buffer.clear();
                    app.mode = Mode::CloneRepoLabelInput;
                } else if let Some(tags_data) = msg.strip_prefix("REMOTE_TAGS:") {
                    crate::debug_log::info("Network Action: Fetching remote tags succeeded");
                    let tags = repo::deserialize_tags(tags_data);
                    if let Some(repo::ItemDetail::Repo { info, .. }) = &mut app.current_detail {
                        info.remote_tags = repo::TabData::Loaded(tags);
                        info.remote_tags_loaded = true;
                    }
                    if app.fetching {
                        app.fetching = false;
                    } else {
                        app.decrement_implicit_network();
                    }
                } else if let Some(err_msg) = msg.strip_prefix("REMOTE_TAGS_ERR:") {
                    crate::debug_log::warn(format!(
                        "Network Action: Fetching remote tags failed: {}",
                        err_msg
                    ));
                    if app.fetching {
                        app.set_error(err_msg.to_string());
                        app.fetching = false;
                    } else {
                        app.decrement_implicit_network();
                    }
                } else {
                    let is_err = msg.starts_with("Fetch failed:")
                        || msg.starts_with("Pull failed:")
                        || msg.starts_with("Push failed:")
                        || msg.starts_with("Failed to")
                        || msg.contains("failed");

                    if is_err {
                        let has_conflict = msg.contains("conflict") || msg.contains("CONFLICT");
                        crate::debug_log::error(format!(
                            "Network Action: Operation failed: {}",
                            msg
                        ));
                        app.set_error(msg);
                        if has_conflict {
                            app.detail_focus = DetailSection::Conflicts;
                        }
                    } else {
                        crate::debug_log::info(format!(
                            "Network Action: Operation succeeded: {}",
                            msg
                        ));
                        app.status_message = Some(msg);
                    }
                    app.fetching = false;
                    app.resync_detail();
                }
            } else {
                app.fetching = false;
            }
        }

        while let Ok((path, detail)) = app.detail_rx.try_recv() {
            app.detail_cache.insert(
                path.clone(),
                DetailCache { detail: detail.clone(), loaded_at: std::time::Instant::now() },
            );

            let is_currently_loading = Some(&path) == app.loading_repo_path.as_ref();
            let is_currently_open = if let Some(current) = &app.current_detail {
                match current {
                    repo::ItemDetail::Repo { resolved, .. }
                    | repo::ItemDetail::Missing { resolved, .. }
                    | repo::ItemDetail::Directory { resolved, .. }
                    | repo::ItemDetail::Error { resolved, .. } => {
                        resolved.to_string_lossy() == path
                    }
                }
            } else {
                false
            };

            if is_currently_loading || is_currently_open {
                app.apply_detail_snapshot(detail);
                if is_currently_loading {
                    app.loading_repo_path = None;
                }
            }
        }

        while let Ok(updates) = app.status_refresh_rx.try_recv() {
            app.background_refresh_running = false;
            for (idx, path, status) in updates {
                if app.config.items.get(idx) == Some(&path) {
                    if idx < app.statuses.len() {
                        app.statuses[idx] = status;
                    }
                }
            }
        }

        while let Ok(results) = app.global_search_rx.try_recv() {
            app.global_search_results = results;
            app.global_search_running = false;
            app.global_search_focus_input = false;
            app.global_search_selection = 0;
        }

        let mut tab_updated = false;
        while let Ok((path, tab_idx, payload)) = app.tab_rx.try_recv() {
            crate::debug_log::info(format!(
                "Received tab payload: tab_idx={}, path={}",
                tab_idx, path
            ));
            if let Some(repo::ItemDetail::Repo { resolved, info }) = &mut app.current_detail {
                let resolved_str = resolved.to_string_lossy().to_string();
                if resolved_str == path {
                    crate::debug_log::info(format!("Paths match! Updating tab_idx={}", tab_idx));
                    tab_updated = true;
                    if tab_idx < 10 {
                        info.tab_loading[tab_idx] = false;
                        info.tab_loaded_at[tab_idx] = Some(std::time::Instant::now());
                    }
                    match payload {
                        repo::TabPayload::Files(res) => {
                            info.files = match res {
                                Ok(files) => repo::TabData::Loaded(files),
                                Err(e) => repo::TabData::Error(e),
                            };
                        }
                        repo::TabPayload::Graph(res) => {
                            info.graph_lines = match res {
                                Ok(lines) => repo::TabData::Loaded(lines),
                                Err(e) => repo::TabData::Error(e),
                            };
                        }
                        repo::TabPayload::Branches { local, remote } => {
                            info.local_branches = match local {
                                Ok(b) => repo::TabData::Loaded(b),
                                Err(e) => repo::TabData::Error(e),
                            };
                            info.remote_branches = match remote {
                                Ok(b) => repo::TabData::Loaded(b),
                                Err(e) => repo::TabData::Error(e),
                            };
                        }
                        repo::TabPayload::Tags { local, remote } => {
                            info.local_tags = match local {
                                Ok(t) => repo::TabData::Loaded(t),
                                Err(e) => repo::TabData::Error(e),
                            };
                            if !info.remote_tags_loaded {
                                info.remote_tags = match remote {
                                    Ok(t) => repo::TabData::Loaded(t),
                                    Err(e) => repo::TabData::Error(e),
                                };
                            }
                        }
                        repo::TabPayload::Remotes(res) => {
                            info.remotes = match res {
                                Ok(r) => repo::TabData::Loaded(r),
                                Err(e) => repo::TabData::Error(e),
                            };
                        }
                        repo::TabPayload::Stashes(res) => {
                            info.stashes = match res {
                                Ok(s) => repo::TabData::Loaded(s),
                                Err(e) => repo::TabData::Error(e),
                            };
                        }
                        repo::TabPayload::Worktrees(res) => {
                            info.worktrees = match res {
                                Ok(w) => repo::TabData::Loaded(w),
                                Err(e) => repo::TabData::Error(e),
                            };
                        }
                        repo::TabPayload::Submodules(res) => {
                            info.submodules = match res {
                                Ok(s) => repo::TabData::Loaded(s),
                                Err(e) => repo::TabData::Error(e),
                            };
                        }
                        repo::TabPayload::Reflog(res) => {
                            info.reflog = match res {
                                Ok(r) => repo::TabData::Loaded(r),
                                Err(e) => repo::TabData::Error(e),
                            };
                        }
                        repo::TabPayload::ForgeIssues(res) => {
                            info.forge_issues = match res {
                                Ok(issues) => repo::TabData::Loaded(issues),
                                Err(e) => repo::TabData::Error(e),
                            };
                        }
                        repo::TabPayload::ForgePRs(res) => {
                            info.forge_prs = match res {
                                Ok(prs) => repo::TabData::Loaded(prs),
                                Err(e) => repo::TabData::Error(e),
                            };
                            app.load_comments_for_selected_pr();
                        }
                        repo::TabPayload::PRComments(res) => {
                            if let Ok(comments) = res {
                                app.forge_pr_comments = Some(comments);
                            } else {
                                app.forge_pr_comments = None;
                            }
                            app.forge_pr_comments_loading = false;
                        }
                        repo::TabPayload::Overview(res) => match res {
                            Ok((stats, capped)) => {
                                info.committer_stats = repo::TabData::Loaded(stats);
                                info.committer_stats_limit_reached = capped;
                            }
                            Err(e) => {
                                info.committer_stats = repo::TabData::Error(e);
                            }
                        },
                    }
                }
            }
        }
        if tab_updated {
            app.update_cache_from_current_detail();
            app.rebuild_visible_files();
        }

        if app.pending_git_app {
            app.pending_git_app = false;
            if let Some(item) = app.config.items.get(app.selected_index) {
                let path = repo::expand_tilde(item);

                let raw_res = crossterm::terminal::disable_raw_mode();
                let exec_res = crossterm::execute!(
                    std::io::stdout(),
                    crossterm::terminal::LeaveAlternateScreen,
                    crossterm::event::DisableMouseCapture
                );
                let cursor_res = terminal.show_cursor();

                if raw_res.is_ok() && exec_res.is_ok() && cursor_res.is_ok() {
                    let git_app_name = &app.config.git_app;
                    let mut cmd = if cfg!(target_os = "windows") {
                        let mut c = std::process::Command::new("cmd");
                        c.arg("/c").arg(git_app_name);
                        c
                    } else {
                        std::process::Command::new(git_app_name)
                    };
                    let status = cmd.current_dir(&path).status();

                    let _ = crossterm::terminal::enable_raw_mode();
                    let _ = crossterm::execute!(
                        std::io::stdout(),
                        crossterm::terminal::EnterAlternateScreen,
                        crossterm::event::EnableMouseCapture
                    );
                    let _ = terminal.clear();

                    match status {
                        Ok(s) if s.success() => {
                            app.status_message = Some(format!("Returned from {}", git_app_name));
                            app.refresh_selected_status();
                        }
                        Ok(_) => {
                            app.status_message =
                                Some(format!("{} exited with error", git_app_name));
                            app.refresh_selected_status();
                        }
                        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                            app.set_error(format!("{} is not found in the system", git_app_name));
                        }
                        Err(e) => {
                            app.set_error(format!("Could not run {}: {}", git_app_name, e));
                        }
                    }
                }
            }
        }

        if app.pending_terminal {
            app.pending_terminal = false;

            let mut paths_to_open = Vec::new();
            if !app.multi_selected.is_empty() {
                paths_to_open = app.multi_selected.iter().cloned().collect::<Vec<_>>();
                app.multi_selected.clear();
            } else if let Some(item) = app.config.items.get(app.selected_index) {
                paths_to_open.push(item.clone());
            }

            if !paths_to_open.is_empty() {
                let raw_res = crossterm::terminal::disable_raw_mode();
                let exec_res = crossterm::execute!(
                    std::io::stdout(),
                    crossterm::terminal::LeaveAlternateScreen,
                    crossterm::event::DisableMouseCapture
                );
                let cursor_res = terminal.show_cursor();

                if raw_res.is_ok() && exec_res.is_ok() && cursor_res.is_ok() {
                    let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());

                    // Helpers to translate active ACCENT color to ANSI codes
                    let accent_color = crate::ui::style::ACCENT();
                    let ansi_normal = match accent_color {
                        ratatui::style::Color::Black => "\x1b[30m",
                        ratatui::style::Color::Red => "\x1b[31m",
                        ratatui::style::Color::Green => "\x1b[32m",
                        ratatui::style::Color::Yellow => "\x1b[33m",
                        ratatui::style::Color::Blue => "\x1b[34m",
                        ratatui::style::Color::Magenta => "\x1b[35m",
                        ratatui::style::Color::Cyan => "\x1b[36m",
                        ratatui::style::Color::Gray => "\x1b[37m",
                        ratatui::style::Color::DarkGray => "\x1b[90m",
                        ratatui::style::Color::LightRed => "\x1b[91m",
                        ratatui::style::Color::LightGreen => "\x1b[92m",
                        ratatui::style::Color::LightYellow => "\x1b[93m",
                        ratatui::style::Color::LightBlue => "\x1b[94m",
                        ratatui::style::Color::LightMagenta => "\x1b[95m",
                        ratatui::style::Color::LightCyan => "\x1b[96m",
                        ratatui::style::Color::White => "\x1b[97m",
                        _ => "\x1b[36m",
                    };
                    let ansi_bold = match accent_color {
                        ratatui::style::Color::Black => "\x1b[1;30m",
                        ratatui::style::Color::Red => "\x1b[1;31m",
                        ratatui::style::Color::Green => "\x1b[1;32m",
                        ratatui::style::Color::Yellow => "\x1b[1;33m",
                        ratatui::style::Color::Blue => "\x1b[1;34m",
                        ratatui::style::Color::Magenta => "\x1b[1;35m",
                        ratatui::style::Color::Cyan => "\x1b[1;36m",
                        ratatui::style::Color::Gray => "\x1b[1;37m",
                        ratatui::style::Color::DarkGray => "\x1b[1;90m",
                        ratatui::style::Color::LightRed => "\x1b[1;91m",
                        ratatui::style::Color::LightGreen => "\x1b[1;92m",
                        ratatui::style::Color::LightYellow => "\x1b[1;93m",
                        ratatui::style::Color::LightBlue => "\x1b[1;94m",
                        ratatui::style::Color::LightMagenta => "\x1b[1;95m",
                        ratatui::style::Color::LightCyan => "\x1b[1;96m",
                        ratatui::style::Color::White => "\x1b[1;97m",
                        _ => "\x1b[1;36m",
                    };

                    for item in &paths_to_open {
                        let path = repo::expand_tilde(item);
                        let repo_name =
                            path.file_name().and_then(|n| n.to_str()).unwrap_or("repository");

                        // Update terminal title for the subshell
                        if app.config.compatibility_mode {
                            let _ = crossterm::execute!(
                                std::io::stdout(),
                                crossterm::terminal::SetTitle(format!(
                                    "[Gitwig] Shell ({})",
                                    repo_name
                                ))
                            );
                        } else {
                            let _ = crossterm::execute!(
                                std::io::stdout(),
                                crossterm::terminal::SetTitle(format!(
                                    "🌿 Gitwig Shell ({})",
                                    repo_name
                                ))
                            );
                        }

                        // Determine borders and branding based on compatibility mode
                        let banner_width = 80;
                        let inner_width = banner_width - 6; // 74 chars
                        let (top_border, left_border, right_border, bottom_border, gitwig_prefix) =
                            if app.config.compatibility_mode {
                                (
                                    "-".repeat(banner_width),
                                    "|",
                                    "|",
                                    "-".repeat(banner_width),
                                    "[Gitwig]",
                                )
                            } else {
                                (
                                    "".to_string() + &"".repeat(banner_width - 2) + "",
                                    "",
                                    "",
                                    "".to_string() + &"".repeat(banner_width - 2) + "",
                                    "🌿 Gitwig",
                                )
                            };

                        println!();
                        println!("{}{}\x1b[0m", ansi_normal, top_border);

                        let line1_text = format!(
                            "{} Subshell — Type 'exit' or press Ctrl+D to return to Gitwig",
                            gitwig_prefix
                        );
                        let padding1 = inner_width.saturating_sub(line1_text.chars().count());
                        println!(
                            "{}{}\x1b[0m  {}{}\x1b[0m{}  {}{}\x1b[0m",
                            ansi_normal,
                            left_border,
                            ansi_bold,
                            line1_text,
                            " ".repeat(padding1),
                            ansi_normal,
                            right_border
                        );

                        let line2_text = format!("Workspace: {}", path.display());
                        let line2_chars: Vec<char> = line2_text.chars().collect();
                        let display_path = if line2_chars.len() > inner_width {
                            let keep_len = inner_width - 15;
                            let truncated: String =
                                line2_chars[line2_chars.len() - keep_len..].iter().collect();
                            format!("Workspace: ...{}", truncated)
                        } else {
                            line2_text
                        };
                        let padding2 = inner_width.saturating_sub(display_path.chars().count());
                        println!(
                            "{}{}\x1b[0m  \x1b[2m{}\x1b[0m{}  {}{}\x1b[0m",
                            ansi_normal,
                            left_border,
                            display_path,
                            " ".repeat(padding2),
                            ansi_normal,
                            right_border
                        );

                        println!("{}{}\x1b[0m", ansi_normal, bottom_border);
                        println!();

                        let _ = std::process::Command::new(&shell)
                            .current_dir(&path)
                            .env("GITWIG", "1")
                            .env("GITWIG_SHELL", "1")
                            .status();
                    }

                    // Restore Gitwig terminal title
                    if app.config.compatibility_mode {
                        let _ = crossterm::execute!(
                            std::io::stdout(),
                            crossterm::terminal::SetTitle("[Gitwig]")
                        );
                    } else {
                        let _ = crossterm::execute!(
                            std::io::stdout(),
                            crossterm::terminal::SetTitle("🌿 Gitwig")
                        );
                    }

                    let _ = crossterm::terminal::enable_raw_mode();
                    let _ = crossterm::execute!(
                        std::io::stdout(),
                        crossterm::terminal::EnterAlternateScreen,
                        crossterm::event::EnableMouseCapture
                    );
                    let _ = terminal.clear();

                    app.status_message = Some("Returned from terminal".to_string());
                    app.refresh_selected_status();
                }
            }
        }

        if let Some((repo_path, target)) = app.pending_interactive_rebase.take() {
            let raw_res = crossterm::terminal::disable_raw_mode();
            let exec_res = crossterm::execute!(
                std::io::stdout(),
                crossterm::terminal::LeaveAlternateScreen,
                crossterm::event::DisableMouseCapture
            );
            let cursor_res = terminal.show_cursor();

            if raw_res.is_ok() && exec_res.is_ok() && cursor_res.is_ok() {
                let status = std::process::Command::new("git")
                    .env("GIT_TERMINAL_PROMPT", "0")
                    .env("GIT_SSH_COMMAND", crate::config::ssh_command_val())
                    .arg("rebase")
                    .arg("-i")
                    .arg(&target)
                    .current_dir(&repo_path)
                    .status();

                let _ = crossterm::terminal::enable_raw_mode();
                let _ = crossterm::execute!(
                    std::io::stdout(),
                    crossterm::terminal::EnterAlternateScreen,
                    crossterm::event::EnableMouseCapture
                );
                let _ = terminal.clear();

                match status {
                    Ok(s) if s.success() => {
                        app.status_message =
                            Some("Interactive rebase completed successfully".to_string());
                    }
                    Ok(s) => {
                        app.status_message = Some(format!(
                            "Rebase exited with status: {}. Check terminal/git status.",
                            s
                        ));
                    }
                    Err(e) => {
                        app.status_message = Some(format!("Failed to run git rebase: {}", e));
                    }
                }
                if let Some(item) = app.config.items.get(app.selected_index) {
                    let new_status = repo::inspect_summary(item);
                    if let Some(slot) = app.statuses.get_mut(app.selected_index) {
                        *slot = new_status;
                    }
                }
                app.refresh_detail();
            }
        }
        if let Some(file_rel_path) = app.pending_editor_file.take() {
            if let Some(repo::ItemDetail::Repo { resolved, .. }) = &app.current_detail {
                let repo_path = resolved.clone();
                let file_path = repo_path.join(&file_rel_path);
                let repo_path_str = repo_path.to_string_lossy().to_string();
                let editor = app
                    .config
                    .repo_configs
                    .get(&repo_path_str)
                    .and_then(|c| c.editor.clone())
                    .unwrap_or_else(|| app.config.editor.clone());

                let raw_res = crossterm::terminal::disable_raw_mode();
                let exec_res = crossterm::execute!(
                    std::io::stdout(),
                    crossterm::terminal::LeaveAlternateScreen,
                    crossterm::event::DisableMouseCapture
                );
                let cursor_res = terminal.show_cursor();

                if raw_res.is_ok() && exec_res.is_ok() && cursor_res.is_ok() {
                    let mut cmd = if cfg!(target_os = "windows") {
                        let mut c = std::process::Command::new("cmd");
                        c.arg("/c").arg(&editor);
                        c
                    } else {
                        std::process::Command::new(&editor)
                    };
                    let status = cmd.arg(&file_path).current_dir(&repo_path).status();

                    let _ = crossterm::terminal::enable_raw_mode();
                    let _ = crossterm::execute!(
                        std::io::stdout(),
                        crossterm::terminal::EnterAlternateScreen,
                        crossterm::event::EnableMouseCapture
                    );
                    let _ = terminal.clear();

                    match status {
                        Ok(s) if s.success() => {
                            app.status_message = Some(format!("Returned from {}", editor));
                            app.refresh_selected_status();
                        }
                        Ok(_) => {
                            app.status_message = Some(format!("{} exited with error", editor));
                            app.refresh_selected_status();
                        }
                        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                            app.set_error(format!("{} is not found in the system", editor));
                        }
                        Err(e) => {
                            app.set_error(format!("Could not run {}: {}", editor, e));
                        }
                    }
                }
            } else {
                app.status_message = Some("Not inside a repository".to_string());
            }
        }

        app.clamp_selection();

        let size = terminal.size()?;
        let area = Rect::new(0, 0, size.width, size.height);
        let inner_area = area.inner(Margin { vertical: 1, horizontal: 1 });

        let available_height = inner_area.height.saturating_sub(app.status_height());
        let mut list_height = if app.config.view_mode == crate::config::HomeViewMode::Compact {
            available_height.saturating_sub(1)
        } else {
            available_height
        };
        if !app.config.items.is_empty() {
            list_height = list_height.saturating_sub(2);
        }
        let rows = app.get_home_rows();
        let mut accumulated_height = 0;
        let mut visible_count = 0;
        let cols = if app.config.view_mode == crate::config::HomeViewMode::Tile {
            app.get_tile_cols()
        } else {
            1
        };
        let mut current_col = 0;

        for row in rows.iter().skip(app.scroll_top) {
            match row {
                crate::app::HomeRow::GroupHeader { .. } => {
                    if current_col > 0 {
                        accumulated_height += 4;
                        current_col = 0;
                    }
                    let h = if app.config.view_mode == crate::config::HomeViewMode::Compact {
                        1
                    } else {
                        2
                    };
                    if accumulated_height + h <= list_height {
                        accumulated_height += h;
                        visible_count += 1;
                    } else {
                        break;
                    }
                }
                crate::app::HomeRow::Repo { .. } => {
                    if app.config.view_mode == crate::config::HomeViewMode::Tile {
                        if current_col == 0 {
                            if accumulated_height + 4 <= list_height {
                                accumulated_height += 4;
                            } else {
                                break;
                            }
                        }
                        visible_count += 1;
                        current_col += 1;
                        if current_col == cols {
                            current_col = 0;
                        }
                    } else {
                        let h = if app.config.view_mode == crate::config::HomeViewMode::Compact {
                            1
                        } else {
                            4
                        };
                        if accumulated_height + h <= list_height {
                            accumulated_height += h;
                            visible_count += 1;
                        } else {
                            break;
                        }
                    }
                }
            }
        }
        if visible_count == 0 && !rows.is_empty() {
            visible_count = 1;
        }
        app.clamp_scroll(visible_count);
        app.clamp_help_scroll(area.height as usize);
        app.clamp_legend_scroll();

        app.trigger_tab_load_if_needed(app.detail_tab);

        // Capture panel rects from the draw pass for mouse hit-testing.
        let mut detail_areas = DetailAreas::default();
        let mut main_areas = Vec::new();
        let mut global_summary_area = None;
        terminal.draw(|f| {
            ui::draw(
                f,
                &app,
                area,
                inner_area,
                visible_count,
                &mut detail_areas,
                &mut main_areas,
                &mut global_summary_area,
            )
        })?;
        app.detail_areas = detail_areas;
        app.main_areas = main_areas;
        app.global_summary_area = global_summary_area;

        // Transient feedback disappears after one frame, unless we are fetching.
        if app.fetching || app.implicit_network_count > 0 {
            if app.fetching && app.status_message.is_none() {
                app.status_message = Some("Executing Git operation...".to_string());
            }
            app.fetch_progress = (app.fetch_progress + 5) % 105;
        } else {
            if !app.fetching && app.mode != Mode::Settings {
                app.status_message = None;
            }
            app.fetch_progress = 0;
        }

        if let Some(completed_at) = app.bulk_fetch_completed_at {
            if completed_at.elapsed().as_secs() >= 30 {
                app.bulk_fetch_results.clear();
                app.bulk_fetch_completed_at = None;
            }
        }

        let poll_dur = if !app.bulk_fetching.is_empty() || app.fetching {
            std::time::Duration::from_millis(80)
        } else {
            std::time::Duration::from_millis(app.config.poll_interval_ms)
        };
        if event::poll(poll_dur)? {
            match event::read()? {
                Event::Key(key) => {
                    if key.kind == crossterm::event::KeyEventKind::Press
                        && !input::handle_key(&mut app, key, visible_count)
                    {
                        return Ok(());
                    }
                }
                Event::Mouse(mouse) => {
                    crate::mouse::handle_mouse(&mut app, mouse);
                }
                _ => {}
            }
        }
    }
}

fn is_tool_installed(name: &str) -> bool {
    #[cfg(target_os = "windows")]
    let cmd = "where";
    #[cfg(not(target_os = "windows"))]
    let cmd = "which";

    std::process::Command::new(cmd)
        .arg(name)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

pub(crate) fn copy_to_clipboard(text: &str) -> Result<(), String> {
    #[cfg(target_os = "macos")]
    {
        use std::io::Write;
        let mut child = std::process::Command::new("pbcopy")
            .stdin(std::process::Stdio::piped())
            .spawn()
            .map_err(|e| e.to_string())?;
        if let Some(mut stdin) = child.stdin.take() {
            stdin.write_all(text.as_bytes()).map_err(|e| e.to_string())?;
        }
        child.wait().map_err(|e| e.to_string())?;
        Ok(())
    }
    #[cfg(target_os = "windows")]
    {
        use std::io::Write;
        let mut child = std::process::Command::new("clip")
            .stdin(std::process::Stdio::piped())
            .spawn()
            .map_err(|e| e.to_string())?;
        if let Some(mut stdin) = child.stdin.take() {
            stdin.write_all(text.as_bytes()).map_err(|e| e.to_string())?;
        }
        child.wait().map_err(|e| e.to_string())?;
        Ok(())
    }
    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
    {
        use std::io::Write;
        if let Ok(mut child) = std::process::Command::new("xclip")
            .arg("-selection")
            .arg("clipboard")
            .stdin(std::process::Stdio::piped())
            .spawn()
        {
            if let Some(mut stdin) = child.stdin.take() {
                if stdin.write_all(text.as_bytes()).is_ok() {
                    let _ = child.wait();
                    return Ok(());
                }
            }
        }
        if let Ok(mut child) = std::process::Command::new("xsel")
            .arg("-ib")
            .stdin(std::process::Stdio::piped())
            .spawn()
        {
            if let Some(mut stdin) = child.stdin.take() {
                if stdin.write_all(text.as_bytes()).is_ok() {
                    let _ = child.wait();
                    return Ok(());
                }
            }
        }
        Err("Could not find xclip or xsel on Linux system".to_string())
    }
}

impl App {
    pub fn is_msi_install(&self) -> bool {
        #[cfg(target_os = "windows")]
        {
            if let Ok(exe_path) = std::env::current_exe() {
                let path_str = exe_path.to_string_lossy().to_lowercase();
                if path_str.contains("program files") || path_str.contains("programfiles") {
                    return true;
                }
            }
        }
        false
    }

    pub fn is_cargo_install(&self) -> bool {
        if let Ok(exe_path) = std::env::current_exe() {
            let path_str = exe_path.to_string_lossy().to_lowercase();
            if path_str.contains(".cargo")
                && (path_str.contains("/bin") || path_str.contains("\\bin"))
            {
                return true;
            }
        }
        false
    }

    pub fn is_homebrew_install(&self) -> bool {
        if let Ok(exe_path) = std::env::current_exe() {
            let path_str = exe_path.to_string_lossy().to_lowercase();
            if path_str.contains("homebrew")
                || path_str.contains("cellar")
                || path_str.contains("linuxbrew")
            {
                return true;
            }
        }
        false
    }

    pub fn can_self_update(&self) -> bool {
        !self.is_msi_install() && !self.is_cargo_install() && !self.is_homebrew_install()
    }

    pub fn refresh_blame_if_shown(&mut self) {
        if self.file_tree.show_blame {
            self.load_blame_for_selected_file();
        } else {
            self.file_tree.file_blame = None;
            self.file_tree.blamed_file_path = None;
        }
    }

    pub fn load_blame_for_selected_file(&mut self) {
        if let Some(item) =
            self.file_tree.visible_files.get(self.file_tree.file_list_selection).cloned()
        {
            if !item.is_dir {
                let repo_path = match &self.current_detail {
                    Some(crate::repo::ItemDetail::Repo { resolved, .. }) => Some(resolved.clone()),
                    _ => None,
                };
                if let Some(resolved) = repo_path {
                    if let Ok(blame) = crate::repo::get_file_blame(&resolved, &item.full_path) {
                        self.file_tree.file_blame = Some(blame);
                        self.file_tree.blamed_file_path = Some(item.full_path);
                        return;
                    }
                }
            }
        }
        self.file_tree.file_blame = None;
        self.file_tree.blamed_file_path = None;
    }

    pub fn item_height(&self) -> u16 {
        if self.config.compact_view { 1 } else { ITEM_HEIGHT }
    }

    pub fn increment_implicit_network(&mut self) {
        self.implicit_network_count = self.implicit_network_count.saturating_add(1);
    }

    pub fn decrement_implicit_network(&mut self) {
        self.implicit_network_count = self.implicit_network_count.saturating_sub(1);
    }

    pub fn trigger_update_check(&mut self) {
        self.trigger_update_check_internal(true);
    }

    pub fn trigger_update_check_internal(&mut self, manual: bool) {
        let reason = if manual { "user triggered" } else { "scheduled" };
        crate::debug_log::info(format!(
            "Network Action: Checking for updates (manual={}, {})",
            manual, reason
        ));
        self.update_check_manual = manual;
        if manual {
            self.status_message = Some("Checking for updates...".to_string());
        } else {
            self.increment_implicit_network();
        }
        let tx_clone = self.tx.clone();
        std::thread::spawn(move || {
            let res = (|| -> Result<String, Box<dyn std::error::Error>> {
                let output = std::process::Command::new("curl")
                    .arg("--max-time")
                    .arg("5")
                    .arg("-fsSL")
                    .arg("https://raw.githubusercontent.com/tareqmy/gitwig/master/.version")
                    .output();
                if let Ok(out) = output {
                    if out.status.success() {
                        let version = String::from_utf8_lossy(&out.stdout).trim().to_string();
                        if !version.is_empty() {
                            return Ok(version);
                        }
                    }
                }
                let output = std::process::Command::new("wget")
                    .arg("--timeout=5")
                    .arg("-qO-")
                    .arg("https://raw.githubusercontent.com/tareqmy/gitwig/master/.version")
                    .output();
                if let Ok(out) = output {
                    if out.status.success() {
                        let version = String::from_utf8_lossy(&out.stdout).trim().to_string();
                        if !version.is_empty() {
                            return Ok(version);
                        }
                    }
                }
                Err("Failed to query update version".into())
            })();
            if let Ok(latest_version) = res {
                crate::debug_log::info(format!(
                    "Network Action: Update check succeeded. Latest version: v{}",
                    latest_version
                ));
                let _ = tx_clone.send(format!("UPDATE_CHECK:{}", latest_version));
            } else {
                crate::debug_log::warn("Network Action: Update check failed");
                let _ = tx_clone.send("UPDATE_CHECK_FAILED:".to_string());
            }
        });
    }

    pub fn trigger_self_update(&mut self) {
        if self.is_msi_install() {
            self.error_message = Some(
                "Self-update is disabled for system-wide Windows installations.\n\n\
                 Please download the latest release from:\n\
                 https://github.com/tareqmy/gitwig/releases"
                    .to_string(),
            );
            self.mode = self.previous_mode.take().unwrap_or(self.mode);
            return;
        }

        if self.is_cargo_install() {
            self.error_message = Some(
                "Self-update is disabled for Cargo installations.\n\n\
                 Please update by running:\n\
                 cargo install gitwig"
                    .to_string(),
            );
            self.mode = self.previous_mode.take().unwrap_or(self.mode);
            return;
        }

        if self.is_homebrew_install() {
            self.error_message = Some(
                "Self-update is disabled for Homebrew installations.\n\n\
                 Please update by running:\n\
                 brew upgrade gitwig"
                    .to_string(),
            );
            self.mode = self.previous_mode.take().unwrap_or(self.mode);
            return;
        }

        crate::debug_log::info("Network Action: Triggering self-update");
        self.fetching = true;
        self.status_message = Some("Updating Gitwig...".to_string());
        self.mode = self.previous_mode.take().unwrap_or(self.mode);

        let version = self.update_available.clone();
        let tx = self.tx.clone();
        std::thread::spawn(move || {
            let res = (|| -> Result<String, Box<dyn std::error::Error>> {
                use sha2::{Digest, Sha256};
                use std::fs::File;
                use std::io::Read;

                let target_ref = match version {
                    Some(ref v) => {
                        if v.starts_with('v') {
                            v.clone()
                        } else {
                            format!("v{}", v)
                        }
                    }
                    None => "master".to_string(),
                };

                let temp_dir = std::env::temp_dir();
                let unique_id = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_nanos();
                let is_windows = cfg!(target_os = "windows");
                let script_name = if is_windows { "install.ps1" } else { "install.sh" };
                let sha_name = if is_windows { "install.ps1.sha256" } else { "install.sh.sha256" };

                let script_path = temp_dir.join(format!("gitwig_{}_{}", unique_id, script_name));
                let sha_path = temp_dir.join(format!("gitwig_{}_{}", unique_id, sha_name));

                let script_url = format!(
                    "https://raw.githubusercontent.com/tareqmy/gitwig/{}/scripts/{}",
                    target_ref, script_name
                );
                let sha_url = format!(
                    "https://raw.githubusercontent.com/tareqmy/gitwig/{}/scripts/{}",
                    target_ref, sha_name
                );

                // Helper to download via curl or wget
                let download =
                    |url: &str, dest: &std::path::Path| -> Result<(), Box<dyn std::error::Error>> {
                        let curl_res = std::process::Command::new("curl")
                            .arg("-fsSL")
                            .arg("-o")
                            .arg(dest)
                            .arg(url)
                            .output();
                        if let Ok(out) = curl_res {
                            if out.status.success() {
                                return Ok(());
                            }
                        }
                        let wget_res = std::process::Command::new("wget")
                            .arg("-q")
                            .arg("-O")
                            .arg(dest)
                            .arg(url)
                            .output();
                        match wget_res {
                            Ok(out) if out.status.success() => Ok(()),
                            _ => Err(format!("Failed to download {}", url).into()),
                        }
                    };

                // Download files
                download(&script_url, &script_path)?;
                download(&sha_url, &sha_path)?;

                // Compute SHA-256 of downloaded script
                let mut file = File::open(&script_path)?;
                let mut hasher = Sha256::new();
                let mut buffer = [0; 1024];
                loop {
                    let count = file.read(&mut buffer)?;
                    if count == 0 {
                        break;
                    }
                    hasher.update(&buffer[..count]);
                }
                let computed_hash = format!("{:02x}", hasher.finalize());

                // Read expected hash
                let mut sha_content = String::new();
                File::open(&sha_path)?.read_to_string(&mut sha_content)?;
                let expected_hash = sha_content
                    .split_whitespace()
                    .next()
                    .ok_or_else(|| "Empty checksum file".to_string())?
                    .trim();

                if computed_hash != expected_hash {
                    let _ = std::fs::remove_file(&script_path);
                    let _ = std::fs::remove_file(&sha_path);
                    return Err(format!(
                        "Checksum verification failed!\nExpected: {}\nGot: {}",
                        expected_hash, computed_hash
                    )
                    .into());
                }

                // Execute the verified script
                let output = if is_windows {
                    std::process::Command::new("powershell")
                        .arg("-NoProfile")
                        .arg("-ExecutionPolicy")
                        .arg("Bypass")
                        .arg("-File")
                        .arg(&script_path)
                        .output()
                } else {
                    std::process::Command::new("sh").arg(&script_path).output()
                };

                let _ = std::fs::remove_file(&script_path);
                let _ = std::fs::remove_file(&sha_path);

                match output {
                    Ok(out) => {
                        if out.status.success() {
                            Ok("Gitwig updated successfully! Please restart the application."
                                .to_string())
                        } else {
                            let err_msg = String::from_utf8_lossy(&out.stderr).trim().to_string();
                            Err(format!("Update failed: {}", err_msg).into())
                        }
                    }
                    Err(e) => Err(format!("Update failed: {}", e).into()),
                }
            })();

            match res {
                Ok(success_msg) => {
                    let _ = tx.send(format!("UPDATE_SUCCESS:{}", success_msg));
                }
                Err(err) => {
                    let _ = tx.send(format!("UPDATE_ERROR:{}", err));
                }
            }
        });
    }
}

fn is_newer_version(current: &str, latest: &str) -> bool {
    let parse = |s: &str| -> Vec<u32> {
        s.trim_start_matches('v').split('.').map(|part| part.parse::<u32>().unwrap_or(0)).collect()
    };
    let cur_parts = parse(current);
    let lat_parts = parse(latest);
    for (c, l) in cur_parts.iter().zip(lat_parts.iter()) {
        if l > c {
            return true;
        } else if c > l {
            return false;
        }
    }
    lat_parts.len() > cur_parts.len()
}

fn run_directory_scan(
    start_dir: std::path::PathBuf,
    max_depth: usize,
    excludes: Vec<String>,
    tx: std::sync::mpsc::Sender<String>,
    bulk: bool,
) {
    std::thread::spawn(move || {
        let root = start_dir;
        let mut count = 0;

        fn has_git_subdirs(dir: &std::path::Path, excludes: &[String]) -> bool {
            if let Ok(entries) = std::fs::read_dir(dir) {
                for entry in entries.flatten() {
                    if let Ok(file_type) = entry.file_type() {
                        if file_type.is_dir() {
                            let path = entry.path();
                            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                                if name.starts_with('.') && name != "." && name != ".." {
                                    if !path.join(".git").exists() {
                                        continue;
                                    }
                                }
                                if excludes
                                    .iter()
                                    .any(|ex| name == ex || path.to_string_lossy().contains(ex))
                                {
                                    continue;
                                }
                            }
                            if path.join(".git").exists() {
                                return true;
                            }
                        }
                    }
                }
            }
            false
        }

        fn scan(
            dir: &std::path::Path,
            depth: usize,
            max_depth: usize,
            excludes: &[String],
            tx: &std::sync::mpsc::Sender<String>,
            count: &mut usize,
            bulk: bool,
        ) {
            *count += 1;
            if (*count).is_multiple_of(50) {
                let _ = tx.send(format!("REPO_SCAN_COUNT:{}", *count));
            }

            let git_dir = dir.join(".git");
            if git_dir.exists() {
                if !bulk {
                    let name = dir
                        .file_name()
                        .map(|n| n.to_string_lossy().into_owned())
                        .unwrap_or_else(|| dir.to_string_lossy().into_owned());
                    let path = dir.to_string_lossy().into_owned();
                    let _ = tx.send(format!("REPO_SCAN_FOUND:{}|||{}", name, path));
                }
                return;
            } else if bulk && has_git_subdirs(dir, excludes) {
                let name = dir
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_else(|| dir.to_string_lossy().into_owned());
                let path = dir.to_string_lossy().into_owned();
                let _ = tx.send(format!("REPO_SCAN_FOUND:{}|||{}", name, path));
            }

            if depth >= max_depth {
                return;
            }

            if let Ok(entries) = std::fs::read_dir(dir) {
                for entry in entries.flatten() {
                    if let Ok(file_type) = entry.file_type() {
                        if file_type.is_dir() {
                            let path = entry.path();
                            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                                if name.starts_with('.') && name != "." && name != ".." {
                                    if !path.join(".git").exists() {
                                        continue;
                                    }
                                }
                                if excludes
                                    .iter()
                                    .any(|ex| name == ex || path.to_string_lossy().contains(ex))
                                {
                                    continue;
                                }
                            }
                            scan(&path, depth + 1, max_depth, excludes, tx, count, bulk);
                        }
                    }
                }
            }
        }

        scan(&root, 0, max_depth, &excludes, &tx, &mut count, bulk);
        let _ = tx.send(format!("REPO_SCAN_COUNT:{}", count));
        let _ = tx.send("REPO_SCAN_COMPLETE:".to_string());
    });
}