rs-hop 0.3.0

Fuzzy-finder TUI to jump between git repositories and folders
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
//! TUI front end: the three-tab list view, its key handling and overlays.
//!
//! [`App`] owns the resolved config, the [`RepoService`] and the view state
//! (active tab, cursor, sort, live filter and the current overlay). [`run`]
//! draws, polls events on a short timeout and drains background git-status
//! updates so the list shows immediately and fills in as `git` reports. Opening
//! an entry returns a [`RunOutcome`] the composition root acts on after the
//! terminal is restored.

pub mod appframe;
pub mod bindings;
pub mod columns;
pub mod detail;
pub mod form;
pub mod git_columns;
pub mod help;
pub mod path_picker;
pub mod presentation;
pub mod preview;
pub mod scroll;
pub mod section_picker;
pub mod sections_modal;
pub mod sections_view;
pub mod skin;
pub mod table;
pub mod terminal;
pub mod widgets;

use std::collections::{HashMap, HashSet};
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
use std::time::{Duration, Instant};

use chrono::{DateTime, Local};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use unicode_width::UnicodeWidthStr;

pub use terminal::{Tui, TuiEvent};

use ratada::input::InputField;
use ratada::nav::cycle;
use ratada::quit::{self, QuitConfirm, QuitKind};
use ratada::shortcut_hints;
use ratada::spinner::Spinner;

use crate::config::Config;
use crate::domain::backup;
use crate::domain::filter::{Tab, TabKind, belongs_to_tab, fuzzy_indices};
use crate::domain::path_repair::nearest_existing_on_disk;
use crate::domain::repo::{self, Repo, RepoKind};
use crate::domain::sections;
use crate::domain::sort::{
    SortContext, SortDir, SortMode, StatsLookup, sort_indices,
};
use crate::keymap::{Action, Keymap};
use crate::service::preview_service::{self, PreviewLog};
use crate::service::repo_service::RepoService;
use crate::service::stats_service::{
    self, CodeUpdate, GitStatsUpdate, StatsCache, spawn_code_stats,
    spawn_git_stats,
};
use crate::service::status_service::{self, StatusUpdate, spawn_refresh};
use crate::service::ui_state_service::{self, TabView, UiState};
use crate::service::zip_service::{ZipJob, ZipUpdate, spawn_zip};
use crate::storage::git_client::GitClient;
use crate::theme::Skin;
use crate::tui::columns::ColumnSet;
use crate::tui::form::{BulkDraft, FormResult, RepoDraft, RepoForm};
use crate::tui::path_picker::{PathPicker, PickerResult};
use crate::tui::presentation::{
    FieldView, IconSet, field_spans, github_url, render_empty_hint,
};
use crate::tui::preview::PreviewLayout;
use crate::tui::section_picker::{SectionPickResult, SectionPicker};
use crate::tui::sections_modal::{SectionsAction, SectionsModal};
use crate::tui::skin::Colors;
use crate::tui::widgets::{
    ConfirmModal, ConfirmResult, PromptResult, SelectModal, SelectResult,
    TextPrompt,
};
use crate::util::opener::launch_git_tool;
use crate::util::paths::expand_tilde;

/// How long a transient status message stays visible.
const STATUS_TTL: Duration = Duration::from_secs(4);

/// How long one refresh-spinner frame is shown.
const SPINNER_INTERVAL: Duration = Duration::from_millis(120);

/// The label in front of the live filter in the status band.
const FILTER_LABEL: &str = "filter: ";
/// The hint after the live filter in the status band.
const FILTER_HINT: &str = "   Enter open · Esc clear";
/// Cells the status band loses to `appframe`'s horizontal padding.
const STATUS_PADDING: usize = 2;

/// The columns the live filter's value may occupy on a `width`-wide terminal:
/// the status band minus its padding, its label and its trailing hint. At least
/// one column, so the caret always has somewhere to sit.
fn filter_value_width(width: u16) -> usize {
    (width as usize)
        .saturating_sub(STATUS_PADDING)
        .saturating_sub(FILTER_LABEL.chars().count())
        .saturating_sub(FILTER_HINT.chars().count())
        .max(1)
}

/// Progress-bar label while a background status refresh runs.
const REFRESH_LABEL: &str = "refreshing";

/// Progress-bar label while a background ZIP backup runs.
const ZIP_LABEL: &str = "zipping";

/// Padding width of the percentage in the progress text, so `XX %` keeps a
/// constant width from `0` through `100`.
const PERCENT_WIDTH: usize = 3;

/// Separator between the percentage/counts prefix and the entry name.
const PROGRESS_SEPARATOR: &str = " - ";

/// How long the cursor must rest on an entry before its preview `git log` is
/// fetched, so quick scrolling does not spawn a fetch per row.
const PREVIEW_DEBOUNCE: Duration = Duration::from_millis(120);

/// How many `git log` lines the preview shows.
const PREVIEW_LOG_LINES: usize = 5;

/// What the user chose to do, acted on by the composition root after the
/// terminal is restored.
pub enum RunOutcome {
    /// Quit without opening anything.
    Quit,
    /// Path written; just exit so the shell can `cd`.
    Jumped,
    /// Path written; launch the git tool in this directory, then exit.
    LaunchGitTool(PathBuf),
    /// Launch the git tool in this directory as an overlay (the loop suspends
    /// the terminal, runs the tool, then returns to the list).
    LaunchGitToolInline(PathBuf),
    /// Open this file in the editor, then exit.
    OpenFile(PathBuf),
    /// Open this file with the platform's default application, then exit.
    OpenWith(PathBuf),
}

/// An active modal layered over the list.
enum Overlay {
    None,
    Help,
    Confirm(ConfirmModal, Vec<usize>),
    Prompt(TextPrompt, usize),
    /// Boxed: the form's three text fields make it far larger than any other
    /// overlay, and `Overlay` is held by value in `App`. The target says whether
    /// it adds, edits one entry, or bulk-edits several.
    Form(Box<RepoForm>, EditTarget),
    Picker(PathPicker, PickerIntent),
    /// The fuzzy section picker over a form in progress (the form is stashed so
    /// it resumes with the chosen section).
    SectionPicker(Box<SectionPicker>, Box<RepoForm>, EditTarget),
    /// The list of errored entries; the vec maps rows to service indices.
    Errors(SelectModal, Vec<usize>),
    /// The action menu for an errored entry at the given service index.
    ErrorAction(SelectModal, usize),
    /// The jump-to-section picker; the vec maps rows to entry display positions.
    SectionJump(SelectModal, Vec<usize>),
    /// The manage-sections list.
    Sections(SectionsModal),
    /// A prompt to add or rename a section.
    SectionPrompt(TextPrompt, SectionPromptKind),
    /// A confirm dialog to delete the named section.
    SectionDelete(ConfirmModal, String),
    /// The sort picker; the vec maps rows to modes.
    Sort(SelectModal, Vec<SortMode>),
}

/// Why the section prompt is open.
enum SectionPromptKind {
    /// Create a new section.
    New,
    /// Rename the section with this current name.
    Rename(String),
}

/// Why the path picker is open.
enum PickerIntent {
    /// Repair the path of the entry at this index.
    Repair(usize),
    /// Fill the path field of a form already in progress.
    FormPath(Box<RepoForm>, EditTarget),
}

/// What a form is editing: a new entry, one existing entry, or several at once.
#[derive(Clone)]
enum EditTarget {
    /// A new entry (the add form).
    Add,
    /// The single entry at this service index.
    One(usize),
    /// Several entries (bulk edit), by service index.
    Bulk(Vec<usize>),
}

/// The interactive application state.
pub struct App {
    config: Config,
    service: RepoService,
    icons: IconSet,
    /// The resolved skin (config-driven palette + glyphs) for the panel frame.
    skin: Skin,
    /// The colour roles resolved once from the active theme.
    colors: Colors,
    /// The resolved key bindings, built once so `[keys]` warnings are logged
    /// once and dispatch never rebuilds the map per key press.
    keymap: Keymap,
    git_client: Arc<dyn GitClient>,
    cache_path: PathBuf,
    /// Path of the ZIP-backup fingerprint cache (in the state directory).
    zip_cache_path: PathBuf,
    ui_state_path: PathBuf,
    tab: Tab,
    cursor: usize,
    /// Per-kind view settings (sort, columns, grouping, fav-float), indexed by
    /// `tab.kind_index()`; a kind's active and archive views share its slot.
    tab_state: [TabState; 2],
    filtering: bool,
    filter: InputField,
    overlay: Overlay,
    /// The help overlay's scroll position, kept across frames.
    help_scroll: scroll::Scroll,
    status_msg: Option<(String, Instant)>,
    loading: Option<(usize, usize)>,
    /// The progress-bar label for the current `loading` operation (a refresh or
    /// a ZIP backup).
    loading_label: &'static str,
    /// The entry currently being processed, shown in the progress-bar text.
    loading_detail: Option<String>,
    /// Display width of the longest entry name in the current `loading` run, so
    /// the progress text can reserve a stable block and pin the `XX %` column.
    loading_name_width: usize,
    /// Receives background ZIP-backup progress, drained each loop.
    zip_rx: Option<Receiver<ZipUpdate>>,
    /// Last ZIP-backup time per repo path, shown in the "ZIP Backup" column.
    /// Loaded once at start and after each backup (no per-frame filesystem I/O).
    zip_backups: HashMap<PathBuf, DateTime<Local>>,
    cache_generated_at: Option<DateTime<Local>>,
    last_fetched: Option<DateTime<Local>>,
    /// All in-flight background status refreshes, drained each loop. Several may
    /// run at once, so starting one never cancels another.
    status_jobs: Vec<RefreshJob>,
    /// Paths across all active refreshes that have not been updated yet (drive
    /// the per-row spinner). Empty when no refresh is running.
    refreshing: HashSet<PathBuf>,
    /// The per-row refresh spinner, stepped by [`App::tick`].
    spinner: Spinner,
    /// When the spinner last stepped, so it animates at a steady rate rather
    /// than at whatever rate the run loop happens to wake up.
    spinner_at: Instant,
    /// Multi-selection by service index (survives sort/filter). Empty = none.
    selected: HashSet<usize>,
    /// Anchor display row for `Shift`-range selection.
    anchor: Option<usize>,
    /// Scroll offset of the sectioned Files list, kept across frames so the
    /// cursor pages within the viewport.
    list_offset: std::cell::Cell<usize>,
    /// Scroll offset of the table view (git tabs, Archive, filtered Files),
    /// kept across frames so the cursor only scrolls once it reaches an edge.
    table_offset: std::cell::Cell<usize>,
    /// Whether the startup mode permits background refreshes (drives the
    /// first-visit refresh of the Git Repos / Archive tabs).
    auto_refresh: bool,
    /// Tabs whose entries have been refreshed since start, so a tab is only
    /// auto-refreshed on its first visit.
    refreshed_tabs: HashSet<Tab>,
    /// Paths of `Path`-kind entries found missing by the on-demand existence
    /// check (`r` on the Files tab). Empty until checked; never run on start.
    files_missing: HashSet<PathBuf>,
    /// Whether slugs are shown in their own dim-italic column after the name.
    show_slugs: bool,
    /// When on, only git entries with a status change are shown (session-only).
    changes_only: bool,
    /// The cursor entry's path per tab, restored when returning to that tab.
    tab_focus: HashMap<Tab, PathBuf>,
    /// The last rendered list height (entry rows), for page-wise navigation.
    list_height: std::cell::Cell<usize>,
    /// Where the detail panel sits and how big it is (persisted).
    preview: PreviewLayout,
    /// The detail panel's scroll position, kept across frames.
    preview_scroll: scroll::Scroll,
    /// Path of the statistics cache in the state directory.
    stats_path: PathBuf,
    /// Cached code and history statistics, seeded from disk at start.
    stats: StatsCache,
    /// Receives background code statistics, drained each loop.
    code_rx: Option<Receiver<CodeUpdate>>,
    /// Receives background history statistics, drained each loop.
    git_stats_rx: Option<Receiver<GitStatsUpdate>>,
    /// Paths a statistics worker has not reported yet (drive the cell spinner).
    computing: HashSet<PathBuf>,
    /// Cached `git log` excerpts for the preview, keyed by entry path.
    preview_log: HashMap<PathBuf, Vec<String>>,
    /// Sender handed to the background log workers; kept alive so `preview_rx`
    /// never disconnects.
    preview_tx: Sender<PreviewLog>,
    /// Receives background preview-log results, drained each loop.
    preview_rx: Receiver<PreviewLog>,
    /// Paths whose preview log is being fetched in the background (dedupe).
    preview_pending: HashSet<PathBuf>,
    /// The cursor path the preview is debouncing, with when it became current.
    preview_target: Option<PathBuf>,
    /// When `preview_target` last changed, for the debounce window.
    preview_target_at: Instant,
}

/// The view settings a kind remembers, shared between its active and archive
/// views (persisted per kind in the UI state).
#[derive(Debug, Clone, Copy)]
struct TabState {
    /// The list sort mode.
    sort: SortMode,
    /// Which way the sort runs.
    sort_dir: SortDir,
    /// Which columns the table shows.
    columns: ColumnSet,
    /// Whether entries are grouped into sections (off = flat global sort).
    grouped: bool,
    /// Whether favourites float to the top of each group.
    fav_float: bool,
}

/// Builds a [`TabState`] from a persisted per-kind [`TabView`], resolving the
/// column-set key and clamping it to what `kind` supports.
fn tab_state_from(view: &TabView, kind: TabKind) -> TabState {
    TabState {
        sort: view.sort,
        sort_dir: view.sort_dir,
        columns: ColumnSet::from_key(&view.columns)
            .available_on(kind.active_tab()),
        grouped: view.grouped,
        fav_float: view.fav_float,
    }
}

/// One in-flight background status refresh. Several may run concurrently, so a
/// new refresh never cancels one already running.
struct RefreshJob {
    /// Receives this worker's `StatusUpdate`s.
    rx: Receiver<StatusUpdate>,
    /// Whether this job's completion updates the global `fetched_at` time (a
    /// full refresh with `fetch`; a subset refresh never does).
    fetched: bool,
    /// Whether this job feeds the full-width progress bar.
    bar: bool,
    /// Paths of this job not yet reported, so its spinners can be cleared if the
    /// job ends before every path is done.
    remaining: HashSet<PathBuf>,
}

/// How the status is sourced on start.
pub enum StartupStatus {
    /// Show only the cache; do not run git at all (`--cached`).
    Cached,
    /// Refresh status in the background, optionally fetching first.
    Refresh {
        /// Whether to `git fetch` before gathering status.
        fetch: bool,
    },
}

impl App {
    /// Builds the app, hydrates status from the cache and, unless `--cached` or
    /// example mode, starts a background refresh (fetching first when asked).
    pub fn new(
        config: Config,
        service: RepoService,
        git_client: Arc<dyn GitClient>,
        cache_path: PathBuf,
        ui_state_path: PathBuf,
        startup: StartupStatus,
    ) -> Self {
        let icons = IconSet::new(config.appearance.glyphs);
        let skin = config.skin();
        let colors = Colors::from_palette(&skin.palette);
        let keymap = config.keymap();
        let cached = status_service::load_cache(&cache_path);
        let ui = ui_state_service::load(&ui_state_path);
        shortcut_hints::set_visible(ui.hints_visible);
        install_quit_confirmation(config.confirm_quit, skin);
        // The ZIP cache lives next to the git-info cache in the state directory.
        let state_dir = cache_path.parent().unwrap_or_else(|| Path::new("."));
        let zip_cache_path = state_dir.join("zip-manifests.toml");
        let stats_path = state_dir.join("stats-cache.toml");
        let stats = stats_service::load_cache(&stats_path);
        let mut service = service;
        service.apply_git_infos(&cached.infos);
        let (preview_tx, preview_rx) = mpsc::channel();
        let tab_state = [
            tab_state_from(&ui.git, TabKind::Git),
            tab_state_from(&ui.files, TabKind::Files),
        ];
        let mut app = App {
            config,
            service,
            icons,
            skin,
            colors,
            keymap,
            git_client,
            cache_path,
            zip_cache_path,
            ui_state_path,
            tab: ui.tab,
            cursor: 0,
            tab_state,
            filtering: false,
            filter: InputField::new(""),
            overlay: Overlay::None,
            help_scroll: scroll::Scroll::default(),
            status_msg: None,
            loading: None,
            loading_label: REFRESH_LABEL,
            loading_detail: None,
            loading_name_width: 0,
            zip_rx: None,
            zip_backups: HashMap::new(),
            cache_generated_at: cached.generated_at,
            last_fetched: cached.fetched_at,
            status_jobs: Vec::new(),
            refreshing: HashSet::new(),
            spinner: Spinner::new(),
            spinner_at: Instant::now(),
            selected: HashSet::new(),
            anchor: None,
            list_offset: std::cell::Cell::new(0),
            table_offset: std::cell::Cell::new(0),
            auto_refresh: false,
            refreshed_tabs: HashSet::new(),
            files_missing: HashSet::new(),
            show_slugs: ui.show_slugs,
            changes_only: false,
            tab_focus: HashMap::new(),
            list_height: std::cell::Cell::new(1),
            preview: PreviewLayout::from_state(
                &ui.preview,
                ui.preview_width_pct,
                ui.preview_height_rows,
            ),
            preview_scroll: scroll::Scroll::default(),
            stats_path,
            stats,
            code_rx: None,
            git_stats_rx: None,
            computing: HashSet::new(),
            preview_log: HashMap::new(),
            preview_tx,
            preview_rx,
            preview_pending: HashSet::new(),
            preview_target: None,
            preview_target_at: Instant::now(),
        };
        app.reload_zip_backups();
        app.start_stats();
        if let StartupStatus::Refresh { fetch } = startup
            && !app.config.example_mode
        {
            app.auto_refresh = true;
            // Honour fetch-on-start for a git tab; the Files tab does its
            // existence check via the first-visit hook below instead.
            if app.tab.kind() == TabKind::Git {
                app.start_refresh(fetch);
            }
        }
        // The active tab counts as its first visit (e.g. the Files existence
        // check, or a git refresh that was skipped above).
        app.refresh_tab_on_first_visit();
        app
    }

    /// The service indices belonging to the current tab (unsorted, unfiltered).
    fn tab_indices(&self) -> Vec<usize> {
        let repos = self.service.repos();
        (0..repos.len())
            .filter(|&i| belongs_to_tab(&repos[i], self.tab))
            .collect()
    }

    /// The current tab's kind's view settings.
    fn view(&self) -> &TabState {
        &self.tab_state[self.tab.kind_index()]
    }

    /// The current tab's kind's view settings, mutably.
    fn view_mut(&mut self) -> &mut TabState {
        &mut self.tab_state[self.tab.kind_index()]
    }

    /// The active sort mode for the current tab.
    fn sort(&self) -> SortMode {
        self.view().sort
    }

    /// The active sort direction for the current tab.
    fn sort_dir(&self) -> SortDir {
        self.view().sort_dir
    }

    /// The active column set for the current tab.
    fn columns(&self) -> ColumnSet {
        self.view().columns
    }

    /// Whether the current tab groups entries into sections.
    fn grouped(&self) -> bool {
        self.view().grouped
    }

    /// Whether the current tab floats favourites to the top.
    fn fav_float(&self) -> bool {
        self.view().fav_float
    }

    /// The ordered service indices visible in the current tab, after the sort
    /// or live fuzzy filter.
    fn ordered_view(&self) -> Vec<usize> {
        let repos = self.service.repos();
        let tab_indices = self.tab_indices();
        let query = self.filter.value();
        let mut indices = if self.filtering_active() {
            let subset: Vec<Repo> =
                tab_indices.iter().map(|&i| repos[i].clone()).collect();
            fuzzy_indices(&subset, query)
                .into_iter()
                .map(|pos| tab_indices[pos])
                .collect()
        } else if self.is_sectioned() {
            // Grouped view: entries by section, sorted within each group by the
            // active sort mode (favourites floated per the fav-float toggle).
            sections::flatten(&self.section_groups())
        } else {
            // Flat view: the chosen sort mode over the whole tab.
            let mut indices = tab_indices;
            sort_indices(repos, &mut indices, &self.sort_context());
            indices
        };
        if self.changes_only {
            indices.retain(|&i| self.shows_change(&repos[i]));
        }
        indices
    }

    /// Whether `repo` passes the changes-only filter (see [`repo_has_change`]).
    fn shows_change(&self, repo: &Repo) -> bool {
        repo_has_change(repo, self.config.example_mode)
    }

    /// Whether the live fuzzy filter is currently narrowing the list.
    fn filtering_active(&self) -> bool {
        self.filtering && !self.filter.value().trim().is_empty()
    }

    /// Whether the current view groups entries into sections (the grouping
    /// toggle is on and no live filter is narrowing the list).
    fn is_sectioned(&self) -> bool {
        self.grouped() && !self.filtering_active()
    }

    /// The display-ordered sections for the current tab: entries grouped by
    /// section (in the kind's stored section order), each group sorted by the
    /// active sort mode, with Ungrouped last. Sorting the flat index list first
    /// carries the order into each bucket (grouping keeps input order).
    fn section_groups(&self) -> Vec<sections::SectionGroup> {
        let repos = self.service.repos();
        let mut indices = self.tab_indices();
        sort_indices(repos, &mut indices, &self.sort_context());
        sections::group(
            self.service.sections(self.tab.repo_kind()),
            &indices,
            |i| repos[i].section.clone(),
        )
    }

    /// Opens the jump-to-section picker for the Files tab.
    fn open_section_jump(&mut self) {
        let groups = self.section_groups();
        if groups.len() < 2 {
            self.set_status("no other sections");
            return;
        }
        let starts = sections::section_starts(&groups);
        let labels: Vec<String> =
            groups.iter().map(|g| g.label.clone()).collect();
        let current =
            sections::current_section(&starts, self.cursor).unwrap_or(0);
        self.overlay = Overlay::SectionJump(
            SelectModal::new("Jump to section", labels, current),
            starts,
        );
    }

    /// Opens the manage-sections overlay at `cursor` over the current kind's
    /// sections.
    fn open_sections_manager_at(&mut self, cursor: usize) {
        let names = self.service.sections(self.tab.repo_kind()).to_vec();
        self.overlay = Overlay::Sections(SectionsModal::new(names, cursor));
    }

    /// Opens the manage-sections overlay at the first section.
    fn open_sections_manager(&mut self) {
        self.open_sections_manager_at(0);
    }

    /// Runs a section-manager action, reporting errors and re-opening the
    /// manager (or a sub-prompt) afterwards.
    fn run_sections_action(
        &mut self,
        modal: SectionsModal,
        action: SectionsAction,
    ) {
        match action {
            SectionsAction::Pending => {
                self.overlay = Overlay::Sections(modal);
            }
            SectionsAction::Close => {}
            SectionsAction::New => {
                self.overlay = Overlay::SectionPrompt(
                    TextPrompt::new("New section", "name", ""),
                    SectionPromptKind::New,
                );
            }
            SectionsAction::Rename(old) => {
                self.overlay = Overlay::SectionPrompt(
                    TextPrompt::new("Rename section", "name", &old),
                    SectionPromptKind::Rename(old),
                );
            }
            SectionsAction::Delete(name) => {
                let message = format!(
                    "Delete section \"{name}\"? Entries become Ungrouped."
                );
                self.overlay = Overlay::SectionDelete(
                    ConfirmModal::new("Delete section", message),
                    name,
                );
            }
            SectionsAction::Move { from, to } => {
                let repo_kind = self.tab.repo_kind();
                if let Err(error) =
                    self.service.move_section(repo_kind, from, to)
                {
                    self.set_status(format!("{error}"));
                }
                self.open_sections_manager_at(to);
            }
        }
    }

    /// Applies a submitted section prompt (new or rename) and re-opens the
    /// manager.
    fn submit_section_prompt(
        &mut self,
        kind: SectionPromptKind,
        value: String,
    ) {
        let repo_kind = self.tab.repo_kind();
        let result = match &kind {
            SectionPromptKind::New => {
                self.service.add_section(repo_kind, &value)
            }
            SectionPromptKind::Rename(old) => {
                self.service.rename_section(repo_kind, old, &value)
            }
        };
        if let Err(error) = result {
            self.set_status(format!("{error}"));
        }
        self.open_sections_manager();
    }

    /// The selected service index, if the view is non-empty.
    fn selected_index(&self) -> Option<usize> {
        self.ordered_view().get(self.cursor).copied()
    }

    /// Clamps the cursor into the current view length.
    fn clamp_cursor(&mut self, view_len: usize) {
        if view_len == 0 {
            self.cursor = 0;
        } else if self.cursor >= view_len {
            self.cursor = view_len - 1;
        }
    }

    /// Sets a transient status message.
    fn set_status(&mut self, message: impl Into<String>) {
        self.status_msg = Some((message.into(), Instant::now()));
    }

    /// Expires the status message once its TTL passes and steps the spinner.
    fn tick(&mut self) {
        if let Some((_, at)) = &self.status_msg
            && at.elapsed() > STATUS_TTL
        {
            self.status_msg = None;
        }
        if !self.refreshing.is_empty()
            && self.spinner_at.elapsed() >= SPINNER_INTERVAL
        {
            self.spinner.advance();
            self.spinner_at = Instant::now();
        }
    }

    /// Starts a background refresh over the current tab's entries (with the
    /// progress bar).
    fn start_refresh(&mut self, fetch: bool) {
        self.refreshed_tabs.insert(self.tab);
        let paths: Vec<PathBuf> = self
            .tab_indices()
            .iter()
            .filter_map(|&i| self.service.get(i).map(|r| r.path.clone()))
            .collect();
        self.refresh_paths(paths, fetch, true);
    }

    /// Starts a background refresh over `paths`, optionally fetching first.
    /// `show_bar` drives the full-width progress bar (and the global
    /// `fetched_at` update); a subset refresh passes `false`.
    fn refresh_paths(
        &mut self,
        paths: Vec<PathBuf>,
        fetch: bool,
        show_bar: bool,
    ) {
        if paths.is_empty() {
            return;
        }
        // Start the spinner only when nothing is already animating, so a running
        // refresh keeps its rhythm rather than jumping back to frame zero.
        if self.refreshing.is_empty() {
            self.spinner = Spinner::new();
            self.spinner_at = Instant::now();
        }
        self.refreshing.extend(paths.iter().cloned());
        if show_bar {
            self.loading_label = REFRESH_LABEL;
            self.loading_detail = None;
            self.loading = Some(match self.loading {
                Some((done, total)) => (done, total + paths.len()),
                None => (0, paths.len()),
            });
            self.loading_name_width =
                self.loading_name_width.max(self.max_name_width(&paths));
        }
        let remaining: HashSet<PathBuf> = paths.iter().cloned().collect();
        self.status_jobs.push(RefreshJob {
            rx: spawn_refresh(Arc::clone(&self.git_client), paths, fetch),
            // Only a full refresh updates the global "remote: fetched …" time.
            fetched: fetch && show_bar,
            bar: show_bar,
            remaining,
        });
    }

    /// Applies any pending background status updates without blocking. Drains
    /// every concurrent refresh job and drops the ones whose worker has ended.
    fn drain_status(&mut self) {
        if self.status_jobs.is_empty() {
            return;
        }
        let mut jobs = std::mem::take(&mut self.status_jobs);
        let mut any_finished = false;
        let mut fetched_finished = false;
        jobs.retain_mut(|job| {
            loop {
                match job.rx.try_recv() {
                    Ok(StatusUpdate::Started { path }) => {
                        self.loading_detail = Some(self.name_for_path(&path));
                    }
                    Ok(StatusUpdate::Done { path, info }) => {
                        self.service.set_git_info(&path, info);
                        self.refreshing.remove(&path);
                        job.remaining.remove(&path);
                        if job.bar
                            && let Some((done, _)) = &mut self.loading
                        {
                            *done += 1;
                        }
                    }
                    Err(TryRecvError::Empty) => return true,
                    Err(TryRecvError::Disconnected) => {
                        // Clear any spinners the worker never reported on.
                        for path in job.remaining.drain() {
                            self.refreshing.remove(&path);
                        }
                        any_finished = true;
                        fetched_finished |= job.fetched;
                        return false;
                    }
                }
            }
        });
        self.status_jobs = jobs;
        if any_finished {
            self.finish_refresh(fetched_finished);
        }
        // The bar lives as long as any bar-owning job runs.
        if !self.status_jobs.iter().any(|job| job.bar) {
            self.loading = None;
            self.loading_detail = None;
            self.loading_name_width = 0;
        }
        if self.status_jobs.is_empty() {
            self.refreshing.clear();
            // A tab switched to mid-refresh deferred its first-visit refresh;
            // run it now that every refresh has drained.
            self.refresh_tab_on_first_visit();
        }
    }

    /// Persists the full status cache after a refresh job finishes.
    fn finish_refresh(&mut self, fetched: bool) {
        let now = Local::now();
        self.cache_generated_at = Some(now);
        if fetched {
            self.last_fetched = Some(now);
        }
        // Persist the full current state (not just the finished job's paths),
        // so a single-entry refresh never drops the other entries' cache.
        let infos: Vec<(PathBuf, crate::domain::repo::GitInfo)> = self
            .service
            .repos()
            .iter()
            .filter_map(|repo| {
                repo.git_info.clone().map(|info| (repo.path.clone(), info))
            })
            .collect();
        let _ = status_service::save_cache(
            &self.cache_path,
            &infos,
            self.last_fetched,
        );
    }

    /// Whether any background status refresh is currently running.
    fn is_refreshing(&self) -> bool {
        !self.status_jobs.is_empty()
    }

    /// The display name of the entry at `path`, or its basename as a fallback.
    fn name_for_path(&self, path: &Path) -> String {
        self.service
            .repos()
            .iter()
            .find(|repo| repo.path == path)
            .map_or_else(|| repo::basename(path), Repo::display_name)
    }

    /// The widest display name among `paths`, used to reserve a stable block in
    /// the progress text so the `XX %` column does not move as names change.
    fn max_name_width(&self, paths: &[PathBuf]) -> usize {
        paths
            .iter()
            .map(|path| {
                UnicodeWidthStr::width(self.name_for_path(path).as_str())
            })
            .max()
            .unwrap_or(0)
    }

    /// The current spinner frame glyph, if a refresh is running.
    fn spinner_frame(&self) -> Option<&'static str> {
        if self.refreshing.is_empty() {
            return None;
        }
        Some(self.spinner.frame(self.config.appearance.glyphs))
    }
}

/// Runs the TUI event loop until the user opens an entry or quits.
///
/// # Errors
/// Returns an I/O error if drawing or reading from the terminal fails.
pub fn run(mut app: App, tui: &mut Tui) -> io::Result<RunOutcome> {
    loop {
        app.drain_status();
        app.drain_zip();
        app.drain_preview();
        app.drain_code_stats();
        app.drain_git_stats();
        app.request_preview_log();
        tui.draw(|frame| app.render(frame))?;
        // Poll faster while a refresh or backup runs (progress bar) or while a
        // preview log is being debounced/fetched, so updates land promptly.
        let timeout =
            if app.is_refreshing() || app.is_zipping() || app.is_computing() {
                80
            } else if app.preview_busy() {
                60
            } else {
                150
            };
        let outcome = match tui.poll_event(Duration::from_millis(timeout))? {
            // The hard `Ctrl+Q` is the escape hatch and never asks.
            Some(TuiEvent::Quit) => Some(RunOutcome::Quit),
            Some(TuiEvent::Key(key)) => match app.handle_key(key) {
                // A soft quit (`q`) goes through the confirmation policy;
                // `handle_key` has no `Tui`, so the loop asks.
                Some(RunOutcome::Quit) => {
                    let repaint = |frame: &mut Frame| app.render(frame);
                    quit::request(tui, QuitKind::Soft, &repaint)
                        .then_some(RunOutcome::Quit)
                }
                other => other,
            },
            Some(TuiEvent::Paste(text)) => {
                app.handle_paste(&text);
                None
            }
            Some(TuiEvent::Resize) | None => None,
        };
        if let Some(outcome) = outcome {
            match outcome {
                RunOutcome::LaunchGitToolInline(path) => {
                    app.run_git_inline(tui, &path)?;
                }
                other => return Ok(other),
            }
        }
        app.tick();
    }
}

/// Wires the toolkit's quit confirmation: `q` asks when `confirm_quit` is set,
/// `Ctrl+Q` never does. `skin` is `Copy` and hop never re-themes at runtime, so
/// the guard can hold it.
fn install_quit_confirmation(confirm_quit: bool, skin: Skin) {
    quit::set_confirm(if confirm_quit {
        QuitConfirm::Soft
    } else {
        QuitConfirm::Never
    });
    quit::set_guard(move |tui, _kind, bg| {
        ratada::modal::confirm(tui, &skin, " Quit hop? ", bg)
    });
}

/// The blank cell (or row) between the list and the detail panel.
const PANEL_GUTTER: u16 = 1;
/// The narrowest list a side panel may squeeze the body down to, in columns.
const MIN_LIST_COLS: u16 = 20;
/// The shortest list a bottom panel may squeeze the body down to, in rows.
/// A column count would leave no room for the panel at all on a normal screen.
const MIN_LIST_ROWS: u16 = 3;

/// The label of the group and help section listing the app-wide chords.
const GLOBAL_GROUP: &str = "Global";

/// The app-wide chords: this app's own keys, resolved through the keymap so a
/// `[keys]` override shows up here too, followed by the ones the toolkit
/// intercepts itself (the hints toggle and the hard quit).
fn global_group(keymap: &Keymap) -> (String, Vec<(String, String)>) {
    let mut hints = keymap.hints(&[Action::Help, Action::Quit]);
    hints.extend(shortcut_hints::global_bindings());
    (GLOBAL_GROUP.to_string(), hints)
}

impl App {
    /// Handles a key, returning an outcome when the loop should end.
    ///
    /// The toolkit's hints toggle is consumed first, so it works in every
    /// state; `Ctrl+Q` never reaches here (the `Tui` turns it into
    /// [`TuiEvent::Quit`]).
    fn handle_key(&mut self, key: KeyEvent) -> Option<RunOutcome> {
        if shortcut_hints::consume_toggle(key) {
            self.save_ui_state();
            return None;
        }
        match &mut self.overlay {
            Overlay::None => self.handle_list_key(key),
            _ => {
                self.handle_overlay_key(key);
                None
            }
        }
    }

    /// Routes a bracketed paste to the focused text field: the live filter, or
    /// the open overlay's own. Anything else has no caret to paste at, so the
    /// paste is dropped.
    fn handle_paste(&mut self, text: &str) {
        if self.filtering {
            self.filter.paste(text);
            // The wider query can drop the entry under the cursor, as after
            // any other filter edit.
            self.cursor = 0;
            return;
        }
        match &mut self.overlay {
            Overlay::Form(form, _) => form.paste(text),
            Overlay::Prompt(prompt, _) => prompt.paste(text),
            Overlay::SectionPrompt(prompt, _) => prompt.paste(text),
            Overlay::SectionPicker(picker, ..) => picker.paste(text),
            Overlay::Picker(picker, _) => picker.paste(text),
            _ => {}
        }
    }

    /// Handles a key for an open overlay, transitioning state as needed.
    fn handle_overlay_key(&mut self, key: KeyEvent) {
        let overlay = std::mem::replace(&mut self.overlay, Overlay::None);
        match overlay {
            Overlay::Help => {
                // `?`/`Esc` close it; everything else keeps it open, and the
                // movement keys scroll the (taller than the screen) list.
                if !matches!(key.code, KeyCode::Char('?') | KeyCode::Esc) {
                    self.help_scroll.handle_key(key);
                    self.overlay = Overlay::Help;
                }
            }
            Overlay::Confirm(modal, targets) => match modal.handle_key(key) {
                ConfirmResult::Yes => self.do_delete(targets),
                ConfirmResult::No => {}
                ConfirmResult::Pending => {
                    self.overlay = Overlay::Confirm(modal, targets);
                }
            },
            Overlay::Prompt(mut prompt, index) => {
                match prompt.handle_key(key) {
                    PromptResult::Submit(value) => {
                        self.do_set_slug(index, value)
                    }
                    PromptResult::Cancel => {}
                    PromptResult::Pending => {
                        self.overlay = Overlay::Prompt(prompt, index);
                    }
                }
            }
            Overlay::Form(mut form, target) => match form.handle_key(key) {
                FormResult::Save(draft) => {
                    self.do_save_form(save_index(&target), draft);
                }
                FormResult::SaveBulk(bulk) => self.do_save_bulk(target, bulk),
                FormResult::PickPath => {
                    self.open_form_path_picker(form, target);
                }
                FormResult::PickSection => {
                    self.open_section_picker(form, target);
                }
                FormResult::Cancel => {}
                FormResult::Pending => {
                    self.overlay = Overlay::Form(form, target);
                }
            },
            Overlay::SectionPicker(mut picker, form, target) => {
                match picker.handle_key(key) {
                    SectionPickResult::Picked(section) => {
                        self.resume_form_with_section(form, target, section);
                    }
                    SectionPickResult::Cancel => {
                        self.overlay = Overlay::Form(form, target);
                    }
                    SectionPickResult::Pending => {
                        self.overlay =
                            Overlay::SectionPicker(picker, form, target);
                    }
                }
            }
            Overlay::Picker(mut picker, intent) => {
                match picker.handle_key(key) {
                    PickerResult::Selected(path) => {
                        self.do_picked(intent, path);
                    }
                    PickerResult::Cancel => {}
                    PickerResult::Pending => {
                        self.overlay = Overlay::Picker(picker, intent);
                    }
                }
            }
            Overlay::Errors(mut modal, indices) => {
                match modal.handle_key(key) {
                    SelectResult::Selected(row) => {
                        if let Some(&index) = indices.get(row) {
                            self.open_error_action(index);
                        }
                    }
                    SelectResult::Cancel => {}
                    SelectResult::Pending => {
                        self.overlay = Overlay::Errors(modal, indices);
                    }
                }
            }
            Overlay::ErrorAction(mut modal, index) => {
                match modal.handle_key(key) {
                    SelectResult::Selected(action) => {
                        self.run_error_action(index, action);
                    }
                    SelectResult::Cancel => {}
                    SelectResult::Pending => {
                        self.overlay = Overlay::ErrorAction(modal, index);
                    }
                }
            }
            Overlay::Sort(mut modal, modes) => match modal.handle_key(key) {
                SelectResult::Selected(row) => {
                    if let Some(&mode) = modes.get(row) {
                        self.apply_sort(mode);
                    }
                }
                SelectResult::Cancel => {}
                SelectResult::Pending => {
                    self.overlay = Overlay::Sort(modal, modes);
                }
            },
            Overlay::SectionJump(mut modal, starts) => {
                match modal.handle_key(key) {
                    SelectResult::Selected(row) => {
                        if let Some(&pos) = starts.get(row) {
                            self.cursor = pos;
                        }
                    }
                    SelectResult::Cancel => {}
                    SelectResult::Pending => {
                        self.overlay = Overlay::SectionJump(modal, starts);
                    }
                }
            }
            Overlay::Sections(mut modal) => {
                let action = modal.handle_key(key);
                self.run_sections_action(modal, action);
            }
            Overlay::SectionPrompt(mut prompt, kind) => {
                match prompt.handle_key(key) {
                    PromptResult::Submit(value) => {
                        self.submit_section_prompt(kind, value);
                    }
                    PromptResult::Cancel => self.open_sections_manager(),
                    PromptResult::Pending => {
                        self.overlay = Overlay::SectionPrompt(prompt, kind);
                    }
                }
            }
            Overlay::SectionDelete(confirm, name) => {
                match confirm.handle_key(key) {
                    ConfirmResult::Yes => {
                        let repo_kind = self.tab.repo_kind();
                        if let Err(error) =
                            self.service.delete_section(repo_kind, &name)
                        {
                            self.set_status(format!("{error}"));
                        }
                        self.open_sections_manager();
                    }
                    ConfirmResult::No => self.open_sections_manager(),
                    ConfirmResult::Pending => {
                        self.overlay = Overlay::SectionDelete(confirm, name);
                    }
                }
            }
            Overlay::None => {}
        }
    }

    /// Handles a key for the list view (no overlay open).
    ///
    /// Keys the keymap cannot express are consumed first (see
    /// [`App::handle_untracked_key`]); everything else resolves to an
    /// [`Action`], so a `[keys]` override actually rebinds it.
    fn handle_list_key(&mut self, key: KeyEvent) -> Option<RunOutcome> {
        if self.filtering {
            return self.handle_filter_key(key);
        }
        if self.handle_untracked_key(key) {
            return None;
        }
        let action = self.keymap.action_for(&key)?;
        self.run_action(action)
    }

    /// Handles the keys that have no [`Action`], returning whether one matched.
    ///
    /// `Shift`+arrow cannot be a binding because [`KeyChord`](crate::keymap::
    /// KeyChord) ignores the shift modifier, so it has to be caught before the
    /// keymap turns a shifted arrow into a plain cursor move. Tab cycling and
    /// `Esc` are structural, not user-facing actions.
    fn handle_untracked_key(&mut self, key: KeyEvent) -> bool {
        // Only a bare `Shift`+arrow extends: `Ctrl`/`Alt`+arrow are real chords
        // the keymap owns, and they keep winning as they did before.
        let shift = key.modifiers == KeyModifiers::SHIFT;
        match key.code {
            KeyCode::Up if shift => self.extend_selection(-1),
            KeyCode::Down if shift => self.extend_selection(1),
            KeyCode::Tab => self.cycle_tab(1),
            KeyCode::BackTab => self.cycle_tab(-1),
            KeyCode::Esc => self.clear_selection(),
            _ => return false,
        }
        true
    }

    /// Runs `action` on the list view, returning an outcome when the loop should
    /// end.
    ///
    /// The context-dependent actions branch on the active tab here rather than
    /// on the key, so a rebound key keeps its meaning: `SectionJump` only jumps
    /// where the list is sectioned, and `Reload`/`ReloadFetch` re-check paths on
    /// the files tabs but refresh git status on the git tabs.
    fn run_action(&mut self, action: Action) -> Option<RunOutcome> {
        match action {
            Action::Up => self.move_cursor(-1),
            Action::Down => self.move_cursor(1),
            Action::Top => self.cursor_to_edge(false),
            Action::Bottom => self.cursor_to_edge(true),
            Action::PageUp => self.page(-1, false),
            Action::PageDown => self.page(1, false),
            Action::HalfPageUp => self.page(-1, true),
            Action::HalfPageDown => self.page(1, true),
            Action::TabGit => self.select_kind(TabKind::Git),
            Action::TabFiles => self.select_kind(TabKind::Files),
            Action::ToggleSelect => self.toggle_select(),
            Action::Jump | Action::JumpCd => return self.open_selected(false),
            Action::Open => return self.open_selected(true),
            Action::GitTool => return self.open_git_inline(),
            Action::OpenApp => return self.force_open_with(),
            Action::Filter => self.filtering = true,
            Action::ChangesFilter => self.toggle_changes_only(),
            Action::Github => self.open_on_github(),
            Action::Preview => self.toggle_preview(),
            Action::PreviewPosition => self.flip_preview_position(),
            Action::PreviewScrollUp => self.scroll_preview(-1),
            Action::PreviewScrollDown => self.scroll_preview(1),
            Action::PreviewShrink => self.resize_preview(-1),
            Action::PreviewGrow => self.resize_preview(1),
            Action::Columns => self.cycle_columns(),
            Action::Sort => self.open_sort_picker(),
            Action::ToggleGrouping => self.toggle_grouping(),
            Action::ToggleFavFloat => self.toggle_fav_float(),
            Action::SectionJump if self.is_sectioned() => {
                self.open_section_jump();
            }
            Action::SectionJump => {}
            Action::ManageSections => self.open_sections_manager(),
            Action::ReorderUp => self.move_entry(-1),
            Action::ReorderDown => self.move_entry(1),
            Action::Add => self.open_add(),
            Action::Edit => self.open_edit_form(),
            Action::Delete => self.open_delete_confirm(),
            Action::Undo => self.undo(),
            Action::ToggleFav => self.toggle_fav(),
            Action::Zip => self.zip_targets(),
            Action::ZipAll => self.zip_all(),
            Action::Archive => self.toggle_archive(),
            Action::Slug => self.open_slug_prompt(),
            Action::ToggleSlugs => self.toggle_slugs(),
            Action::CopyPath => self.copy_path(),
            Action::RepairPath => self.open_repair_picker(),
            Action::Errors => self.open_error_list(),
            Action::Reload | Action::ReloadFetch
                if self.tab.kind() == TabKind::Files =>
            {
                self.check_files_existence();
            }
            Action::Reload => self.reload_status(false),
            Action::ReloadFetch => self.reload_status(true),
            Action::RefreshOne => self.refresh_targets(false),
            Action::RefreshOneFetch => self.refresh_targets(true),
            Action::Help => {
                self.help_scroll.reset();
                self.overlay = Overlay::Help;
            }
            Action::Quit => return Some(RunOutcome::Quit),
        }
        None
    }

    /// Handles a key while the live filter is active.
    fn handle_filter_key(&mut self, key: KeyEvent) -> Option<RunOutcome> {
        match key.code {
            KeyCode::Esc => {
                self.filtering = false;
                self.filter = InputField::new("");
                self.cursor = 0;
            }
            KeyCode::Up => self.move_cursor(-1),
            KeyCode::Down => self.move_cursor(1),
            KeyCode::Enter => return self.open_selected(false),
            _ => {
                if self.filter.handle_key(key) {
                    self.cursor = 0;
                }
            }
        }
        None
    }

    /// Selects `kind`: switches to its active view, or toggles between active
    /// and archive when that kind is already showing (the double-press of
    /// `1`/`2`).
    fn select_kind(&mut self, kind: TabKind) {
        let target = if self.tab.kind() == kind {
            self.tab.toggle_archived()
        } else {
            kind.active_tab()
        };
        self.switch_tab(target);
    }

    /// Toggles grouping for the current kind (grouped <-> flat) and persists it.
    fn toggle_grouping(&mut self) {
        let grouped = self.view().grouped;
        self.view_mut().grouped = !grouped;
        let len = self.ordered_view().len();
        self.clamp_cursor(len);
        self.save_ui_state();
    }

    /// Toggles floating favourites for the current kind and persists it.
    fn toggle_fav_float(&mut self) {
        let fav_float = self.view().fav_float;
        self.view_mut().fav_float = !fav_float;
        let len = self.ordered_view().len();
        self.clamp_cursor(len);
        self.save_ui_state();
    }

    /// Switches to `tab`, remembering the current tab's cursor entry and
    /// restoring the target tab's, clearing the selection and persisting state.
    fn switch_tab(&mut self, tab: Tab) {
        if tab == self.tab {
            return;
        }
        self.remember_focus();
        self.tab = tab;
        self.clear_selection();
        // Each tab is a distinct list; drop the previous tab's scroll offset.
        self.list_offset.set(0);
        self.table_offset.set(0);
        self.restore_focus();
        let clamped = self.columns().available_on(tab);
        self.view_mut().columns = clamped;
        self.preview_scroll.reset();
        self.save_ui_state();
        self.start_stats();
        self.refresh_tab_on_first_visit();
    }

    /// Cycles to the next/previous active tab (`Tab`/`Shift+Tab`). Archives are
    /// not part of the cycle; an archive view normalises to its active sibling
    /// first.
    fn cycle_tab(&mut self, delta: isize) {
        let base = self.tab.active();
        let current = Tab::ACTIVE.iter().position(|t| *t == base).unwrap_or(0);
        let next = cycle(current, Tab::ACTIVE.len(), delta);
        self.switch_tab(Tab::ACTIVE[next]);
    }

    /// Records the current tab's cursor entry by path, to restore on return.
    fn remember_focus(&mut self) {
        if let Some(index) = self.selected_index()
            && let Some(repo) = self.service.get(index)
        {
            let path = repo.path.clone();
            self.tab_focus.insert(self.tab, path);
        }
    }

    /// Restores the cursor to the remembered entry for the current tab (by
    /// path), or the top when none is remembered or it is no longer visible.
    fn restore_focus(&mut self) {
        self.cursor = 0;
        let Some(path) = self.tab_focus.get(&self.tab).cloned() else {
            return;
        };
        let view = self.ordered_view();
        let repos = self.service.repos();
        if let Some(pos) = view.iter().position(|&i| repos[i].path == path) {
            self.cursor = pos;
        }
    }

    /// Runs the per-tab first-visit work: the files tabs check that their paths
    /// still exist; the git tabs refresh status (without fetching), mirroring
    /// the startup refresh of the initially active tab. Each runs once per
    /// session; a git refresh is deferred while another is in flight (and
    /// retried when it finishes) so switching tabs never aborts it.
    fn refresh_tab_on_first_visit(&mut self) {
        if self.refreshed_tabs.contains(&self.tab) {
            return;
        }
        if self.tab.kind() == TabKind::Files {
            self.refreshed_tabs.insert(self.tab);
            if !self.config.example_mode {
                self.check_files_existence();
            }
            return;
        }
        if !self.auto_refresh || self.is_refreshing() {
            return;
        }
        self.start_refresh(false);
    }

    /// Everything a sort needs, borrowed from the statistics caches.
    fn sort_context(&self) -> SortContext<'_> {
        SortContext {
            mode: self.sort(),
            dir: self.sort_dir(),
            float_favs: self.fav_float(),
            now: Local::now().timestamp(),
            stats: StatsLookup {
                code: &self.stats.code,
                git: &self.stats.git,
            },
        }
    }

    /// The modes the sort picker offers: the four general ones, then the
    /// columns of the active set - so a user only sorts by what is on screen.
    fn sort_modes(&self) -> Vec<SortMode> {
        let mut modes = vec![
            SortMode::Name,
            SortMode::Recent,
            SortMode::Frecency,
            SortMode::Custom,
        ];
        modes.extend_from_slice(self.columns().sort_modes());
        modes
    }

    /// Opens the sort picker, with the cursor on the active mode.
    fn open_sort_picker(&mut self) {
        let (sort, dir) = (self.sort(), self.sort_dir());
        let modes = self.sort_modes();
        let cursor = modes.iter().position(|m| *m == sort).unwrap_or(0);
        let items: Vec<String> = modes
            .iter()
            .map(|mode| {
                if *mode == sort {
                    format!("{}  {}", mode.title(), dir.arrow())
                } else {
                    mode.title().to_string()
                }
            })
            .collect();
        self.overlay =
            Overlay::Sort(SelectModal::new(" Sort by ", items, cursor), modes);
    }

    /// Applies a picked sort mode. Re-picking the active column flips the
    /// direction; a fresh statistics column starts descending, because "which
    /// is the biggest" is the question it answers.
    fn apply_sort(&mut self, mode: SortMode) {
        let dir = if mode == self.sort() {
            self.sort_dir().flip()
        } else if mode.is_statistic() {
            SortDir::Desc
        } else {
            SortDir::Asc
        };
        let view = self.view_mut();
        view.sort = mode;
        view.sort_dir = dir;
        self.save_ui_state();
    }

    /// Cycles the table's column set and starts the worker the new set needs.
    fn cycle_columns(&mut self) {
        let next = self.columns().next(self.tab);
        self.view_mut().columns = next;
        self.save_ui_state();
        self.start_stats();
    }

    /// Toggles the Slug column display and persists it for the next run.
    fn toggle_slugs(&mut self) {
        self.show_slugs = !self.show_slugs;
        self.save_ui_state();
    }

    /// Toggles the changes-only filter (git entries with a status change),
    /// keeping the cursor in range. Session-only (not persisted).
    fn toggle_changes_only(&mut self) {
        self.changes_only = !self.changes_only;
        self.clear_selection();
        let len = self.ordered_view().len();
        self.clamp_cursor(len);
        self.set_status(if self.changes_only {
            "showing changed repos only"
        } else {
            "showing all entries"
        });
    }

    /// Shows or hides the detail panel and persists the choice.
    fn toggle_preview(&mut self) {
        self.preview.toggle();
        self.preview_scroll.reset();
        self.save_ui_state();
    }

    /// Moves the detail panel to the other side.
    fn flip_preview_position(&mut self) {
        self.preview.flip_position();
        self.save_ui_state();
    }

    /// Grows or shrinks the detail panel along its current axis.
    fn resize_preview(&mut self, step: i16) {
        if !self.preview.visible {
            return;
        }
        self.preview.resize(step);
        self.save_ui_state();
    }

    /// Scrolls the detail panel.
    fn scroll_preview(&mut self, delta: i32) {
        if self.preview.visible {
            self.preview_scroll.scroll_by(delta);
        }
    }

    /// The persisted per-kind view block for tab-state index `i`.
    fn tab_view_of(&self, i: usize) -> TabView {
        let state = &self.tab_state[i];
        TabView {
            sort: state.sort,
            sort_dir: state.sort_dir,
            columns: state.columns.as_key().to_string(),
            grouped: state.grouped,
            fav_float: state.fav_float,
        }
    }

    /// Persists the per-kind view settings, active tab, slug display, preview
    /// mode and whether the hint footer is shown.
    fn save_ui_state(&self) {
        let _ = ui_state_service::save(
            &self.ui_state_path,
            &UiState {
                git: self.tab_view_of(TabKind::Git.index()),
                files: self.tab_view_of(TabKind::Files.index()),
                tab: self.tab,
                show_slugs: self.show_slugs,
                preview: self.preview.as_key().to_string(),
                preview_width_pct: self.preview.width_pct,
                preview_height_rows: self.preview.height_rows,
                hints_visible: shortcut_hints::visible(),
            },
        );
    }

    /// Moves the cursor cyclically within the current view; a plain move drops
    /// the range anchor so the next `Shift`-move re-anchors at the cursor.
    fn move_cursor(&mut self, delta: isize) {
        let len = self.ordered_view().len();
        self.cursor = cycle(self.cursor, len, delta);
        self.anchor = None;
    }

    /// Moves the cursor by `delta` without wrapping, clamped into the view.
    fn move_clamped(&mut self, delta: isize) {
        let len = self.ordered_view().len();
        if len == 0 {
            return;
        }
        let last = len as isize - 1;
        self.cursor = (self.cursor as isize + delta).clamp(0, last) as usize;
        self.anchor = None;
    }

    /// Jumps the cursor to the first (`g`) or last (`G`) entry.
    fn cursor_to_edge(&mut self, to_end: bool) {
        let len = self.ordered_view().len();
        self.cursor = if to_end { len.saturating_sub(1) } else { 0 };
        self.anchor = None;
    }

    /// Moves the cursor by whole (`pages` != 0) or half pages, using the last
    /// rendered list height.
    fn page(&mut self, pages: isize, half: bool) {
        let height = self.list_height.get().max(1) as isize;
        let step = if half { (height / 2).max(1) } else { height };
        self.move_clamped(pages.signum() * step);
    }

    /// Reverts the last config mutation, keeping the cursor in range.
    fn undo(&mut self) {
        match self.service.undo() {
            Ok(Some(label)) => {
                self.clear_selection();
                let len = self.ordered_view().len();
                self.clamp_cursor(len);
                self.set_status(format!("undid: {label}"));
            }
            Ok(None) => self.set_status("nothing to undo"),
            Err(error) => self.set_status(format!("undo failed: {error}")),
        }
    }

    /// Records the open, writes the handoff path and returns the outcome for
    /// the selected entry. `launch_tool` distinguishes Enter from the `o` jump.
    fn open_selected(&mut self, launch_tool: bool) -> Option<RunOutcome> {
        let index = self.selected_index()?;
        let repo = self.service.get(index)?.clone();
        if let Err(error) = self.service.mark_used(index) {
            self.set_status(format!("could not record usage: {error}"));
        }
        match repo.kind {
            RepoKind::Git if launch_tool => {
                self.write_selected(&repo.path);
                Some(RunOutcome::LaunchGitTool(repo.path))
            }
            RepoKind::Git => {
                self.write_selected(&repo.path);
                Some(RunOutcome::Jumped)
            }
            RepoKind::Path => self.open_path_entry(repo, launch_tool),
        }
    }

    /// Opens the selected Git entry's tool as an overlay: the run loop suspends
    /// the terminal, runs the tool to completion, then returns to the list and
    /// refreshes that entry. Non-Git entries are ignored.
    fn open_git_inline(&mut self) -> Option<RunOutcome> {
        let index = self.selected_index()?;
        let repo = self.service.get(index)?.clone();
        if repo.kind != RepoKind::Git {
            self.set_status("not a git repo");
            return None;
        }
        if let Err(error) = self.service.mark_used(index) {
            self.set_status(format!("could not record usage: {error}"));
        }
        Some(RunOutcome::LaunchGitToolInline(repo.path))
    }

    /// Runs the git tool for `dir` with the terminal suspended, then refreshes
    /// only that entry's status in the background (no fetch, no progress bar).
    fn run_git_inline(&mut self, tui: &mut Tui, dir: &Path) -> io::Result<()> {
        let Some(program) = self.config.git_program.clone() else {
            self.set_status("no git_program configured");
            return Ok(());
        };
        tui.suspend(|| {
            if let Err(error) = launch_git_tool(&program, dir) {
                log::error!("could not launch {program}: {error}");
            }
        })?;
        if !self.config.example_mode {
            self.refresh_paths(vec![dir.to_path_buf()], false, false);
        }
        Ok(())
    }

    /// Opens a file/folder entry: a folder `cd`s; on `o` (no launch) a file
    /// `cd`s to its parent; on Enter a text file opens in the editor and any
    /// other file in the default application.
    fn open_path_entry(
        &mut self,
        repo: Repo,
        launch_tool: bool,
    ) -> Option<RunOutcome> {
        let class =
            repo::classify_path(&repo.path, &self.config.editor_extensions);
        if class == repo::PathClass::Folder {
            self.write_selected(&repo.path);
            return Some(RunOutcome::Jumped);
        }
        if !launch_tool {
            // Jump-only on a file lands the shell in its parent directory.
            let dir = repo
                .path
                .parent()
                .map_or_else(|| repo.path.clone(), Path::to_path_buf);
            self.write_selected(&dir);
            return Some(RunOutcome::Jumped);
        }
        match class {
            repo::PathClass::TextFile => Some(RunOutcome::OpenFile(repo.path)),
            _ => Some(RunOutcome::OpenWith(repo.path)),
        }
    }

    /// Opens the selected entry with the platform's default application,
    /// regardless of its kind (forces a text file into its GUI app, or reveals
    /// a folder in the file manager). Does not `cd`.
    fn force_open_with(&mut self) -> Option<RunOutcome> {
        let index = self.selected_index()?;
        let repo = self.service.get(index)?.clone();
        if let Err(error) = self.service.mark_used(index) {
            self.set_status(format!("could not record usage: {error}"));
        }
        Some(RunOutcome::OpenWith(repo.path))
    }

    /// Writes the selected-repo handoff file, surfacing any error.
    fn write_selected(&mut self, path: &std::path::Path) {
        if let Err(error) = self.service.write_selected(path) {
            self.set_status(format!("could not write selected path: {error}"));
        }
    }

    /// Starts adding an entry: the form opens directly with a kind guessed from
    /// the active tab. The path is a plain text field; `^O` opens the picker.
    fn open_add(&mut self) {
        let form = RepoForm::for_add("", self.tab.repo_kind());
        self.overlay = Overlay::Form(Box::new(form), EditTarget::Add);
    }

    /// Opens the path picker to fill the path field of `form`, seeded near the
    /// path typed so far.
    fn open_form_path_picker(
        &mut self,
        form: Box<RepoForm>,
        target: EditTarget,
    ) {
        let typed = form.path_value();
        let start = if typed.trim().is_empty() {
            crate::util::paths::home_dir().unwrap_or_else(|| PathBuf::from("/"))
        } else {
            crate::util::paths::expand_tilde(&typed)
        };
        self.overlay = Overlay::Picker(
            PathPicker::new(&start, true),
            PickerIntent::FormPath(form, target),
        );
    }

    /// Opens the fuzzy section picker over a form in progress, seeded with the
    /// form's kind's section list and its current section.
    fn open_section_picker(&mut self, form: Box<RepoForm>, target: EditTarget) {
        let sections = self.service.sections(form.kind()).to_vec();
        let picker = SectionPicker::new(&sections, form.section().as_deref());
        self.overlay = Overlay::SectionPicker(Box::new(picker), form, target);
    }

    /// Re-opens the form after the section picker, applying the chosen section.
    fn resume_form_with_section(
        &mut self,
        mut form: Box<RepoForm>,
        target: EditTarget,
        section: Option<String>,
    ) {
        form.set_section(section);
        self.overlay = Overlay::Form(form, target);
    }

    /// Opens the edit form: a bulk form when several entries are targeted, else
    /// the single-entry form for the cursor/selection.
    fn open_edit_form(&mut self) {
        let targets = self.targets();
        match targets.len() {
            0 => {}
            1 => self.edit_form_for(targets[0]),
            _ => self.open_bulk_form(targets),
        }
    }

    /// Opens the edit form for the entry at `index`.
    fn edit_form_for(&mut self, index: usize) {
        let Some(repo) = self.service.get(index) else {
            return;
        };
        let form = RepoForm::for_edit(repo);
        self.overlay = Overlay::Form(Box::new(form), EditTarget::One(index));
    }

    /// Opens a bulk-edit form over `indices` (all the same kind, since selection
    /// is per-tab): the shared value of each field, or *mixed* when they differ.
    fn open_bulk_form(&mut self, indices: Vec<usize>) {
        let repos: Vec<&Repo> = indices
            .iter()
            .filter_map(|&index| self.service.get(index))
            .collect();
        if repos.is_empty() {
            return;
        }
        let kind = repos[0].kind;
        let section = shared(&repos, |repo| repo.section.clone());
        let fav = shared(&repos, |repo| repo.fav);
        let backup = shared(&repos, |repo| repo.include_in_backup);
        let form = RepoForm::for_bulk(repos.len(), kind, section, fav, backup);
        self.overlay = Overlay::Form(Box::new(form), EditTarget::Bulk(indices));
    }

    /// Opens the delete confirmation for the target entries (selection/cursor).
    fn open_delete_confirm(&mut self) {
        let targets = self.targets();
        if !targets.is_empty() {
            self.confirm_delete(targets);
        }
    }

    /// Opens the delete confirmation for a single entry at `index`.
    fn delete_confirm_for(&mut self, index: usize) {
        self.confirm_delete(vec![index]);
    }

    /// Opens a delete confirmation whose message names the count of `targets`.
    fn confirm_delete(&mut self, targets: Vec<usize>) {
        let message = if targets.len() == 1 {
            let name = self
                .service
                .get(targets[0])
                .map_or_else(String::new, Repo::display_name);
            format!("Delete \"{name}\" from the list?")
        } else {
            format!("Delete {} entries from the list?", targets.len())
        };
        self.overlay = Overlay::Confirm(
            ConfirmModal::new("Delete entries", message),
            targets,
        );
    }

    /// Opens the slug prompt for the selected entry.
    fn open_slug_prompt(&mut self) {
        let Some(index) = self.selected_index() else {
            return;
        };
        let current = self
            .service
            .get(index)
            .and_then(|r| r.slug.clone())
            .unwrap_or_default();
        self.overlay = Overlay::Prompt(
            TextPrompt::new("Set slug", "slug", &current),
            index,
        );
    }

    /// Opens the path picker to repair the selected entry's missing path.
    fn open_repair_picker(&mut self) {
        if let Some(index) = self.selected_index() {
            self.repair_picker_for(index);
        }
    }

    /// Opens the repair picker for the entry at `index`, starting at the nearest
    /// existing ancestor of its (missing) path.
    fn repair_picker_for(&mut self, index: usize) {
        let Some(repo) = self.service.get(index) else {
            return;
        };
        let start = nearest_existing_on_disk(&repo.path)
            .unwrap_or_else(|| PathBuf::from("/"));
        self.overlay = Overlay::Picker(
            PathPicker::new(&start, false),
            PickerIntent::Repair(index),
        );
    }

    /// Opens the popup listing all entries with a missing or invalid path.
    fn open_error_list(&mut self) {
        let repos = self.service.repos();
        let mut indices = Vec::new();
        let mut labels = Vec::new();
        for (index, repo) in repos.iter().enumerate() {
            if let Some(error) = self.path_error(repo) {
                labels.push(format!("{} - {error}", repo.display_name()));
                indices.push(index);
            }
        }
        if indices.is_empty() {
            self.set_status("no errors");
            return;
        }
        self.overlay =
            Overlay::Errors(SelectModal::new("Errors", labels, 0), indices);
    }

    /// Opens the action menu for an errored entry at `index`.
    fn open_error_action(&mut self, index: usize) {
        let name = self
            .service
            .get(index)
            .map_or_else(String::new, Repo::display_name);
        let actions = vec![
            "Repair path".to_string(),
            "Edit".to_string(),
            "Delete".to_string(),
        ];
        self.overlay = Overlay::ErrorAction(
            SelectModal::new(format!("Fix \"{name}\""), actions, 0),
            index,
        );
    }

    /// Runs the chosen action menu entry for the errored entry at `index`.
    fn run_error_action(&mut self, index: usize, action: usize) {
        match action {
            0 => self.repair_picker_for(index),
            1 => self.edit_form_for(index),
            _ => self.delete_confirm_for(index),
        }
    }

    /// Copies the selected entry's path to the system clipboard.
    fn copy_path(&mut self) {
        let paths = self.target_paths();
        if paths.is_empty() {
            return;
        }
        let count = paths.len();
        let text = paths.join("\n");
        match crate::util::clipboard::copy(&text) {
            Ok(()) => self.set_status(if count == 1 {
                "copied path to clipboard".to_string()
            } else {
                format!("copied {count} paths to clipboard")
            }),
            Err(error) => self.set_status(format!("copy failed: {error}")),
        }
    }

    /// The paths of the target entries (the selection, or the cursor entry when
    /// nothing is selected), in list order.
    fn target_paths(&self) -> Vec<String> {
        self.targets()
            .into_iter()
            .filter_map(|index| self.service.get(index))
            .map(|repo| repo.path.to_string_lossy().into_owned())
            .collect()
    }

    /// Opens the selected git entry's GitHub page in the browser (a non-blocking
    /// GUI handoff, so the TUI stays up).
    fn open_on_github(&mut self) {
        let targets = self.targets();
        let urls: Vec<String> = targets
            .iter()
            .filter_map(|&index| self.github_url_for(index))
            .collect();
        if urls.is_empty() {
            self.set_status("no GitHub remote");
            return;
        }
        let mut opened = 0;
        for url in &urls {
            match crate::util::opener::open_url(url) {
                Ok(_) => opened += 1,
                Err(error) => {
                    self.set_status(format!("could not open browser: {error}"));
                }
            }
        }
        if opened == 0 {
            return;
        }
        let skipped = targets.len() - urls.len();
        if opened == 1 && skipped == 0 {
            self.set_status(format!("opening {}", urls[0]));
        } else if skipped == 0 {
            self.set_status(format!("opening {opened} GitHub pages"));
        } else {
            self.set_status(format!(
                "opening {opened} GitHub pages ({skipped} skipped)"
            ));
        }
    }

    /// The GitHub URL for the entry at `index`, if it is a git repo with a
    /// resolvable remote (non-git entries and repos without a remote yield
    /// `None`).
    fn github_url_for(&self, index: usize) -> Option<String> {
        let repo = self.service.get(index)?;
        let info = if self.config.example_mode {
            repo.example_git_info.as_ref()
        } else {
            repo.git_info.as_ref()
        };
        let name = info.and_then(|info| info.github_repo_name.clone())?;
        github_url(&name, self.config.github_username.as_deref())
    }

    /// The entries an action applies to: the multi-selection, or the cursor
    /// entry when nothing is selected. Sorted ascending.
    fn targets(&self) -> Vec<usize> {
        if self.selected.is_empty() {
            return self.selected_index().into_iter().collect();
        }
        let mut indices: Vec<usize> = self.selected.iter().copied().collect();
        indices.sort_unstable();
        indices
    }

    /// Toggles the favourite flag of the target entries (all on, else all off),
    /// keeping the cursor on the same entry even as favourites re-sort.
    fn toggle_fav(&mut self) {
        let targets = self.targets();
        if targets.is_empty() {
            return;
        }
        let focus = self.cursor_path();
        let all_fav = targets
            .iter()
            .all(|&i| self.service.get(i).is_some_and(|r| r.fav));
        if let Err(error) = self.service.set_fav_many(&targets, !all_fav) {
            self.set_status(format!("could not change favourite: {error}"));
        }
        self.clear_selection();
        self.refocus(focus);
    }

    /// Zips the target git entries (selection or cursor) into the backup folder.
    /// Non-git entries are ignored; a lone non-git cursor reports a hint.
    fn zip_targets(&mut self) {
        // An explicit single/selection backup ignores the include flag: the
        // user is targeting these entries on purpose. Git repos and folders
        // both qualify; missing/non-folder paths are dropped in `start_zip`.
        let targets = self.targets();
        if targets.is_empty() {
            self.set_status("nothing to zip");
            return;
        }
        self.start_zip(&targets);
        self.clear_selection();
    }

    /// Zips every entry (across all tabs) that opts into the "backup all" run
    /// into the backup folder: all git repos plus the file/folder entries whose
    /// backup toggle is on.
    fn zip_all(&mut self) {
        let indices: Vec<usize> = self
            .service
            .repos()
            .iter()
            .enumerate()
            .filter(|(_, repo)| repo.include_in_backup)
            .map(|(index, _)| index)
            .collect();
        if indices.is_empty() {
            self.set_status("nothing to zip");
            return;
        }
        self.start_zip(&indices);
    }

    /// Starts a background ZIP backup of the repos at `indices`, showing the
    /// progress bar. Refuses to start while another refresh or backup runs.
    fn start_zip(&mut self, indices: &[usize]) {
        if self.loading.is_some() {
            self.set_status("busy: a refresh or backup is running");
            return;
        }
        let Some(folder) = self.config.zip_backup_folder.as_deref() else {
            self.set_status("no zip_backup_folder configured");
            return;
        };
        let folder = expand_tilde(folder);
        if let Err(error) = std::fs::create_dir_all(&folder) {
            self.set_status(format!("could not create backup folder: {error}"));
            return;
        }
        let repos = self.service.repos();
        let jobs: Vec<ZipJob> = indices
            .iter()
            .filter_map(|&i| repos.get(i))
            // Skip entries whose directory is gone (broken or offline drives),
            // so no empty archive is written for them.
            .filter(|repo| repo.path.is_dir())
            .map(|repo| ZipJob {
                src: repo.path.clone(),
                dest: backup_dest(&folder, repo, repos),
                name: repo.display_name(),
            })
            .collect();
        if jobs.is_empty() {
            self.set_status("nothing to zip (paths missing?)");
            return;
        }
        let count = jobs.len();
        self.set_status(if count == 1 {
            "creating backup…".to_string()
        } else {
            format!("creating {count} backups…")
        });
        self.loading_name_width = jobs
            .iter()
            .map(|job| UnicodeWidthStr::width(job.name.as_str()))
            .max()
            .unwrap_or(0);
        self.loading = Some((0, 0));
        self.loading_label = ZIP_LABEL;
        self.loading_detail = None;
        self.zip_rx = Some(spawn_zip(
            jobs,
            self.config.zip_exclude_dirs.clone(),
            self.zip_cache_path.clone(),
        ));
    }

    /// Applies any pending background ZIP-backup progress without blocking.
    /// Starts the worker the active column set needs, over the paths currently
    /// shown. `Standard` starts nothing at all, so a user who never opens the
    /// statistics never pays for a source walk.
    ///
    /// In example mode no worker ever runs; the cells fall back to a dash
    /// rather than spinning forever.
    fn start_stats(&mut self) {
        self.code_rx = None;
        self.git_stats_rx = None;
        self.computing.clear();
        if !self.columns().is_statistics() || self.config.example_mode {
            return;
        }
        let paths: Vec<PathBuf> = self
            .ordered_view()
            .iter()
            .filter_map(|&i| self.service.get(i))
            .map(|repo| repo.path.clone())
            .collect();
        if paths.is_empty() {
            return;
        }
        self.computing = paths.iter().cloned().collect();
        if self.columns().needs_code_stats() {
            self.code_rx = Some(spawn_code_stats(
                paths,
                self.config.zip_exclude_dirs.clone(),
            ));
        } else if self.columns().needs_git_stats() {
            self.git_stats_rx =
                Some(spawn_git_stats(Arc::clone(&self.git_client), paths));
        }
    }

    /// Drains the background code statistics into the cache.
    fn drain_code_stats(&mut self) {
        let Some(rx) = self.code_rx.take() else {
            return;
        };
        loop {
            match rx.try_recv() {
                Ok(CodeUpdate::Started { .. }) => {}
                Ok(CodeUpdate::Done { path, stats }) => {
                    self.computing.remove(&path);
                    self.stats.code.insert(path, *stats);
                }
                Err(mpsc::TryRecvError::Empty) => {
                    self.code_rx = Some(rx);
                    return;
                }
                Err(mpsc::TryRecvError::Disconnected) => {
                    self.finish_stats();
                    return;
                }
            }
        }
    }

    /// Drains the background history statistics into the cache.
    fn drain_git_stats(&mut self) {
        let Some(rx) = self.git_stats_rx.take() else {
            return;
        };
        loop {
            match rx.try_recv() {
                Ok(GitStatsUpdate::Started { .. }) => {}
                Ok(GitStatsUpdate::Done { path, stats }) => {
                    self.computing.remove(&path);
                    self.stats.git.insert(path, stats);
                }
                Err(mpsc::TryRecvError::Empty) => {
                    self.git_stats_rx = Some(rx);
                    return;
                }
                Err(mpsc::TryRecvError::Disconnected) => {
                    self.finish_stats();
                    return;
                }
            }
        }
    }

    /// Persists the statistics cache once a worker has finished.
    fn finish_stats(&mut self) {
        self.computing.clear();
        if let Err(error) =
            stats_service::save_cache(&self.stats_path, &self.stats)
        {
            log::warn!("could not write the stats cache: {error}");
        }
    }

    /// Whether a statistics worker is still running.
    fn is_computing(&self) -> bool {
        self.code_rx.is_some() || self.git_stats_rx.is_some()
    }

    fn drain_zip(&mut self) {
        let Some(rx) = self.zip_rx.take() else {
            return;
        };
        let mut summary = None;
        let mut disconnected = false;
        loop {
            match rx.try_recv() {
                Ok(update) => {
                    self.loading = Some((update.done, update.total));
                    if update.label.is_some() {
                        self.loading_detail = update.label;
                    }
                    if update.finished {
                        summary = Some((
                            update.archives,
                            update.unchanged,
                            update.errors,
                        ));
                    }
                }
                Err(TryRecvError::Empty) => break,
                Err(TryRecvError::Disconnected) => {
                    disconnected = true;
                    break;
                }
            }
        }
        if disconnected || summary.is_some() {
            self.loading = None;
            self.loading_label = REFRESH_LABEL;
            self.loading_detail = None;
            self.reload_zip_backups();
            if let Some((archives, unchanged, errors)) = summary {
                self.report_zip_done(archives, unchanged, errors);
            }
        } else {
            self.zip_rx = Some(rx);
        }
    }

    /// Reports the outcome of a finished ZIP-backup run.
    fn report_zip_done(
        &mut self,
        archives: usize,
        unchanged: usize,
        errors: usize,
    ) {
        // Nothing written and nothing failed: every target was already current.
        if archives == 0 && errors == 0 && unchanged > 0 {
            self.set_status("backup up to date (no changes)");
            return;
        }
        let folder =
            self.config.zip_backup_folder.as_deref().unwrap_or_default();
        let mut message = if archives == 1 {
            format!("backed up 1 archive to {folder}")
        } else {
            format!("backed up {archives} archives to {folder}")
        };
        if unchanged > 0 {
            message.push_str(&format!(" ({unchanged} unchanged)"));
        }
        if errors > 0 {
            message.push_str(&format!(" ({errors} failed)"));
        }
        self.set_status(message);
    }

    /// Whether a background ZIP backup is currently running.
    fn is_zipping(&self) -> bool {
        self.zip_rx.is_some()
    }

    /// Rebuilds the per-repo last-backup times from the backup folder (once at
    /// start and after each backup; never per frame).
    fn reload_zip_backups(&mut self) {
        self.zip_backups.clear();
        let Some(folder) = self.config.zip_backup_folder.as_deref() else {
            return;
        };
        let folder = expand_tilde(folder);
        let repos = self.service.repos();
        // Both git repos and file/folder entries can have a backup archive.
        for repo in repos.iter() {
            let dest = backup_dest(&folder, repo, repos);
            if let Ok(meta) = std::fs::metadata(&dest)
                && let Ok(modified) = meta.modified()
            {
                self.zip_backups.insert(
                    repo.path.clone(),
                    DateTime::<Local>::from(modified),
                );
            }
        }
    }

    /// The path of the entry under the cursor, if any.
    fn cursor_path(&self) -> Option<PathBuf> {
        self.selected_index()
            .and_then(|index| self.service.get(index))
            .map(|repo| repo.path.clone())
    }

    /// Moves the cursor onto the entry with `path`, if it is still visible.
    fn refocus(&mut self, path: Option<PathBuf>) {
        let Some(path) = path else {
            return;
        };
        let view = self.ordered_view();
        let repos = self.service.repos();
        if let Some(pos) = view.iter().position(|&i| repos[i].path == path) {
            self.cursor = pos;
        }
    }

    /// Archives or restores the target entries (all archived, else all on) and
    /// keeps the cursor in range.
    fn toggle_archive(&mut self) {
        let targets = self.targets();
        if targets.is_empty() {
            return;
        }
        let all_archived = targets
            .iter()
            .all(|&i| self.service.get(i).is_some_and(|r| r.archived));
        if let Err(error) =
            self.service.set_archived_many(&targets, !all_archived)
        {
            self.set_status(format!("could not change archive: {error}"));
        }
        self.clear_selection();
        let len = self.ordered_view().len();
        self.clamp_cursor(len);
    }

    /// Restarts the full background refresh, optionally fetching first. When the
    /// preview is visible, the current tab's git logs are reloaded too.
    fn reload_status(&mut self, fetch: bool) {
        if self.config.example_mode {
            self.set_status("example mode: live status is off");
            return;
        }
        self.set_status(if fetch {
            "fetching and reloading status…"
        } else {
            "reloading status…"
        });
        self.start_refresh(fetch);
        if self.preview.visible {
            let paths = self.tab_git_paths();
            self.invalidate_logs(&paths);
            self.fetch_logs(paths);
        }
    }

    /// The current tab's git entry paths (for reloading preview logs).
    fn tab_git_paths(&self) -> Vec<PathBuf> {
        self.tab_indices()
            .iter()
            .filter_map(|&i| self.service.get(i))
            .filter(|repo| repo.kind == RepoKind::Git)
            .map(|repo| repo.path.clone())
            .collect()
    }

    /// Refreshes the target entries in the background, optionally fetching
    /// first. The global "remote: fetched …" line is left untouched.
    fn refresh_targets(&mut self, fetch: bool) {
        if self.config.example_mode {
            self.set_status("example mode: live status is off");
            return;
        }
        let targets = self.targets();
        let paths: Vec<PathBuf> = targets
            .iter()
            .filter_map(|&i| self.service.get(i).map(|r| r.path.clone()))
            .collect();
        if paths.is_empty() {
            return;
        }
        let message = if targets.len() == 1 {
            let name = self
                .service
                .get(targets[0])
                .map_or_else(String::new, Repo::display_name);
            format!("refreshing {name}…")
        } else {
            format!("refreshing {} entries…", targets.len())
        };
        self.set_status(message);
        self.refresh_paths(paths, fetch, false);
        if self.preview.visible {
            let git_paths: Vec<PathBuf> = targets
                .iter()
                .filter_map(|&i| self.service.get(i))
                .filter(|repo| repo.kind == RepoKind::Git)
                .map(|repo| repo.path.clone())
                .collect();
            self.invalidate_logs(&git_paths);
            self.fetch_logs(git_paths);
        }
        self.clear_selection();
    }

    /// Toggles the selection of the cursor entry and re-anchors the range.
    fn toggle_select(&mut self) {
        if let Some(index) = self.selected_index() {
            if !self.selected.remove(&index) {
                self.selected.insert(index);
            }
            self.anchor = Some(self.cursor);
        }
    }

    /// Clears the multi-selection.
    fn clear_selection(&mut self) {
        self.selected.clear();
        self.anchor = None;
    }

    /// Extends the range selection by moving the cursor (clamped, not cyclic)
    /// and selecting every row between the anchor and the cursor.
    fn extend_selection(&mut self, delta: isize) {
        let view = self.ordered_view();
        if view.is_empty() {
            return;
        }
        let anchor = *self.anchor.get_or_insert(self.cursor);
        let last = view.len() - 1;
        let new =
            (self.cursor as isize + delta).clamp(0, last as isize) as usize;
        self.cursor = new;
        let (lo, hi) = (anchor.min(new).min(last), anchor.max(new).min(last));
        self.selected = view[lo..=hi].iter().copied().collect();
    }

    /// Moves the cursor entry within the custom order (only in custom sort).
    fn move_entry(&mut self, delta: isize) {
        // Manual reorder only makes sense in custom sort; every other mode
        // orders automatically.
        if self.sort() != SortMode::Custom {
            self.set_status("switch to custom sort (t) to reorder");
            return;
        }
        let view = self.ordered_view();
        if view.is_empty() {
            return;
        }
        let cur = self.cursor.min(view.len() - 1);
        let neighbor = cur as isize + delta;
        if neighbor < 0 || neighbor as usize >= view.len() {
            return;
        }
        let (a, b) = (view[cur], view[neighbor as usize]);
        let repos = self.service.repos();
        // While favourites float, stay within the fav / non-fav segment.
        if self.fav_float() && repos[a].fav != repos[b].fav {
            return;
        }
        // In the grouped view, only reorder within the same section.
        if self.is_sectioned() && repos[a].section != repos[b].section {
            return;
        }
        let moved = repos[a].path.clone();
        if self.service.swap_entries(a, b).is_ok()
            && let Some(pos) = self
                .ordered_view()
                .iter()
                .position(|&i| self.service.repos()[i].path == moved)
        {
            self.cursor = pos;
        }
    }

    /// Deletes the confirmed target entries.
    fn do_delete(&mut self, targets: Vec<usize>) {
        match self.service.delete_many(&targets) {
            Ok(()) => {
                self.clear_selection();
                let len = self.ordered_view().len();
                self.clamp_cursor(len);
                let count = targets.len();
                self.set_status(if count == 1 {
                    "deleted entry".to_string()
                } else {
                    format!("deleted {count} entries")
                });
            }
            Err(error) => self.set_status(format!("delete failed: {error}")),
        }
    }

    /// Sets or clears the slug of the entry at `index`.
    fn do_set_slug(&mut self, index: usize, value: String) {
        let slug = if value.trim().is_empty() {
            None
        } else {
            Some(value)
        };
        match self.service.set_slug(index, slug) {
            Ok(()) => self.set_status("slug updated"),
            Err(error) => self.set_status(format!("{error}")),
        }
    }

    /// Saves the add or edit form into a new or existing entry, registering a
    /// newly typed section name.
    fn do_save_form(&mut self, index: Option<usize>, draft: RepoDraft) {
        let path = crate::util::paths::expand_tilde(draft.path.trim());
        if draft.path.trim().is_empty() {
            self.set_status("path must not be empty");
            return;
        }
        let section = draft.section.clone();
        let kind = draft.kind;
        // A folder needs a trailing slash to be recognised before it exists.
        let assumed_file = kind == RepoKind::Path
            && !draft.path.trim().ends_with('/')
            && !path.exists();
        // A git entry refreshes its own status only when its path changed (or
        // when it is newly added); other edits never touch git.
        let path_changed = match index {
            Some(index) => {
                self.service.get(index).map(|r| &r.path) != Some(&path)
            }
            None => true,
        };
        let new_path = path.clone();
        let (result, ok_message) = match index {
            Some(index) => {
                let Some(mut repo) = self.service.get(index).cloned() else {
                    return;
                };
                apply_draft(&mut repo, draft, path);
                (self.service.update(index, repo), "entry updated")
            }
            None => {
                let mut repo = Repo::new(path.clone());
                apply_draft(&mut repo, draft, path);
                (self.service.add(repo), "entry added")
            }
        };
        let saved = result.is_ok();
        if saved && let Some(name) = section {
            let _ = self.service.ensure_section(kind, &name);
        }
        self.report(result, ok_message);
        if saved && assumed_file {
            self.set_status(
                "no trailing / - treated as a file (end with / for a folder)",
            );
        }
        if saved
            && kind == RepoKind::Git
            && path_changed
            && !self.config.example_mode
        {
            self.refresh_paths(vec![new_path], false, false);
        }
    }

    /// Applies a bulk edit: writes each touched field onto every target entry
    /// (one undo frame), registering a newly typed section and refocusing.
    fn do_save_bulk(&mut self, target: EditTarget, draft: BulkDraft) {
        let EditTarget::Bulk(indices) = target else {
            return;
        };
        // The kind after the edit decides which namespace a new section joins.
        let kind_after = draft.kind.unwrap_or_else(|| self.tab.repo_kind());
        let result = self.service.update_many(&indices, |repo| {
            if let Some(section) = &draft.section {
                repo.section = section.clone();
            }
            if let Some(fav) = draft.fav {
                repo.fav = fav;
            }
            if let Some(backup) = draft.include_in_backup {
                repo.include_in_backup = backup;
            }
            if let Some(kind) = draft.kind {
                repo.kind = kind;
            }
        });
        if result.is_ok()
            && let Some(Some(name)) = &draft.section
        {
            let _ = self.service.ensure_section(kind_after, name);
        }
        let count = indices.len();
        self.report(result, &format!("updated {count} entries"));
        self.clear_selection();
        let len = self.ordered_view().len();
        self.clamp_cursor(len);
        self.start_stats();
    }

    /// Applies a picked path to its intent (repair an entry, or fill a form).
    fn do_picked(&mut self, intent: PickerIntent, path: PathBuf) {
        match intent {
            PickerIntent::Repair(index) => {
                let repaired = path.clone();
                match self.service.set_path(index, path) {
                    Ok(()) => {
                        self.set_status("path repaired");
                        if !self.config.example_mode {
                            self.clear_repaired_error(repaired);
                        }
                    }
                    Err(error) => {
                        self.set_status(format!("repair failed: {error}"))
                    }
                }
            }
            PickerIntent::FormPath(mut form, target) => {
                form.set_path(&path.to_string_lossy());
                self.overlay = Overlay::Form(form, target);
            }
        }
    }

    /// Reports a service result as a transient status message.
    fn report(
        &mut self,
        result: crate::domain::error::Result<()>,
        ok_message: &str,
    ) {
        match result {
            Ok(()) => self.set_status(ok_message),
            Err(error) => self.set_status(format!("{error}")),
        }
    }
}

/// The single index a non-bulk `Save` applies to (`One` -> `Some`, else `None`).
fn save_index(target: &EditTarget) -> Option<usize> {
    match target {
        EditTarget::One(index) => Some(*index),
        _ => None,
    }
}

/// The shared value of a field over `repos`: `Some(value)` when all agree, or
/// `None` when they differ (a *mixed* field).
fn shared<T: PartialEq>(
    repos: &[&Repo],
    get: impl Fn(&Repo) -> T,
) -> Option<T> {
    let mut values = repos.iter().map(|repo| get(repo));
    let first = values.next()?;
    values.all(|value| value == first).then_some(first)
}

/// Copies the draft's fields onto `repo`, keeping its runtime/example fields.
fn apply_draft(repo: &mut Repo, draft: RepoDraft, path: PathBuf) {
    repo.name = draft.name;
    repo.path = path;
    repo.slug = draft.slug;
    repo.section = draft.section;
    repo.kind = draft.kind;
    repo.fav = draft.fav;
    repo.include_in_backup = draft.include_in_backup;
}

impl App {
    /// Renders the whole screen: the panel app-frame (tinted header/content/
    /// status bands plus backgroundless hints), the entry list (and preview) in
    /// the content surface, and any overlay on top.
    fn render(&self, frame: &mut Frame) {
        let area = frame.area();
        let areas = appframe::render_frame(
            frame,
            &self.skin,
            appframe::TabBar {
                active: self.tab.kind_index(),
                archived: self.tab.is_archived(),
            },
            self.status_lines(area.width),
            &self.hint_groups(),
            self.loading.is_some(),
        );
        let (body, footer) = self.split_columns_footer(areas.content);
        let (list_area, preview_area) = self.split_preview(body);
        self.render_body(frame, list_area);
        if let Some(footer) = footer {
            self::columns::render_footer(
                frame,
                footer,
                (self.columns(), self.tab),
                (self.visible_totals(), &self.colors),
            );
        }
        if let Some(preview_area) = preview_area {
            self.render_preview(frame, preview_area);
        }
        if let Some(progress_area) = areas.progress {
            self.render_progress_bar(frame, progress_area);
        }
        // Snapshot the finished view so an overlay can dim it as its backdrop.
        appframe::snapshot_frame(frame);
        self.render_overlay(frame, area);
    }

    /// Paints the refresh/backup progress bar (pre-migration style) into the
    /// panel reserved above the status band, when a run is in flight.
    fn render_progress_bar(&self, frame: &mut Frame, area: Rect) {
        let Some((done, total)) = self.loading else {
            return;
        };
        let ratio = progress_ratio(done, total);
        let prefix = self.progress_prefix(ratio, done, total);
        render_progress(
            frame,
            area,
            &self.skin,
            ProgressText {
                prefix: &prefix,
                name: self.loading_detail.as_deref().unwrap_or(""),
                ratio,
                name_width: self.loading_name_width,
            },
        );
    }

    /// The status-band lines: the info line (or the progress line while a
    /// refresh/backup runs), plus the live-filter input or a transient status
    /// message when either is active. `width` is the terminal width, from which
    /// the columns left for the filter's value are measured.
    fn status_lines(&self, width: u16) -> Vec<Line<'_>> {
        let mut lines = vec![self.info_line()];
        if self.filtering {
            let mut spans = vec![Span::styled(
                FILTER_LABEL,
                Style::default().fg(self.colors.accent),
            )];
            spans.extend(field_spans(FieldView {
                field: &self.filter,
                palette: &self.skin.palette,
                width: filter_value_width(width),
                focused: true,
            }));
            spans.push(Span::styled(
                FILTER_HINT,
                Style::default().fg(self.colors.dim),
            ));
            lines.push(Line::from(spans));
        } else if let Some((message, _)) = &self.status_msg {
            lines.push(Line::from(Span::styled(
                format!(" {message}"),
                Style::default().fg(self.colors.accent),
            )));
        }
        lines
    }

    /// The per-tab footer hints as labelled groups (clibase-style). A compact
    /// Navigation group leads, then each `bindings` group is turned into
    /// `(key, description)` pairs via the keymap, so the shown keys reflect any
    /// `[keys]` overrides. Empty groups (no bound key) are dropped.
    fn hint_groups(&self) -> Vec<(String, Vec<(String, String)>)> {
        let keymap = &self.keymap;
        let navigation = (
            "Navigation".to_string(),
            [
                ("\u{2191}\u{2193}", "move"),
                ("g/G", "top/bottom"),
                ("PgUp/PgDn", "page"),
                ("Ctrl+u/d", "half"),
            ]
            .into_iter()
            .map(|(key, desc)| (key.to_string(), desc.to_string()))
            .collect(),
        );
        let mut groups = vec![navigation];
        for (label, actions) in bindings::hint_groups(self.tab) {
            let hints = keymap.hints(actions);
            if !hints.is_empty() {
                groups.push(((*label).to_string(), hints));
            }
        }
        groups.push(global_group(keymap));
        groups
    }

    /// The app-wide chords, shared by the footer and the help overlay.
    fn global_hints(&self) -> (String, Vec<(String, String)>) {
        global_group(&self.keymap)
    }

    /// Splits the content band into the body and, outside the standard column
    /// set, the totals-and-bar footer below it. A short terminal keeps every
    /// row for the list and gets no footer.
    fn split_columns_footer(&self, content: Rect) -> (Rect, Option<Rect>) {
        let rows = self::columns::footer_rows(self.columns(), content.height);
        if rows == 0 {
            return (content, None);
        }
        let parts = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Min(1), Constraint::Length(rows)])
            .split(content);
        (parts[0], Some(parts[1]))
    }

    /// The summed statistics of the entries currently shown, so the totals row
    /// follows the filter.
    fn visible_totals(&self) -> crate::domain::stats::Totals {
        let entries = self
            .ordered_view()
            .into_iter()
            .filter_map(|i| self.service.get(i))
            .filter_map(|repo| self.stats.code.get(&repo.path));
        crate::domain::stats::totals(entries)
    }

    /// Splits `body` into the list area and an optional panel area, per the
    /// active [`PreviewLayout`]. A one-cell gutter separates the two, so the
    /// panel's border never touches the list.
    fn split_preview(&self, body: Rect) -> (Rect, Option<Rect>) {
        if !self.preview.visible {
            return (body, None);
        }
        let (direction, minimum, panel) = match self.preview.position {
            preview::PreviewPosition::Right => (
                Direction::Horizontal,
                MIN_LIST_COLS,
                Constraint::Percentage(self.preview.width_pct),
            ),
            preview::PreviewPosition::Bottom => (
                Direction::Vertical,
                MIN_LIST_ROWS,
                Constraint::Length(self.preview.height_rows),
            ),
        };
        let parts = Layout::default()
            .direction(direction)
            .constraints([
                Constraint::Min(minimum),
                Constraint::Length(PANEL_GUTTER),
                panel,
            ])
            .split(body);
        (parts[0], Some(parts[2]))
    }

    /// The cursor entry's path when it is a git repo whose log the preview
    /// would show (preview visible, not example mode); otherwise `None`.
    fn preview_log_path(&self) -> Option<PathBuf> {
        if !self.preview.visible || self.config.example_mode {
            return None;
        }
        let repo = self.selected_index().and_then(|i| self.service.get(i))?;
        if repo.kind != RepoKind::Git {
            return None;
        }
        Some(repo.path.clone())
    }

    /// Requests the cursor entry's preview `git log` once the cursor has rested
    /// on it for [`PREVIEW_DEBOUNCE`], so quick scrolling never blocks. The
    /// fetch itself runs on a background worker (see [`fetch_logs`]).
    fn request_preview_log(&mut self) {
        let Some(path) = self.preview_log_path() else {
            self.preview_target = None;
            return;
        };
        if self.preview_log.contains_key(&path)
            || self.preview_pending.contains(&path)
        {
            return;
        }
        if self.preview_target.as_deref() != Some(&path) {
            self.preview_target = Some(path);
            self.preview_target_at = Instant::now();
            return;
        }
        if self.preview_target_at.elapsed() < PREVIEW_DEBOUNCE {
            return;
        }
        self.fetch_logs(vec![path]);
    }

    /// Spawns a background worker to fetch the preview logs for `paths`,
    /// skipping any already cached and marking the rest as pending.
    fn fetch_logs(&mut self, paths: Vec<PathBuf>) {
        let wanted: Vec<PathBuf> = paths
            .into_iter()
            .filter(|path| !self.preview_log.contains_key(path))
            .collect();
        if wanted.is_empty() {
            return;
        }
        for path in &wanted {
            self.preview_pending.insert(path.clone());
        }
        preview_service::spawn_logs(
            Arc::clone(&self.git_client),
            wanted,
            PREVIEW_LOG_LINES,
            self.preview_tx.clone(),
        );
    }

    /// Applies any background preview-log results without blocking.
    fn drain_preview(&mut self) {
        while let Ok(log) = self.preview_rx.try_recv() {
            self.preview_pending.remove(&log.path);
            self.preview_log.insert(log.path, log.lines);
        }
    }

    /// Whether the preview is waiting on a log (debouncing or fetching), so the
    /// loop should poll faster to pick the result up promptly.
    fn preview_busy(&self) -> bool {
        if !self.preview_pending.is_empty() {
            return true;
        }
        self.preview_log_path()
            .is_some_and(|path| !self.preview_log.contains_key(&path))
    }

    /// Drops the cached and pending preview logs for `paths`, so they are
    /// re-fetched on demand. Does nothing for paths not in the cache.
    fn invalidate_logs(&mut self, paths: &[PathBuf]) {
        for path in paths {
            self.preview_log.remove(path);
            self.preview_pending.remove(path);
        }
    }

    /// Renders the detail/preview panel for the cursor entry.
    fn render_preview(&self, frame: &mut Frame, area: Rect) {
        let repo = self.selected_index().and_then(|i| self.service.get(i));
        let log = repo
            .map(|r| self.preview_log.get(&r.path).map(Vec::as_slice))
            .unwrap_or(None);
        let log_loading = self
            .preview_log_path()
            .is_some_and(|path| !self.preview_log.contains_key(&path));
        preview::render(
            frame,
            area,
            &self.skin,
            preview::PreviewContext {
                repo,
                icons: &self.icons,
                colors: &self.colors,
                example_mode: self.config.example_mode,
                log: log.unwrap_or(&[]),
                log_loading,
                code: repo.and_then(|r| self.stats.code.get(&r.path)),
                git: repo.and_then(|r| self.stats.git.get(&r.path)),
                now: Local::now().timestamp(),
                scroll: &self.preview_scroll,
            },
        );
    }

    /// The fixed-width leading part of the progress text: the percentage, plus
    /// the file counts while zipping. Widths are padded so the part keeps a
    /// constant width, pinning the `XX %` column for the whole run.
    fn progress_prefix(&self, ratio: f64, done: usize, total: usize) -> String {
        let pct = (ratio * 100.0).round() as u16;
        let pw = PERCENT_WIDTH;
        if self.loading_label == ZIP_LABEL {
            let cw = digit_count(total);
            format!("{pct:>pw$} % ({done:>cw$}/{total})")
        } else {
            format!("{pct:>pw$} %")
        }
    }

    /// The info line for the status band - error count, entry count, sort, the
    /// active lenses, local status and remote fetch time, each behind its icon.
    /// The refresh/backup progress is shown by the bar above the status band
    /// (see [`App::render_progress_bar`]), so this stays the normal info line.
    fn info_line(&self) -> Line<'_> {
        let icons = self.icons;
        let muted = Style::default().fg(self.colors.muted);
        let sep = || Span::styled("   ", Style::default().fg(self.colors.dim));
        let mut spans = vec![Span::raw(" ")];

        let errors = self.error_count();
        if errors > 0 {
            spans.push(Span::styled(
                format!("{}{errors}", icons.missing),
                Style::default()
                    .fg(self.colors.danger)
                    .add_modifier(Modifier::BOLD),
            ));
            spans.push(sep());
        }
        // Entry count, as shown/total when a filter narrows the list.
        let shown = self.ordered_view().len();
        let total = self.tab_indices().len();
        let count = if shown == total {
            format!("{} {shown}", icons.count)
        } else {
            format!("{} {shown}/{total}", icons.count)
        };
        spans.push(Span::styled(count, muted));
        spans.push(sep());
        spans.push(Span::styled(
            format!("{} {}", icons.sort, self.sort().label()),
            muted,
        ));
        // Active view lenses (filter / changes-only / slugs) in the accent.
        let mut lenses: Vec<&str> = Vec::new();
        if self.filtering_active() {
            lenses.push("filter");
        }
        if self.changes_only {
            lenses.push("changes");
        }
        if self.show_slugs {
            lenses.push("slugs");
        }
        if !lenses.is_empty() {
            spans.push(sep());
            spans.push(Span::styled(
                lenses.join(" · "),
                Style::default().fg(self.colors.accent),
            ));
        }

        // The status/remote times are git-specific, so skip them on the files
        // tabs.
        if self.config.example_mode {
            spans.push(sep());
            spans.push(Span::styled("example mode", muted));
        } else if self.tab.kind() == TabKind::Git {
            if let Some(at) = self.cache_generated_at {
                let age = Local::now().signed_duration_since(at);
                spans.push(sep());
                spans.push(Span::styled(
                    format!(
                        "{} {} ({} ago)",
                        icons.clock,
                        at.format("%Y-%m-%d %H:%M"),
                        relative_age(age),
                    ),
                    muted,
                ));
            }
            spans.push(sep());
            spans.push(self.remote_span(icons.remote, muted));
        }
        Line::from(spans)
    }

    /// The remote-fetch segment of the info line: amber when over a day old or
    /// never fetched, muted otherwise.
    fn remote_span(&self, icon: &str, muted: Style) -> Span<'static> {
        match self.last_fetched {
            None => Span::styled(
                format!("{icon} never fetched"),
                Style::default().fg(self.colors.changes),
            ),
            Some(at) => {
                let age = Local::now().signed_duration_since(at);
                let stale = age.num_hours() >= 24;
                let suffix = if stale { "  (stale)" } else { "" };
                let text = format!(
                    "{icon} {} ({} ago){suffix}",
                    at.format("%Y-%m-%d %H:%M"),
                    relative_age(age),
                );
                let style = if stale {
                    Style::default().fg(self.colors.changes)
                } else {
                    muted
                };
                Span::styled(text, style)
            }
        }
    }

    /// The number of current-tab entries flagged with a path error.
    fn error_count(&self) -> usize {
        let repos = self.service.repos();
        self.tab_indices()
            .iter()
            .filter(|&&i| self.path_error(&repos[i]).is_some())
            .count()
    }

    /// The path error for `repo`, if any. A git entry reports a missing or
    /// invalid repository from its gathered git info (set by the background
    /// refresh, so no filesystem stat happens here); a file/folder entry only
    /// reports a missing path once the on-demand existence check (`r` on the
    /// Files tab) has flagged it.
    fn path_error(&self, repo: &Repo) -> Option<String> {
        if self.config.example_mode {
            // Example mode shows curated demo data, so a git entry's error comes
            // from its example info; path entries are never checked on disk.
            return match repo.kind {
                RepoKind::Git => repo.example_error(),
                RepoKind::Path => None,
            };
        }
        match repo.kind {
            RepoKind::Git => repo.entry_error(),
            RepoKind::Path => self
                .files_missing
                .contains(&repo.path)
                .then(|| repo::PATH_NOT_FOUND.to_string()),
        }
    }

    /// Clears the error state of a just-repaired entry, whichever tab it lives
    /// on. The error list spans every tab, so a tab-wide refresh would miss an
    /// entry repaired from another tab: re-stat the file/folder entries (clears
    /// the missing marker) and refresh just the repaired path's git status.
    fn clear_repaired_error(&mut self, path: PathBuf) {
        self.recheck_files();
        self.refresh_paths(vec![path], false, false);
    }

    /// Re-stats every file/folder entry, recording the ones whose path is
    /// missing so the marker and error count reflect the current filesystem.
    fn recheck_files(&mut self) {
        self.files_missing = self
            .service
            .repos()
            .iter()
            .filter(|repo| repo.kind == RepoKind::Path && !repo.path.exists())
            .map(|repo| repo.path.clone())
            .collect();
    }

    /// Checks on disk which file/folder entries are missing, recording them so
    /// the marker and the error count reflect the result. Triggered by `r` on
    /// the Files tab; never on start. Reports a transient summary.
    fn check_files_existence(&mut self) {
        self.recheck_files();
        let missing = self.files_missing.len();
        self.set_status(if missing == 0 {
            "checked paths: all exist".to_string()
        } else if missing == 1 {
            "checked paths: 1 missing".to_string()
        } else {
            format!("checked paths: {missing} missing")
        });
    }

    /// Renders the entry table, or an empty hint.
    fn render_body(&self, frame: &mut Frame, area: Rect) {
        // Remember the page size for page-wise navigation.
        self.list_height
            .set(area.height.saturating_sub(1).max(1) as usize);
        let view = self.ordered_view();
        if view.is_empty() {
            render_empty_hint(frame, area, empty_hint(self.tab), &self.colors);
            return;
        }
        if self.is_sectioned() {
            self.render_sections(frame, area, view.len());
            return;
        }
        let repos = self.service.repos();
        let visible: Vec<&Repo> = view.iter().map(|&i| &repos[i]).collect();
        let cursor = self.cursor.min(visible.len() - 1);
        // Rows still in flight show an animated spinner in the status column.
        let spinner =
            self.spinner_frame().map(|glyph| (&self.refreshing, glyph));
        // Which visible rows are part of the multi-selection.
        let selected: Vec<bool> =
            view.iter().map(|i| self.selected.contains(i)).collect();
        let query = self.filter.value();
        let table_view = table::TableView {
            tab: self.tab,
            config: &self.config,
            skin: &self.skin,
            colors: &self.colors,
            columns: self.columns(),
            code: &self.stats.code,
            git: &self.stats.git,
            computing: &self.computing,
            now: Local::now().timestamp(),
            icons: &self.icons,
            example_mode: self.config.example_mode,
            spinner,
            selected: &selected,
            has_selection: !self.selected.is_empty(),
            missing: &self.files_missing,
            show_slugs: self.show_slugs,
            // The flat view labels each row with its section when grouping is
            // off, so the section is still visible without header bars.
            show_section: !self.grouped(),
            query: self.filtering_active().then_some(query),
            zip_backups: &self.zip_backups,
            offset: &self.table_offset,
        };
        table::render_table(frame, area, &visible, cursor, &table_view);
    }

    /// Renders the current tab as a sectioned list (`view_len` entries total).
    fn render_sections(&self, frame: &mut Frame, area: Rect, view_len: usize) {
        let groups = self.section_groups();
        let cursor = self.cursor.min(view_len.saturating_sub(1));
        let spinner =
            self.spinner_frame().map(|glyph| (&self.refreshing, glyph));
        let view = sections_view::SectionedView {
            tab: self.tab,
            groups: &groups,
            repos: self.service.repos(),
            config: &self.config,
            icons: &self.icons,
            skin: &self.skin,
            colors: &self.colors,
            columns: self.columns(),
            code: &self.stats.code,
            git: &self.stats.git,
            computing: &self.computing,
            example_mode: self.config.example_mode,
            spinner,
            now: Local::now().timestamp(),
            selected: &self.selected,
            has_selection: !self.selected.is_empty(),
            missing: &self.files_missing,
            show_slugs: self.show_slugs,
            zip_backups: &self.zip_backups,
            offset: &self.list_offset,
        };
        sections_view::render(frame, area, cursor, &view);
    }

    /// Renders the active overlay, if any, over the dimmed live view (the
    /// snapshot taken at the end of [`App::render`]), clibase-style.
    fn render_overlay(&self, frame: &mut Frame, area: Rect) {
        if matches!(self.overlay, Overlay::None) {
            return;
        }
        appframe::dim_backdrop(frame);
        let skin = &self.skin;
        match &self.overlay {
            Overlay::None => {}
            Overlay::Help => help::render(
                frame,
                area,
                skin,
                &self.global_hints(),
                &self.help_scroll,
            ),
            Overlay::Confirm(modal, _) => modal.render(frame, area, skin),
            Overlay::Prompt(prompt, _) => prompt.render(frame, area, skin),
            Overlay::Form(form, _) => form.render(frame, area, skin),
            Overlay::SectionPicker(picker, _, _) => {
                picker.render(frame, area, skin)
            }
            Overlay::Picker(picker, _) => picker.render(frame, area, skin),
            Overlay::Errors(modal, _) => modal.render(frame, area, skin),
            Overlay::ErrorAction(modal, _) => modal.render(frame, area, skin),
            Overlay::SectionJump(modal, _) => modal.render(frame, area, skin),
            Overlay::Sort(modal, _) => modal.render(frame, area, skin),
            Overlay::Sections(modal) => modal.render(frame, area, skin),
            Overlay::SectionPrompt(prompt, _) => {
                prompt.render(frame, area, skin)
            }
            Overlay::SectionDelete(confirm, _) => {
                confirm.render(frame, area, skin)
            }
        }
    }
}

/// The placeholder text for an empty tab.
fn empty_hint(tab: Tab) -> &'static str {
    match tab {
        Tab::GitActive => "No git repos. Press n to add one.",
        Tab::GitArchive => "No archived git repos.",
        Tab::FilesActive => "No folders or files. Press n to add one.",
        Tab::FilesArchive => "No archived folders or files.",
    }
}

/// The destination archive path for `repo` in `folder`: a unique, slugified
/// file name (see [`crate::domain::backup::backup_filename`]).
fn backup_dest(folder: &Path, repo: &Repo, repos: &[Repo]) -> PathBuf {
    folder.join(backup::backup_filename(repo, repos))
}

/// The fill ratio for `done` of `total`, clamped to `0.0..=1.0` (0 when empty).
fn progress_ratio(done: usize, total: usize) -> f64 {
    if total == 0 {
        return 0.0;
    }
    (done as f64 / total as f64).clamp(0.0, 1.0)
}

/// The number of decimal digits in `n` (at least 1), for padding counts.
fn digit_count(n: usize) -> usize {
    n.to_string().len()
}

/// The composed text and fill ratio for one frame of the progress bar.
struct ProgressText<'a> {
    /// The fixed-width leading part (percentage, plus file counts when zipping).
    prefix: &'a str,
    /// The entry name shown after the prefix; empty when none is known yet.
    name: &'a str,
    /// Fill ratio in `0.0..=1.0`.
    ratio: f64,
    /// Display width reserved for the name, so the prefix column stays put as
    /// names of different lengths come and go.
    name_width: usize,
}

impl ProgressText<'_> {
    /// The bar's label, `prefix - name`, with the name padded to the widest name
    /// of the run. The gauge centres the label, so a constant label width pins
    /// the `XX %` column even as names of different lengths come and go. The
    /// name column is reserved before the first name arrives; the separator
    /// appears only once there is a name to separate.
    fn label(&self) -> String {
        let separator = if self.name.is_empty() {
            " ".repeat(PROGRESS_SEPARATOR.chars().count())
        } else {
            PROGRESS_SEPARATOR.to_string()
        };
        format!(
            "{}{separator}{:<width$}",
            self.prefix,
            self.name,
            width = self.name_width
        )
    }
}

/// Renders a solid progress bar for an in-flight operation (status refresh or
/// ZIP backup) across `area`, leaving one blank cell of padding on each side.
fn render_progress(
    frame: &mut Frame,
    area: Rect,
    skin: &Skin,
    text: ProgressText,
) {
    let area = Rect {
        x: area.x.saturating_add(1),
        width: area.width.saturating_sub(2),
        ..area
    };
    ratada::gauge::render(
        frame,
        area,
        &skin.palette,
        text.ratio,
        &text.label(),
    );
}

/// A short relative age like `2d`, `5h` or `3m` for the remote line.
fn relative_age(age: chrono::Duration) -> String {
    if age.num_days() >= 1 {
        return format!("{}d", age.num_days());
    }
    if age.num_hours() >= 1 {
        return format!("{}h", age.num_hours());
    }
    format!("{}m", age.num_minutes().max(0))
}

/// Whether `repo` passes the changes-only filter: non-git entries always pass;
/// a git entry passes only when its (live or example) status is not clean.
fn repo_has_change(repo: &Repo, example_mode: bool) -> bool {
    if repo.kind != RepoKind::Git {
        return true;
    }
    let info = if example_mode {
        repo.example_git_info.as_ref()
    } else {
        repo.git_info.as_ref()
    };
    info.is_some_and(|info| !info.is_clean())
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::path::Path;

    use crossterm::event::KeyModifiers;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    use super::*;
    use crate::config::{Appearance, Config};
    use crate::domain::repo::GitInfo;
    use crate::storage::in_memory_repository::InMemoryRepoRepository;
    use crate::theme::GlyphVariant;

    use crate::domain::stats::GitStats;

    /// A git client that does nothing (the smoke test runs in example mode).
    struct NoGit;

    impl GitClient for NoGit {
        fn collect(&self, _path: &Path) -> GitInfo {
            GitInfo::default()
        }
        fn fetch(&self, _path: &Path) {}
        fn log(&self, _path: &Path, _max: usize) -> Vec<String> {
            Vec::new()
        }
        fn stats(&self, _path: &Path) -> GitStats {
            GitStats::default()
        }
    }

    fn sample_app() -> App {
        app_with_keys(BTreeMap::new())
    }

    /// A sample app whose `[keys]` section holds `overrides`.
    fn app_with_keys(overrides: BTreeMap<String, Vec<String>>) -> App {
        let mut config = sample_config();
        config.keys = overrides;
        app_with(config)
    }

    /// The demo settings every sample app shares: example mode, ASCII glyphs.
    fn sample_config() -> Config {
        Config {
            example_mode: true,
            appearance: Appearance {
                glyphs: GlyphVariant::Ascii,
                ..Appearance::default()
            },
            ..Config::default()
        }
    }

    /// A sample app over four demo entries, using `config`.
    fn app_with(config: Config) -> App {
        let mut git = Repo::new(PathBuf::from("/code/hop"));
        git.name = Some("hop".to_string());
        git.fav = true;
        let mut missing = Repo::new(PathBuf::from("/code/gone"));
        missing.slug = Some("gone".to_string());
        let mut folder = Repo::new(PathBuf::from("/notes"));
        folder.kind = RepoKind::Path;
        let mut archived = Repo::new(PathBuf::from("/old"));
        archived.archived = true;
        // Each app needs its own state files: the tests run in parallel and
        // would otherwise read each other's persisted sort and column set.
        static NEXT: std::sync::atomic::AtomicUsize =
            std::sync::atomic::AtomicUsize::new(0);
        let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let dir = std::env::temp_dir()
            .join(format!("hop-tui-test-{}-{id}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let service = RepoService::new(
            Box::new(InMemoryRepoRepository::new(vec![
                git, missing, folder, archived,
            ])),
            dir.join("usage.toml"),
            dir.join("selected.txt"),
        )
        .unwrap();
        App::new(
            config,
            service,
            Arc::new(NoGit),
            dir.join("cache.toml"),
            dir.join("ui-state.toml"),
            StartupStatus::Refresh { fetch: false },
        )
    }

    #[test]
    fn the_active_theme_colours_the_content_cells() {
        // The whole point of dropping `tui::colors`: a re-theme must reach the
        // table cells, not just the frame and the modals.
        let rose = Colors::from_palette(&sample_config().palette());
        let mut config = sample_config();
        config.appearance.theme = "monochrome".to_string();
        let mono = Colors::from_palette(&config.palette());
        assert_ne!(rose.accent, mono.accent, "the themes must differ");

        let app = app_with(config);
        let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();
        terminal.draw(|frame| app.render(frame)).unwrap();
        let buffer = terminal.backend().buffer().clone();
        let foregrounds: Vec<_> =
            buffer.content().iter().map(|c| c.style().fg).collect();
        assert!(
            foregrounds.contains(&Some(mono.accent)),
            "the theme accent must appear in the rendered content"
        );
        assert!(
            !foregrounds.contains(&Some(rose.accent)),
            "no cell may keep the compiled-in rose accent"
        );
    }

    fn press(app: &mut App, code: KeyCode) {
        app.handle_key(KeyEvent::new(code, KeyModifiers::NONE));
    }

    #[test]
    fn renders_every_tab_without_panicking() {
        let mut app = sample_app();
        let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();
        for tab in ['1', '2', '3'] {
            press(&mut app, KeyCode::Char(tab));
            terminal.draw(|frame| app.render(frame)).unwrap();
        }
    }

    /// The whole rendered buffer as one string.
    fn screen(app: &App, width: u16, height: u16) -> String {
        let mut terminal =
            Terminal::new(TestBackend::new(width, height)).unwrap();
        terminal.draw(|frame| app.render(frame)).unwrap();
        terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(ratatui::buffer::Cell::symbol)
            .collect()
    }

    #[test]
    fn c_cycles_the_column_sets_and_only_they_show_the_bar() {
        let mut app = sample_app();
        // Flat view (grouping off) shows the classic table with column headers.
        press(&mut app, KeyCode::Char('.'));
        // Standard looks exactly as it always did: no bar, no totals row.
        let standard = screen(&app, 120, 30);
        assert!(standard.contains("Branch"));
        assert!(!standard.contains("Columns"), "no bar in the standard set");

        press(&mut app, KeyCode::Char('c'));
        let code = screen(&app, 120, 30);
        assert!(code.contains("LOC") && code.contains("Language"));
        assert!(
            !code.contains("Branch"),
            "the standard columns are replaced"
        );
        assert!(code.contains("Columns"), "the bar names the sets");
        assert!(code.contains("projects"), "the totals row is shown");

        press(&mut app, KeyCode::Char('c'));
        let activity = screen(&app, 120, 30);
        assert!(activity.contains("Commits") && activity.contains("Authors"));

        press(&mut app, KeyCode::Char('c'));
        assert!(screen(&app, 120, 30).contains("Branch"), "back to standard");
    }

    #[test]
    fn example_mode_shows_dashes_rather_than_spinning_forever() {
        // No worker ever runs in example mode, so a spinner would never stop.
        // Unicode glyphs, because the ASCII spinner uses `-` itself - which is
        // also the text for a value that will never arrive.
        let mut config = sample_config();
        config.appearance.glyphs = GlyphVariant::Unicode;
        let mut app = app_with(config);
        assert!(app.config.example_mode);
        press(&mut app, KeyCode::Char('c'));
        let code = screen(&app, 120, 30);
        assert!(code.contains('-'), "an uncomputable cell reads as a dash");
        for frame in spinner_frames(GlyphVariant::Unicode) {
            assert!(
                !code.contains(frame),
                "example mode must never spin: found {frame:?}"
            );
        }
    }

    /// Every distinct frame of the toolkit spinner, gathered by stepping it
    /// until it wraps back to where it started.
    fn spinner_frames(variant: GlyphVariant) -> Vec<&'static str> {
        let mut spinner = Spinner::new();
        let first = spinner.frame(variant);
        let mut frames = vec![first];
        loop {
            spinner.advance();
            let frame = spinner.frame(variant);
            if frame == first {
                return frames;
            }
            frames.push(frame);
        }
    }

    #[test]
    fn the_bar_and_totals_vanish_on_a_short_terminal() {
        let mut app = sample_app();
        press(&mut app, KeyCode::Char('c'));
        assert!(screen(&app, 120, 30).contains("Columns"));
        // Too short to spare five rows: the list keeps them.
        assert!(!screen(&app, 120, 14).contains("Columns"));
    }

    #[test]
    fn v_toggles_the_panel_and_capital_v_moves_it() {
        let mut app = sample_app();
        assert!(!screen(&app, 120, 30).contains("Details"));
        press(&mut app, KeyCode::Char('v'));
        // The border title names the cursor entry.
        assert!(screen(&app, 120, 30).contains("Details - hop"));
        assert_eq!(app.preview.position, preview::PreviewPosition::Right);
        press(&mut app, KeyCode::Char('V'));
        assert_eq!(app.preview.position, preview::PreviewPosition::Bottom);
        assert!(screen(&app, 120, 30).contains("Details - hop"));
        press(&mut app, KeyCode::Char('v'));
        assert!(!screen(&app, 120, 30).contains("Details"));
    }

    #[test]
    fn ctrl_arrows_resize_the_panel_only_while_it_is_open() {
        let mut app = sample_app();
        let before = app.preview.width_pct;
        // Closed: the chord does nothing.
        app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::CONTROL));
        assert_eq!(app.preview.width_pct, before);

        press(&mut app, KeyCode::Char('v'));
        app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::CONTROL));
        assert!(app.preview.width_pct > before, "ctrl+right widens it");
        app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::CONTROL));
        assert_eq!(app.preview.width_pct, before, "ctrl+left narrows it back");
    }

    #[test]
    fn t_opens_the_sort_picker_and_re_picking_flips_the_direction() {
        let mut app = sample_app();
        press(&mut app, KeyCode::Char('t'));
        assert!(matches!(app.overlay, Overlay::Sort(_, _)));
        let listed = screen(&app, 120, 30);
        assert!(listed.contains("Sort by") && listed.contains("Frecency"));
        // Standard offers no column modes.
        assert!(!listed.contains("Lines of code"));

        // Name is active and first; Enter re-picks it and flips the direction.
        assert_eq!(
            (app.sort(), app.sort_dir()),
            (SortMode::Name, SortDir::Asc)
        );
        press(&mut app, KeyCode::Enter);
        assert_eq!(
            (app.sort(), app.sort_dir()),
            (SortMode::Name, SortDir::Desc)
        );
    }

    #[test]
    fn the_sort_picker_offers_the_active_column_sets_modes() {
        let mut app = sample_app();
        press(&mut app, KeyCode::Char('c'));
        press(&mut app, KeyCode::Char('t'));
        let listed = screen(&app, 120, 30);
        assert!(listed.contains("Lines of code") && listed.contains("Size"));
        assert!(!listed.contains("Commits"), "those belong to Activity");
    }

    #[test]
    fn the_grouped_view_shows_the_column_header() {
        let mut app = sample_app();
        // Default git tab, grouping on: the column header sits above the list.
        let git = screen(&app, 120, 30);
        assert!(git.contains("Branch"), "git header shows Branch");
        assert!(git.contains("Status") && git.contains("GitHub"));
        assert!(git.contains("ZIP Backup"));

        // The files tab (grouped) shows its own header.
        press(&mut app, KeyCode::Char('2'));
        let files = screen(&app, 120, 30);
        assert!(files.contains("Type") && files.contains("Path"));
    }

    #[test]
    fn i_shows_the_slug_in_its_own_column() {
        let mut app = sample_app();
        // Flat view (grouping off) so the table draws its column headers.
        press(&mut app, KeyCode::Char('.'));
        let before = screen(&app, 120, 30);
        assert!(!before.contains("Slug"), "no Slug header until toggled");

        press(&mut app, KeyCode::Char('i'));
        let after = screen(&app, 120, 30);
        assert!(after.contains("Slug"), "the Slug column has a header");
        // The demo git entry's slug is shown (it lives in its own column).
        assert!(after.contains("gone"), "the slug value is rendered");
    }

    #[test]
    fn the_files_tab_never_offers_the_activity_columns() {
        let mut app = sample_app();
        press(&mut app, KeyCode::Char('2'));
        press(&mut app, KeyCode::Char('c'));
        assert_eq!(app.columns(), ColumnSet::Code);
        press(&mut app, KeyCode::Char('c'));
        assert_eq!(app.columns(), ColumnSet::Standard, "Activity is skipped");
    }

    #[test]
    fn a_column_set_the_tab_lacks_falls_back_when_switching_to_it() {
        let mut app = sample_app();
        press(&mut app, KeyCode::Char('c'));
        press(&mut app, KeyCode::Char('c'));
        assert_eq!(app.columns(), ColumnSet::Activity);
        press(&mut app, KeyCode::Char('2'));
        // Switching to files keeps the files tab's own column set (Standard).
        assert_eq!(app.columns(), ColumnSet::Standard);
    }

    #[test]
    fn every_overlay_renders_at_a_normal_and_a_cramped_size() {
        // The form, the slug prompt and the path picker size their fields from
        // the box's inner width; on a terminal too small to hold the box that
        // width goes to zero, which must clamp rather than underflow.
        // Each case is the keys that open the overlay; `M` is Files-tab only.
        // The error list is left out: it needs a failing entry, and it is the
        // same `SelectModal` the sort picker already covers.
        let openers = [
            ("n", "add form"),
            ("e", "edit form"),
            ("d", "delete confirm"),
            ("S", "slug prompt"),
            ("p", "path picker"),
            ("2M", "manage sections"),
            ("t", "sort picker"),
            ("?", "help"),
        ];
        for (keys, what) in openers {
            let mut app = sample_app();
            for key in keys.chars() {
                press(&mut app, KeyCode::Char(key));
            }
            assert!(
                !matches!(app.overlay, Overlay::None),
                "{what} did not open on {keys:?}"
            );
            for (width, height) in [(100, 30), (20, 6)] {
                let _ = screen(&app, width, height);
            }
        }
    }

    #[test]
    fn a_long_filter_query_scrolls_inside_the_status_band() {
        // The status band is one row wide; the toolkit's field scrolls the query
        // under the caret and marks the hidden head, rather than overrunning the
        // trailing hint. A hand-drawn caret used to just overflow.
        let mut app = sample_app();
        press(&mut app, KeyCode::Char('f'));
        for ch in "abcdefghijklmnopqrstuvwxyz0123456789".chars() {
            press(&mut app, KeyCode::Char(ch));
        }
        let narrow = screen(&app, 60, 20);
        assert!(narrow.contains('\u{2026}'), "the clipped head is marked");
        assert!(narrow.contains("Esc clear"), "the trailing hint survives");
        assert!(narrow.contains('9'), "the caret's end stays visible");
        // Given room, the whole query fits and nothing is marked as clipped.
        let wide = screen(&app, 120, 20);
        assert!(wide.contains("abcdefghijklmnopqrstuvwxyz0123456789"));
    }

    #[test]
    fn the_progress_label_keeps_its_width_as_the_name_changes() {
        // The gauge centres the label, so a constant label width is what pins
        // the `XX %` column while entry names of different lengths come and go.
        let label_for = |name: &str| {
            ProgressText {
                prefix: " 50 %",
                name,
                ratio: 0.5,
                name_width: 6,
            }
            .label()
        };
        let widths: Vec<usize> = ["", "hop", "mdtask"]
            .iter()
            .map(|n| label_for(n).len())
            .collect();
        assert_eq!(widths, vec![widths[0]; 3]);
        assert!(label_for("hop").starts_with(" 50 % - hop"));
        // Without a name the separator is blanked out rather than dangling.
        assert!(!label_for("").contains('-'));
    }

    #[test]
    fn progress_bar_paints_accent_fill_and_label() {
        // A half-filled bar: the left cells carry the accent background and the
        // centred percentage label is present.
        let config = Config::default();
        let colors = Colors::from_palette(&config.palette());
        let skin = config.skin();
        let mut terminal = Terminal::new(TestBackend::new(40, 2)).unwrap();
        terminal
            .draw(|frame| {
                render_progress(
                    frame,
                    frame.area(),
                    &skin,
                    ProgressText {
                        prefix: " 50 %",
                        name: "repo",
                        ratio: 0.5,
                        name_width: 4,
                    },
                );
            })
            .unwrap();
        let buf = terminal.backend().buffer().clone();
        // A cell early in the bar (inside the padded, filled region) is accent.
        assert_eq!(buf.cell((2, 0)).unwrap().style().bg, Some(colors.accent));
        // A cell near the right end (past the half fill) is the track colour.
        assert_eq!(
            buf.cell((38, 0)).unwrap().style().bg,
            Some(colors.selection_bg)
        );
        let text: String = buf
            .content()
            .iter()
            .map(ratatui::buffer::Cell::symbol)
            .collect();
        assert!(text.contains('%') && text.contains("repo"));
    }

    #[test]
    fn copy_targets_collects_selected_paths() {
        let mut app = sample_app();
        // No selection: just the cursor entry (the first git repo).
        assert_eq!(app.target_paths(), vec!["/code/hop".to_string()]);
        // Selecting two entries copies both paths, in index order.
        app.selected.insert(0);
        app.selected.insert(2);
        assert_eq!(
            app.target_paths(),
            vec!["/code/hop".to_string(), "/notes".to_string()],
        );
    }

    #[test]
    fn hint_groups_are_labelled_and_tab_specific() {
        let labels = |app: &App| {
            app.hint_groups()
                .into_iter()
                .map(|(label, _)| label)
                .collect::<Vec<_>>()
        };
        let mut app = sample_app();
        app.tab = Tab::GitActive;
        let git = labels(&app);
        assert_eq!(git.first().map(String::as_str), Some("Navigation"));
        assert!(git.contains(&"Git".to_string()));
        // Sections now work on the git tabs too.
        assert!(git.contains(&"Sections".to_string()));

        app.tab = Tab::FilesActive;
        let files = labels(&app);
        assert!(files.contains(&"Sections".to_string()));
        assert!(files.contains(&"Paths".to_string()));
        assert!(!files.contains(&"Git".to_string()));

        // Keys come from the keymap (per-action), e.g. add -> "n".
        let add = app
            .hint_groups()
            .into_iter()
            .flat_map(|(_, pairs)| pairs)
            .find(|(_, desc)| desc == "add");
        assert_eq!(add, Some(("n".to_string(), "add".to_string())));
    }

    #[test]
    fn hint_band_grows_to_fit_all_hints() {
        // At a narrow width the hints wrap past two rows; the panel's hint band
        // must size to hold them all rather than clipping at a fixed height.
        let app = sample_app();
        let width = 60;
        let mut terminal = Terminal::new(TestBackend::new(width, 40)).unwrap();
        terminal.draw(|frame| app.render(frame)).unwrap();
        let rendered = terminal.backend().buffer().clone();
        let text: String = rendered
            .content()
            .iter()
            .map(ratatui::buffer::Cell::symbol)
            .collect();
        // The last hint must be present, i.e. nothing was clipped away.
        assert!(text.contains("quit"), "last footer hint was clipped");
    }

    #[test]
    fn filter_and_help_overlay_render() {
        let mut app = sample_app();
        let mut terminal = Terminal::new(TestBackend::new(100, 30)).unwrap();
        press(&mut app, KeyCode::Char('F'));
        press(&mut app, KeyCode::Char('h'));
        terminal.draw(|frame| app.render(frame)).unwrap();
        press(&mut app, KeyCode::Esc);
        press(&mut app, KeyCode::Char('?'));
        terminal.draw(|frame| app.render(frame)).unwrap();
    }

    #[test]
    fn pressing_shift_l_on_a_git_repo_returns_launch_outcome() {
        let mut app = sample_app();
        // The first git-tab entry is the git repo "hop".
        let outcome = app
            .handle_key(KeyEvent::new(KeyCode::Char('L'), KeyModifiers::NONE));
        assert!(matches!(outcome, Some(RunOutcome::LaunchGitTool(_))));
    }

    #[test]
    fn pressing_enter_on_a_git_repo_only_jumps() {
        let mut app = sample_app();
        // The first git-tab entry is the git repo "hop".
        let outcome =
            app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        assert!(matches!(outcome, Some(RunOutcome::Jumped)));
    }

    #[test]
    fn pressing_l_on_a_git_repo_opens_the_tool_inline() {
        let mut app = sample_app();
        // The first git-tab entry is the git repo "hop".
        let outcome = app
            .handle_key(KeyEvent::new(KeyCode::Char('l'), KeyModifiers::NONE));
        assert!(matches!(outcome, Some(RunOutcome::LaunchGitToolInline(_))));
    }

    #[test]
    fn q_quits() {
        let mut app = sample_app();
        let outcome = app
            .handle_key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE));
        assert!(matches!(outcome, Some(RunOutcome::Quit)));
    }

    #[test]
    fn ctrl_q_is_left_to_the_terminal_guard() {
        // The `Tui` turns `Ctrl+Q` into `TuiEvent::Quit` before dispatch ever
        // sees it, so no list binding may claim the chord. Dispatch used to
        // quit on it only because it matched on `KeyCode` and ignored the
        // modifier.
        let mut app = sample_app();
        let outcome = app.handle_key(KeyEvent::new(
            KeyCode::Char('q'),
            KeyModifiers::CONTROL,
        ));
        assert!(outcome.is_none());
    }

    #[test]
    fn a_keys_override_rebinds_the_action() {
        let overrides =
            BTreeMap::from([("quit".to_string(), vec!["w".to_string()])]);
        let mut app = app_with_keys(overrides);
        let rebound = app
            .handle_key(KeyEvent::new(KeyCode::Char('w'), KeyModifiers::NONE));
        assert!(matches!(rebound, Some(RunOutcome::Quit)));
        let default = app
            .handle_key(KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE));
        assert!(
            default.is_none(),
            "the replaced default must not still quit"
        );
    }

    #[test]
    fn relative_age_picks_the_largest_unit() {
        assert_eq!(relative_age(chrono::Duration::days(3)), "3d");
        assert_eq!(relative_age(chrono::Duration::hours(5)), "5h");
        assert_eq!(relative_age(chrono::Duration::minutes(12)), "12m");
        assert_eq!(relative_age(chrono::Duration::seconds(-30)), "0m");
    }

    #[test]
    fn changes_filter_keeps_non_git_and_dirty_git() {
        use crate::domain::repo::GitInfo;
        // A non-git entry always passes.
        let mut folder = Repo::new(PathBuf::from("/notes"));
        folder.kind = RepoKind::Path;
        assert!(repo_has_change(&folder, false));

        // A git entry with no info or a clean tree is filtered out.
        let mut clean = Repo::new(PathBuf::from("/clean"));
        assert!(!repo_has_change(&clean, false));
        clean.git_info = Some(GitInfo {
            valid: true,
            ..GitInfo::default()
        });
        assert!(!repo_has_change(&clean, false));

        // A git entry with changes passes.
        let mut dirty = Repo::new(PathBuf::from("/dirty"));
        dirty.git_info = Some(GitInfo {
            valid: true,
            changes: Some(2),
            ..GitInfo::default()
        });
        assert!(repo_has_change(&dirty, false));
    }
}