duodiff 0.6.0

A fast, cross-platform terminal user interface (TUI) directory comparison tool
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
use crate::app::{App, FlatRow, HelpTopic, PaletteMode, ViewMode};
use crate::diff::DiffState;
use crate::theme::Theme;
use ratatui::{prelude::*, widgets::*};
use std::time::SystemTime;
use unicode_width::UnicodeWidthChar;

/// Format a `SystemTime` as a UTC datetime string (`YYYY-MM-DD HH:MM:SS UTC`).
/// Uses UTC everywhere so we do not need platform-specific localtime (no `libc`).
fn format_system_time(t: &SystemTime) -> String {
    match t.duration_since(SystemTime::UNIX_EPOCH) {
        Ok(dur) => {
            let total_secs = dur.as_secs() as i64;
            let s = total_secs.rem_euclid(60);
            let m = (total_secs / 60).rem_euclid(60);
            let h = (total_secs / 3600).rem_euclid(24);
            let days = total_secs.div_euclid(86400);
            let (y, mo, d) = days_to_date(days);
            format!("{y:04}-{mo:02}-{d:02} {h:02}:{m:02}:{s:02} UTC")
        }
        Err(_) => "unknown".to_string(),
    }
}

/// Gregorian civil date for `days_since_epoch` days after 1970-01-01 (UTC).
fn days_to_date(days_since_epoch: i64) -> (i64, i64, i64) {
    let mut y = 1970;
    let mut remaining = days_since_epoch;
    loop {
        let days_in_year = if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) {
            366
        } else {
            365
        };
        if remaining < days_in_year {
            break;
        }
        remaining -= days_in_year;
        y += 1;
    }
    let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
    let month_days = [
        31,
        if leap { 29 } else { 28 },
        31,
        30,
        31,
        30,
        31,
        31,
        30,
        31,
        30,
        31,
    ];
    let mut mo = 0;
    for (i, &md) in month_days.iter().enumerate() {
        if remaining < md {
            mo = i as i64 + 1;
            break;
        }
        remaining -= md;
    }
    (y, mo, remaining + 1)
}

/// Build a detail info string for the selected row showing modification times
/// and sizes when both sides exist and differ.
///
/// `pub(crate)`: also called from [`App::tree_layout_inputs`] (has_detail), not just
/// [`draw_tree_footer`] — widened rather than re-deriving the same `DiffState` match twice.
pub(crate) fn selected_row_detail(row: Option<&FlatRow>) -> Option<(String, String)> {
    let row = row?;
    match row.state {
        DiffState::DifferentNewerLeft
        | DiffState::DifferentNewerRight
        | DiffState::DifferentSameTime => {}
        _ => return None,
    }
    let left = row.left.as_ref()?;
    let right = row.right.as_ref()?;

    let left_time = format_system_time(&left.modified);
    let right_time = format_system_time(&right.modified);

    let (left_tag, right_tag) = match row.state {
        DiffState::DifferentNewerLeft => (" (newer)", ""),
        DiffState::DifferentNewerRight => ("", " (newer)"),
        _ => ("", ""),
    };

    if left.is_dir {
        Some((
            format!("{}{}", left_time, left_tag),
            format!("{}{}", right_time, right_tag),
        ))
    } else {
        Some((
            format!("{} {}{}", format_size(left.size), left_time, left_tag),
            format!("{} {}{}", format_size(right.size), right_time, right_tag),
        ))
    }
}

/// Format byte size in a human-friendly form.
fn format_size(bytes: u64) -> String {
    if bytes < 1024 {
        format!("{} B", bytes)
    } else if bytes < 1024 * 1024 {
        format!("{:.1} KB", bytes as f64 / 1024.0)
    } else if bytes < 1024 * 1024 * 1024 {
        format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
    } else {
        format!("{:.1} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
    }
}

/// Render `input`'s text with a reverse-video block cursor at its real (char, not byte)
/// position, so multi-byte CJK text and mid-string editing show the cursor correctly.
/// `cursor_style` is the caller's accent colour; the cursor block always reverses video
/// regardless, so it stays visible over any text colour.
fn text_input_spans(
    input: &crate::text_input::TextInput,
    cursor_style: Style,
) -> Vec<Span<'static>> {
    let chars: Vec<char> = input.chars().collect();
    let cursor = input.cursor().min(chars.len());
    let rev = cursor_style.add_modifier(Modifier::REVERSED);
    let mut spans = Vec::new();
    let before: String = chars[..cursor].iter().collect();
    if !before.is_empty() {
        spans.push(Span::raw(before));
    }
    if cursor < chars.len() {
        spans.push(Span::styled(chars[cursor].to_string(), rev));
        let after: String = chars[cursor + 1..].iter().collect();
        if !after.is_empty() {
            spans.push(Span::raw(after));
        }
    } else {
        spans.push(Span::styled(" ".to_string(), rev));
    }
    spans
}

/// Pure title-bar state for the shared top chrome (Config / Help shortcuts).
#[derive(Clone, Copy, Debug)]
pub struct TopBarView {
    pub view_mode: ViewMode,
    pub precise_mode: bool,
    pub diff_show_full: bool,
    pub diff_wrap: bool,
    pub theme: Theme,
}

/// Render the shared top bar from an [`App`] (projects via [`App::top_bar_view`]).
pub fn draw_top_bar(f: &mut Frame, app: &App, area: Rect) {
    draw_top_bar_content(f, &app.top_bar_view(), area);
}

// Text spans `draw_top_bar_content`'s right-aligned column renders, named so the
// painter and `top_bar_links`'s hit-test geometry read from the same source and
// cannot drift apart.
const TOPBAR_LEAD: &str = " (";
const TOPBAR_CONFIG_KEY: &str = "C";
const TOPBAR_CONFIG_LABEL: &str = ")onfig";
const TOPBAR_GAP: &str = "  ";
const TOPBAR_HELP_LEAD: &str = "(";
const TOPBAR_HELP_KEY: &str = "?";
const TOPBAR_HELP_LABEL: &str = ")Help";
const TOPBAR_TRAIL: &str = " ";

/// The top bar's `[left title, right Config/Help column]` split. Shared by
/// `draw_top_bar_content` (render) and `top_bar_links` (hit-test) so the column
/// boundary itself — not just the text within it — cannot drift between them.
fn top_bar_columns(area: Rect) -> (Rect, Rect) {
    let layout = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Min(30), Constraint::Length(22)])
        .split(area);
    (layout[0], layout[1])
}

/// Paint the top bar from a hand-built [`TopBarView`] (no full `App`).
pub fn draw_top_bar_content(f: &mut Frame, view: &TopBarView, area: Rect) {
    let theme = view.theme;
    let (left_col, right_col) = top_bar_columns(area);

    let left_text = match view.view_mode {
        ViewMode::DirectoryTree => {
            if view.precise_mode {
                " duodiff - Directory Tree [Precise] ".to_string()
            } else {
                " duodiff - Directory Tree [Fast] ".to_string()
            }
        }
        ViewMode::FileDiff => {
            let context_label = if view.diff_show_full {
                "Full"
            } else {
                "Diff Only"
            };
            let wrap_label = if view.diff_wrap { "Wrap" } else { "No Wrap" };
            format!(" duodiff - File Diff [{}] [{}] ", context_label, wrap_label)
        }
        ViewMode::ConfigMenu => " duodiff - Configuration ".to_string(),
        ViewMode::Help => " duodiff - Help ".to_string(),
    };

    let left_p = Paragraph::new(Line::from(vec![Span::styled(
        left_text,
        Style::default().fg(theme.emphasis).bold(),
    )]));
    f.render_widget(left_p, left_col);

    let right_p = Paragraph::new(Line::from(vec![
        Span::styled(TOPBAR_LEAD, Style::default().fg(theme.muted)),
        Span::styled(TOPBAR_CONFIG_KEY, Style::default().fg(theme.accent).bold()),
        Span::styled(TOPBAR_CONFIG_LABEL, Style::default().fg(theme.muted)),
        Span::raw(TOPBAR_GAP),
        Span::styled(TOPBAR_HELP_LEAD, Style::default().fg(theme.muted)),
        Span::styled(TOPBAR_HELP_KEY, Style::default().fg(theme.accent).bold()),
        Span::styled(TOPBAR_HELP_LABEL, Style::default().fg(theme.muted)),
        Span::raw(TOPBAR_TRAIL),
    ]))
    .alignment(Alignment::Right);
    f.render_widget(right_p, right_col);
}

/// The clickable Rects for the top bar's "(C)onfig"/"(?)Help" links, derived from
/// the same span-width constants `draw_top_bar_content` renders from — so the two
/// cannot drift apart. `area` is the top-bar's Rect (row 0, full width) — same
/// `Constraint::Length(22)` right column `draw_top_bar_content` splits out. Each
/// link's Rect covers its key + label text (e.g. "(C)onfig"), not the surrounding
/// lead space / gap / trailing space.
pub struct TopBarLinks {
    pub config: Rect,
    pub help: Rect,
}

pub fn top_bar_links(area: Rect) -> TopBarLinks {
    let (_, col) = top_bar_columns(area);

    let total_width = (TOPBAR_LEAD.len()
        + TOPBAR_CONFIG_KEY.len()
        + TOPBAR_CONFIG_LABEL.len()
        + TOPBAR_GAP.len()
        + TOPBAR_HELP_LEAD.len()
        + TOPBAR_HELP_KEY.len()
        + TOPBAR_HELP_LABEL.len()
        + TOPBAR_TRAIL.len()) as u16;
    let text_start = col.x + col.width.saturating_sub(total_width);

    let config_x = text_start + TOPBAR_LEAD.len() as u16 - 1; // include TOPBAR_LEAD's '('
    let config_width = 1 + TOPBAR_CONFIG_KEY.len() as u16 + TOPBAR_CONFIG_LABEL.len() as u16;

    let help_x = config_x + config_width + TOPBAR_GAP.len() as u16;
    let help_width = TOPBAR_HELP_LEAD.len() as u16
        + TOPBAR_HELP_KEY.len() as u16
        + TOPBAR_HELP_LABEL.len() as u16;

    TopBarLinks {
        config: Rect {
            x: config_x,
            y: col.y,
            width: config_width,
            height: 1,
        },
        help: Rect {
            x: help_x,
            y: col.y,
            width: help_width,
            height: 1,
        },
    }
}

pub fn draw(f: &mut Frame, app: &mut App) {
    // Paint the full canvas so every unfilled cell uses the theme background (no-op for
    // dark theme where bg=Reset; effective for light theme which sets a white canvas).
    f.render_widget(Block::default().style(app.theme().base_style()), f.area());

    match app.view_mode() {
        ViewMode::DirectoryTree => {
            draw_tree(f, app);
            if app.confirm_modal().is_some() {
                draw_confirm_modal(f, app);
            }
        }
        ViewMode::FileDiff => {
            draw_diff(f, app);
            if app.confirm_modal().is_some() {
                draw_confirm_modal(f, app);
            }
        }
        ViewMode::ConfigMenu => draw_config(f, app),
        ViewMode::Help => draw_help(f, app),
    }

    if app.palette_visible() {
        draw_palette(f, app);
    }
}

fn get_display_path(path: &std::path::Path, max_len: usize) -> String {
    let path_str = path.to_string_lossy();
    if path_str.len() <= max_len {
        return path_str.into_owned();
    }

    let sep = std::path::MAIN_SEPARATOR.to_string();
    let components: Vec<_> = path
        .components()
        .map(|c| c.as_os_str().to_string_lossy().into_owned())
        .filter(|s| !s.is_empty() && s != &sep)
        .collect();

    if components.is_empty() {
        return path_str.into_owned();
    }

    let last = &components[components.len() - 1];
    let mut right_part = last.to_string();
    let mut idx = components.len().saturating_sub(2);
    while idx > 0 {
        let next_part = format!("{}{}{}", components[idx], sep, right_part);
        if next_part.len() + 4 <= max_len {
            right_part = next_part;
            idx -= 1;
        } else {
            break;
        }
    }

    format!("...{}{}", sep, right_part)
}

/// Borrowed render state for the directory-tree **content** region (dual panes + indicator).
///
/// Built by [`App::tree_view`] in production, or hand-assembled in ui tests without
/// a full [`App`]. Top bar and footer stay on the [`draw_tree`] shell.
#[derive(Clone, Copy, Debug)]
pub struct TreeView<'a> {
    /// Filtered tree rows (full list; view applies scroll/selection).
    pub rows: &'a [FlatRow],
    pub scroll_offset: usize,
    pub selected_idx: usize,
    pub visible_height: usize,
    pub left_root: &'a std::path::Path,
    pub right_root: &'a std::path::Path,
    pub active_side_left: bool,
    pub theme: Theme,
}

/// Borrowed render state for the directory-tree **footer** region (status toast, detail
/// line, filter bar, keybindings/scan banner, update hint).
///
/// Built by [`App::tree_footer_view`] in production, or hand-assembled in ui tests without
/// a full [`App`]. Separate from [`TreeView`] (content-only) because the footer needs
/// several more fields than the content pane ever reads — folding them into `TreeView`
/// would make [`draw_tree_content`] receive data it never uses.
#[derive(Clone, Copy, Debug)]
pub struct TreeFooterView<'a> {
    /// Selected tree row (for the width-dependent left/right detail line).
    pub row: Option<&'a FlatRow>,
    pub status_toast: Option<(&'a str, bool)>,
    pub filter_active: bool,
    pub filter_input: &'a crate::text_input::TextInput,
    pub filter_pattern: &'a str,
    pub filter_diffs_only: bool,
    pub scan_in_progress: bool,
    pub update_available: Option<&'a str>,
    pub install_method: &'a crate::upgrade::InstallMethod,
    pub theme: Theme,
}

/// Pure geometry-decision inputs for [`tree_layout`], shared with [`App::sync_viewport`]
/// (via [`App::tree_layout_inputs`]) so the sizing decision and the frame render read the
/// same booleans without either side borrowing `&App`. Same shape as [`DiffLayoutInputs`].
#[derive(Clone, Copy, Debug)]
pub struct TreeLayoutInputs {
    pub has_detail: bool,
    pub has_status: bool,
    pub has_filter: bool,
    pub has_update: bool,
}

/// Regions of the directory-tree screen.
pub struct TreeLayout {
    pub top_bar: Rect,
    /// Left file pane, borders included.
    pub left: Rect,
    /// Narrow column of `=` / `≠` / `⬅` / `➡` symbols between the panes.
    pub indicator: Rect,
    /// Right file pane, borders included.
    pub right: Rect,
    pub footer: Rect,
}

/// Split `area` into the directory-tree screen's regions.
///
/// Shared by [`draw_tree`] (via [`App::tree_layout_inputs`]) and [`App::sync_viewport`],
/// so the rects the renderer draws into and the geometry scrolling is clamped against
/// cannot drift apart.
pub fn tree_layout(inputs: &TreeLayoutInputs, area: Rect) -> TreeLayout {
    let TreeLayoutInputs {
        has_detail,
        has_status,
        has_filter,
        has_update,
    } = *inputs;
    let footer_height = match (has_detail, has_status, has_filter) {
        (true, true, true) => 4,
        (true, true, false) => 3,
        (true, false, true) | (false, true, true) => 3,
        (true, false, false) | (false, true, false) | (false, false, true) => 2,
        (false, false, false) => 1,
    } + if has_update { 1 } else { 0 };
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1),             // Top Bar (1 line)
            Constraint::Min(5),                // Body
            Constraint::Length(footer_height), // Footer
        ])
        .split(area);

    let body_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Min(30),   // Left
            Constraint::Length(4), // Indicator (no borders, symbols only)
            Constraint::Min(30),   // Right
        ])
        .split(chunks[1]);

    TreeLayout {
        top_bar: chunks[0],
        left: body_chunks[0],
        indicator: body_chunks[1],
        right: body_chunks[2],
        footer: chunks[2],
    }
}

/// Render the directory-tree screen.
///
/// Shell: layout + top bar (still need [`App`]). Content and footer paint through
/// [`draw_tree_content`]/[`draw_tree_footer`] with their own [`TreeView`]/[`TreeFooterView`]
/// so ui tests can exercise either region without a full app fixture.
pub fn draw_tree(f: &mut Frame, app: &App) {
    let inputs = app.tree_layout_inputs();
    let layout = tree_layout(&inputs, f.area());

    draw_top_bar(f, app, layout.top_bar);

    let view = app.tree_view();
    draw_tree_content(f, &view, &layout);

    let footer_view = app.tree_footer_view();
    draw_tree_footer(f, &footer_view, &layout);
}

/// Paint the directory-tree footer (status toast, detail line, filter bar,
/// keybindings/scan banner, update hint).
///
/// Same split as [`draw_tree_content`]: no `&App`, just `view` + `layout`. The
/// width-dependent detail-line padding needs `layout.footer.width`, so it computes
/// here rather than earlier — it can't be decided before the `Layout::split` that
/// produces the Rect.
pub fn draw_tree_footer(f: &mut Frame, view: &TreeFooterView<'_>, layout: &TreeLayout) {
    let theme = view.theme;

    let footer_txt = if view.scan_in_progress {
        Line::from("Scanning in progress... Please wait.")
    } else {
        Line::from(vec![
            Span::styled(" ; ", Style::default().fg(theme.accent).bold()),
            Span::raw("Menu  ·  "),
            Span::styled(" Ctrl+p ", Style::default().fg(theme.accent).bold()),
            Span::raw("Palette"),
        ])
    };

    // Build footer lines (top → bottom: status, detail, filter input, keybindings)
    let mut footer_lines: Vec<Line> = Vec::new();

    if let Some((msg, is_error)) = view.status_toast {
        let status_style = if is_error {
            Style::default().fg(theme.error).bold()
        } else {
            Style::default().fg(theme.success).bold()
        };
        let icon = if is_error { "" } else { "" };
        footer_lines.push(Line::from(Span::styled(
            format!("{}{}", icon, msg),
            status_style,
        )));
    }

    if let Some((left_detail, right_detail)) = selected_row_detail(view.row) {
        let left_len = left_detail.chars().count();
        let right_len = right_detail.chars().count();
        let total_width = layout.footer.width as usize;
        let padding = total_width.saturating_sub(left_len + right_len);
        let space = " ".repeat(padding);
        footer_lines.push(Line::from(vec![
            Span::styled(left_detail, Style::default().fg(theme.accent)),
            Span::raw(space),
            Span::styled(right_detail, Style::default().fg(theme.accent)),
        ]));
    }

    // Filter input bar (shown when filter is active or a pattern is committed)
    if view.filter_active {
        let mut filter_spans = vec![Span::styled(
            " Filter: ",
            Style::default().fg(theme.warn).bold(),
        )];
        filter_spans.extend(text_input_spans(
            view.filter_input,
            Style::default().fg(theme.warn),
        ));
        if view.filter_diffs_only {
            filter_spans.push(Span::styled(
                "  [diffs only]",
                Style::default().fg(theme.accent),
            ));
        }
        footer_lines.push(Line::from(filter_spans));
    } else if !view.filter_pattern.is_empty() || view.filter_diffs_only {
        let mut filter_spans = vec![
            Span::styled(" Filter: ", Style::default().fg(theme.warn).bold()),
            Span::raw(view.filter_pattern),
            Span::styled(
                "  (/:edit, Backspace at empty:clear)",
                Style::default().fg(theme.dim),
            ),
        ];
        if view.filter_diffs_only {
            filter_spans.push(Span::styled(
                "  [diffs only]",
                Style::default().fg(theme.accent),
            ));
        }
        footer_lines.push(Line::from(filter_spans));
    }

    footer_lines.push(footer_txt);

    if let Some(version) = view.update_available {
        let hint = crate::upgrade::update_hint(version, view.install_method);
        footer_lines.push(Line::from(Span::styled(
            hint,
            Style::default().fg(theme.warn).bold(),
        )));
    }
    let footer_p = Paragraph::new(footer_lines);
    f.render_widget(footer_p, layout.footer);
}

/// Paint the directory-tree content region (left / indicator / right panes).
///
/// Does not touch top bar or footer — those stay on the [`draw_tree`] shell.
pub fn draw_tree_content(f: &mut Frame, view: &TreeView<'_>, layout: &TreeLayout) {
    let theme = view.theme;

    let mut left_items = Vec::new();
    let mut indicator_items = Vec::new();
    let mut right_items = Vec::new();

    // Pad the indicator column with a blank top line so symbols align
    // vertically with items in the bordered left/right panes (which have
    // a top border row).
    indicator_items.push(ListItem::new(""));

    for (i, row) in view
        .rows
        .iter()
        .enumerate()
        .skip(view.scroll_offset)
        .take(view.visible_height)
    {
        let is_selected = i == view.selected_idx;
        let style = if is_selected {
            Style::default()
                .bg(theme.selection_bg)
                .fg(theme.selection_fg)
        } else {
            match row.state {
                DiffState::Identical => Style::default().fg(theme.muted),
                DiffState::DifferentNewerLeft
                | DiffState::DifferentNewerRight
                | DiffState::DifferentSameTime => Style::default().fg(theme.warn),
                DiffState::LeftOnly => Style::default().fg(theme.success),
                DiffState::RightOnly => Style::default().fg(theme.info),
                DiffState::TypeConflict => Style::default().fg(theme.error).bold(),
            }
        };

        let indent = "  ".repeat(row.depth);

        // Left item
        if let Some(ref left_info) = row.left {
            let icon = if left_info.is_dir { "📁 " } else { "📄 " };
            left_items.push(ListItem::new(format!("{}{}{}", indent, icon, row.name)).style(style));
        } else {
            left_items.push(ListItem::new("").style(style));
        }

        // Indicator
        let symbol = match row.state {
            DiffState::Identical => " =",
            DiffState::DifferentNewerLeft
            | DiffState::DifferentNewerRight
            | DiffState::DifferentSameTime => "",
            DiffState::LeftOnly => "",
            DiffState::RightOnly => "",
            DiffState::TypeConflict => " 💥",
        };
        indicator_items.push(ListItem::new(symbol).style(style));

        // Right item
        if let Some(ref right_info) = row.right {
            let icon = if right_info.is_dir { "📁 " } else { "📄 " };
            right_items.push(ListItem::new(format!("{}{}{}", indent, icon, row.name)).style(style));
        } else {
            right_items.push(ListItem::new("").style(style));
        }
    }

    let left_title = Line::from(vec![
        Span::raw(" "),
        Span::styled("[1] ", Style::default().fg(theme.accent).bold()),
        Span::styled(
            get_display_path(view.left_root, 31),
            Style::default().bold(),
        ),
        Span::raw(" "),
    ]);
    let right_title = Line::from(vec![
        Span::raw(" "),
        Span::styled("[2] ", Style::default().fg(theme.accent).bold()),
        Span::styled(
            get_display_path(view.right_root, 31),
            Style::default().bold(),
        ),
        Span::raw(" "),
    ]);

    let left_border_style = if view.active_side_left {
        Style::default().fg(theme.border_focus)
    } else {
        Style::default().fg(theme.dim)
    };

    let right_border_style = if !view.active_side_left {
        Style::default().fg(theme.border_focus)
    } else {
        Style::default().fg(theme.dim)
    };

    let left_list = List::new(left_items).block(
        Block::default()
            .title(left_title)
            .border_style(left_border_style)
            .borders(Borders::ALL),
    );

    let indicator_list = List::new(indicator_items);

    let right_list = List::new(right_items).block(
        Block::default()
            .title(right_title)
            .border_style(right_border_style)
            .borders(Borders::ALL),
    );

    f.render_widget(left_list, layout.left);
    f.render_widget(indicator_list, layout.indicator);
    f.render_widget(right_list, layout.right);
}

/// Format a `SystemTime` as a relative time string (e.g. "3d ago", "1y ago").
fn format_relative_time(t: &SystemTime) -> String {
    let now = SystemTime::now();
    match now.duration_since(*t) {
        Ok(dur) => {
            let secs = dur.as_secs();
            if secs < 60 {
                "just now".to_string()
            } else if secs < 3600 {
                format!("{}m ago", secs / 60)
            } else if secs < 86400 {
                format!("{}h ago", secs / 3600)
            } else if secs < 2_592_000 {
                format!("{}d ago", secs / 86400)
            } else if secs < 31_536_000 {
                format!("{}mo ago", secs / 2_592_000)
            } else {
                format!("{}y ago", secs / 31_536_000)
            }
        }
        Err(_) => format_system_time(t),
    }
}

/// Wrap a single line of text into chunks that fit within `width` display columns.
/// Preserves empty input as a single empty chunk so alignment is maintained.
fn wrap_text(text: &str, width: usize) -> Vec<String> {
    wrap_text_with_mask(text, &[], width)
        .into_iter()
        .map(|(line, _)| line)
        .collect()
}

/// Extract the visible portion of `text` starting at `h_scroll` character columns.
fn scrolled_text(text: &str, h_scroll: usize, width: usize) -> String {
    if width == 0 {
        return String::new();
    }
    text.chars().skip(h_scroll).take(width).collect()
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum DiffLineHighlight {
    None,
    /// Any row that belongs to a differing (mergeable) hunk.
    ChangeHunk,
    /// The hunk under the current scroll position (target for `[` / `]`).
    ActiveHunk,
    /// The physical row at `diff_scroll`.
    Cursor,
}

fn diff_line_highlight(
    in_change_hunk: bool,
    in_active_hunk: bool,
    is_cursor: bool,
) -> DiffLineHighlight {
    if is_cursor {
        DiffLineHighlight::Cursor
    } else if in_active_hunk {
        DiffLineHighlight::ActiveHunk
    } else if in_change_hunk {
        DiffLineHighlight::ChangeHunk
    } else {
        DiffLineHighlight::None
    }
}

fn apply_diff_line_highlight(style: Style, highlight: DiffLineHighlight, theme: Theme) -> Style {
    match highlight {
        DiffLineHighlight::None => style,
        DiffLineHighlight::ChangeHunk => style.bg(theme.hunk_bg),
        DiffLineHighlight::ActiveHunk => style.bg(theme.active_hunk_bg),
        DiffLineHighlight::Cursor => style.bg(theme.cursor_bg).bold(),
    }
}

#[derive(Clone)]
struct DiffDisplayCell {
    text: String,
    tag: Option<similar::ChangeTag>,
    intraline_mask: Option<Vec<bool>>,
    highlight: DiffLineHighlight,
}

fn diff_tag_base_style(tag: Option<similar::ChangeTag>, theme: Theme) -> Style {
    match tag {
        Some(similar::ChangeTag::Delete) => Style::default().fg(theme.error),
        Some(similar::ChangeTag::Insert) => Style::default().fg(theme.success),
        Some(similar::ChangeTag::Equal) => Style::default().fg(theme.muted),
        None => Style::default(),
    }
}

fn line_from_diff_cell(cell: &DiffDisplayCell, theme: Theme) -> Line<'static> {
    let base =
        apply_diff_line_highlight(diff_tag_base_style(cell.tag, theme), cell.highlight, theme);
    let Some(mask) = &cell.intraline_mask else {
        if cell.text.is_empty() && cell.highlight != DiffLineHighlight::None {
            return Line::from(Span::styled(" ", base));
        }
        return Line::from(Span::styled(cell.text.clone(), base));
    };

    let chars: Vec<char> = cell.text.chars().collect();
    if chars.is_empty() {
        if cell.highlight != DiffLineHighlight::None {
            return Line::from(Span::styled(" ", base));
        }
        return Line::from(Span::raw(""));
    }

    let mut aligned_mask = mask.clone();
    aligned_mask.truncate(chars.len());
    aligned_mask.resize(chars.len(), false);

    let mut spans = Vec::new();
    let mut run_start = 0usize;
    let mut run_highlight = aligned_mask[0];

    for i in 1..=chars.len() {
        if i == chars.len() || aligned_mask[i] != run_highlight {
            let run: String = chars[run_start..i].iter().collect();
            let style = if run_highlight {
                base.bold().underlined()
            } else {
                base.add_modifier(Modifier::DIM)
            };
            spans.push(Span::styled(run, style));
            if i < chars.len() {
                run_start = i;
                run_highlight = aligned_mask[i];
            }
        }
    }

    Line::from(spans)
}

fn wrap_text_with_mask(text: &str, mask: &[bool], width: usize) -> Vec<(String, Vec<bool>)> {
    if width == 0 {
        return vec![(text.to_string(), mask.to_vec())];
    }

    let chars: Vec<char> = text.chars().collect();
    let mut aligned_mask = mask.to_vec();
    aligned_mask.truncate(chars.len());
    aligned_mask.resize(chars.len(), false);

    let mut lines = Vec::new();
    let mut line_chars = Vec::new();
    let mut line_mask = Vec::new();
    let mut line_width = 0usize;

    for (ch, highlighted) in chars.iter().zip(aligned_mask.iter()) {
        let ch_width = if *ch == '\t' {
            4
        } else {
            ch.width().unwrap_or(0)
        };
        if line_width + ch_width > width && !line_chars.is_empty() {
            lines.push((line_chars.iter().collect(), std::mem::take(&mut line_mask)));
            line_chars.clear();
            line_width = 0;
        }
        line_chars.push(*ch);
        line_mask.push(*highlighted);
        line_width += ch_width;
    }

    if !line_chars.is_empty() || lines.is_empty() {
        lines.push((line_chars.into_iter().collect(), line_mask));
    }

    lines
}

fn scrolled_text_with_mask(
    text: &str,
    mask: &[bool],
    h_scroll: usize,
    width: usize,
) -> (String, Vec<bool>) {
    if width == 0 {
        return (String::new(), Vec::new());
    }
    let chars: Vec<char> = text.chars().skip(h_scroll).take(width).collect();
    let visible_mask: Vec<bool> = mask.iter().skip(h_scroll).take(width).copied().collect();
    (chars.into_iter().collect(), visible_mask)
}

fn push_diff_display_cells(
    cells: &mut Vec<DiffDisplayCell>,
    text: Option<&str>,
    tag: Option<similar::ChangeTag>,
    intraline_mask: Option<Vec<bool>>,
    wrap: bool,
    content_width: usize,
    h_scroll: usize,
) {
    let Some(text) = text else {
        cells.push(DiffDisplayCell {
            text: String::new(),
            tag: None,
            intraline_mask: None,
            highlight: DiffLineHighlight::None,
        });
        return;
    };

    if wrap {
        if let Some(mask) = intraline_mask.as_deref() {
            for (chunk, chunk_mask) in wrap_text_with_mask(text, mask, content_width) {
                cells.push(DiffDisplayCell {
                    text: chunk,
                    tag,
                    intraline_mask: Some(chunk_mask),
                    highlight: DiffLineHighlight::None,
                });
            }
        } else {
            for chunk in wrap_text(text, content_width) {
                cells.push(DiffDisplayCell {
                    text: chunk,
                    tag,
                    intraline_mask: None,
                    highlight: DiffLineHighlight::None,
                });
            }
        }
    } else {
        let (visible, visible_mask) = if let Some(mask) = intraline_mask.as_ref() {
            scrolled_text_with_mask(text, mask, h_scroll, content_width)
        } else {
            (scrolled_text(text, h_scroll, content_width), Vec::new())
        };
        cells.push(DiffDisplayCell {
            text: visible,
            tag,
            intraline_mask: if intraline_mask.is_some() {
                Some(visible_mask)
            } else {
                None
            },
            highlight: DiffLineHighlight::None,
        });
    }
}

/// Borrowed render state for the file-diff **content** region (info bar + panes).
///
/// Built by [`App::diff_view`] in production, or hand-assembled in ui tests without
/// standing up a full [`App`]. Top bar and footer stay on the `draw_diff` shell.
#[derive(Clone, Copy, Debug)]
pub struct DiffView<'a> {
    pub rows: &'a [crate::diff_view::DiffRow],
    pub wrap: bool,
    pub scroll: usize,
    pub h_scroll: usize,
    /// Content rows visible in each pane (from [`crate::app::Viewport`]).
    pub visible_height: usize,
    /// Content columns inside one pane (borders excluded).
    pub content_width: usize,
    pub left_root: &'a std::path::Path,
    pub right_root: &'a std::path::Path,
    /// Selected tree row that was opened into the diff (for titles / info bar).
    pub row: Option<&'a FlatRow>,
    pub left_hash: Option<&'a str>,
    pub right_hash: Option<&'a str>,
    pub left_line_ending: Option<&'a str>,
    pub right_line_ending: Option<&'a str>,
    pub theme: Theme,
    /// Active footer toast, if any: `(message, is_error)` (footer content).
    pub status_toast: Option<(&'a str, bool)>,
    /// Whether the two sides have any differing lines (keybinding-hint trimming, footer content).
    pub has_changes: bool,
    /// Latest update version when available (update hint, footer content).
    pub update_available: Option<&'a str>,
    pub install_method: &'a crate::upgrade::InstallMethod,
}

/// Pure geometry-decision inputs for [`diff_layout`], shared with [`App::sync_viewport`]
/// (via [`App::diff_layout_inputs`]) so the sizing decision and the frame render read the
/// same booleans without either side borrowing `&App`.
#[derive(Clone, Copy, Debug)]
pub struct DiffLayoutInputs {
    pub has_changes: bool,
    /// Selected row has content on either side (used with `!has_changes` to show the
    /// "files are identical" notice).
    pub row_has_content: bool,
    pub has_status: bool,
    pub has_update: bool,
}

/// Regions of the file-diff screen.
pub struct DiffLayout {
    pub top_bar: Rect,
    /// Row below the top bar carrying the "files are identical" notice; empty
    /// unless [`DiffLayout::show_identical`].
    pub notice: Rect,
    /// Left half of the info bar (size + SHA-256 + line ending).
    pub info_left: Rect,
    /// Right half of the info bar.
    pub info_right: Rect,
    /// Left diff pane, borders included.
    pub left: Rect,
    /// Right diff pane, borders included.
    pub right: Rect,
    pub footer: Rect,
    /// True when the two sides have no differing lines.
    pub show_identical: bool,
}

/// Split `area` into the file-diff screen's regions.
///
/// Shared by [`draw_diff`] (via [`App::diff_layout_inputs`]) and [`App::sync_viewport`],
/// so the rects the renderer draws into and the geometry scrolling is clamped against
/// cannot drift apart.
pub fn diff_layout(inputs: &DiffLayoutInputs, area: Rect) -> DiffLayout {
    let show_identical = !inputs.has_changes && inputs.row_has_content;

    let header_height = if show_identical { 2 } else { 1 };
    let footer_height =
        if inputs.has_status { 2 } else { 1 } + if inputs.has_update { 1 } else { 0 };
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(header_height), // Header (Top Bar + optional Identical Msg)
            Constraint::Length(1),             // Info bar (size + SHA-256)
            Constraint::Min(5),                // Body
            Constraint::Length(footer_height), // Footer
        ])
        .split(area);

    let header_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Min(0)])
        .split(chunks[0]);

    let info_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
        .split(chunks[1]);

    let body_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
        .split(chunks[2]);

    DiffLayout {
        top_bar: header_layout[0],
        notice: header_layout[1],
        info_left: info_chunks[0],
        info_right: info_chunks[1],
        left: body_chunks[0],
        right: body_chunks[1],
        footer: chunks[3],
        show_identical,
    }
}

/// Render the file-diff screen.
///
/// Shell: layout + top bar (still need [`App`]). Content and footer paint through
/// [`draw_diff_content`]/[`draw_diff_footer`] with one shared [`DiffView`] so ui tests
/// can exercise either region without a full app fixture.
pub fn draw_diff(f: &mut Frame, app: &App) {
    let inputs = app.diff_layout_inputs();
    let layout = diff_layout(&inputs, f.area());

    draw_top_bar(f, app, layout.top_bar);

    let view = app.diff_view();
    draw_diff_content(f, &view, &layout);
    draw_diff_footer(f, &view, &layout);
}

/// Paint the file-diff footer (status toast, keybindings, update hint).
///
/// Same split as [`draw_diff_content`]: no `&App`, just `view` + `layout`.
pub fn draw_diff_footer(f: &mut Frame, view: &DiffView<'_>, layout: &DiffLayout) {
    let theme = view.theme;

    // Build footer lines (top → bottom: status, keybindings)
    let mut footer_lines: Vec<Line> = Vec::new();

    if let Some((msg, is_error)) = view.status_toast {
        let status_style = if is_error {
            Style::default().fg(theme.error).bold()
        } else {
            Style::default().fg(theme.success).bold()
        };
        let icon = if is_error { "" } else { "" };
        footer_lines.push(Line::from(Span::styled(
            format!("{}{}", icon, msg),
            status_style,
        )));
    }

    let mut footer_spans = vec![
        Span::styled(" N ", Style::default().fg(theme.accent).bold()),
        Span::raw("Next  ·  "),
        Span::styled(" P ", Style::default().fg(theme.accent).bold()),
        Span::raw("Prev  ·  "),
        Span::styled(" [ ", Style::default().fg(theme.accent).bold()),
        Span::raw("Hunk←  ·  "),
        Span::styled(" ] ", Style::default().fg(theme.accent).bold()),
        Span::raw("Hunk→  ·  "),
        Span::styled(" ; ", Style::default().fg(theme.accent).bold()),
        Span::raw("Menu  ·  "),
        Span::styled(" Ctrl+p ", Style::default().fg(theme.accent).bold()),
        Span::raw("Palette"),
    ];
    if !view.has_changes {
        footer_spans.drain(0..10);
    }
    footer_lines.push(Line::from(footer_spans));

    if let Some(version) = view.update_available {
        let hint = crate::upgrade::update_hint(version, view.install_method);
        footer_lines.push(Line::from(Span::styled(
            hint,
            Style::default().fg(theme.warn).bold(),
        )));
    }
    let footer_p = Paragraph::new(footer_lines);
    f.render_widget(footer_p, layout.footer);
}

/// Paint the file-diff content region (identical notice, info bar, dual panes).
///
/// Does not touch top bar or footer — those stay on the [`draw_diff`] shell.
/// Geometry comes from `layout` (shell/`diff_layout`); line data from `view`.
pub fn draw_diff_content(f: &mut Frame, view: &DiffView<'_>, layout: &DiffLayout) {
    let theme = view.theme;
    let show_identical = layout.show_identical;

    if show_identical {
        let msg = Paragraph::new(Line::from(Span::styled(
            " ✓ Both files are identical — no differences found.",
            Style::default().fg(theme.success).bold(),
        )));
        f.render_widget(msg, layout.notice);
    }

    // Info bar: size + SHA-256 hash for each side, above the pane borders
    let left_info =
        build_diff_info_spans(view.row, true, view.left_hash, view.left_line_ending, theme);
    let right_info = build_diff_info_spans(
        view.row,
        false,
        view.right_hash,
        view.right_line_ending,
        theme,
    );
    f.render_widget(Paragraph::new(left_info), layout.info_left);
    f.render_widget(Paragraph::new(right_info), layout.info_right);

    let max_visible = view.visible_height;
    let content_width = view.content_width;

    let Some(row) = view.row else {
        return;
    };

    let mut left_physical: Vec<DiffDisplayCell> = Vec::new();
    let mut right_physical: Vec<DiffDisplayCell> = Vec::new();

    let hunk_row_ranges = crate::diff_view::diff_hunk_row_ranges(view.rows);
    let active_hunk_rows =
        crate::diff_view::hunk_index_at_scroll(view.rows, view.scroll, content_width, view.wrap)
            .and_then(|idx| hunk_row_ranges.get(idx).cloned());

    let mut physical_row = 0usize;
    for (logical_row, (left_line, right_line)) in view.rows.iter().enumerate() {
        let in_change_hunk = hunk_row_ranges
            .iter()
            .any(|range| range.contains(&logical_row));
        let in_active_hunk = active_hunk_rows
            .as_ref()
            .is_some_and(|range| range.contains(&logical_row));
        let left_text = left_line.as_ref().map(|l| l.text.trim_end());
        let right_text = right_line.as_ref().map(|r| r.text.trim_end());
        let left_tag = left_line.as_ref().map(|l| l.tag);
        let right_tag = right_line.as_ref().map(|r| r.tag);

        let replacement = crate::diff_view::is_replacement_pair(left_line, right_line);
        let left_mask = replacement
            .then(|| {
                left_text
                    .zip(right_text)
                    .map(|(left, right)| crate::diff_view::intraline_change_mask(left, right, true))
            })
            .flatten();
        let right_mask = replacement
            .then(|| {
                left_text.zip(right_text).map(|(left, right)| {
                    crate::diff_view::intraline_change_mask(right, left, false)
                })
            })
            .flatten();

        let mut left_chunk = Vec::new();
        let mut right_chunk = Vec::new();
        push_diff_display_cells(
            &mut left_chunk,
            left_text,
            left_tag,
            left_mask,
            view.wrap,
            content_width,
            view.h_scroll,
        );
        push_diff_display_cells(
            &mut right_chunk,
            right_text,
            right_tag,
            right_mask,
            view.wrap,
            content_width,
            view.h_scroll,
        );

        let max_lines = std::cmp::max(left_chunk.len(), right_chunk.len());
        for i in 0..max_lines {
            let highlight = diff_line_highlight(
                in_change_hunk,
                in_active_hunk,
                physical_row + i == view.scroll,
            );
            left_physical.push(
                left_chunk
                    .get(i)
                    .cloned()
                    .map(|mut cell| {
                        cell.highlight = highlight;
                        cell
                    })
                    .unwrap_or(DiffDisplayCell {
                        text: String::new(),
                        tag: left_tag,
                        intraline_mask: None,
                        highlight,
                    }),
            );
            right_physical.push(
                right_chunk
                    .get(i)
                    .cloned()
                    .map(|mut cell| {
                        cell.highlight = highlight;
                        cell
                    })
                    .unwrap_or(DiffDisplayCell {
                        text: String::new(),
                        tag: right_tag,
                        intraline_mask: None,
                        highlight,
                    }),
            );
        }
        physical_row += max_lines;
    }

    let left_lines: Vec<Line> = left_physical
        .into_iter()
        .skip(view.scroll)
        .take(max_visible)
        .map(|cell| line_from_diff_cell(&cell, theme))
        .collect();

    let right_lines: Vec<Line> = right_physical
        .into_iter()
        .skip(view.scroll)
        .take(max_visible)
        .map(|cell| line_from_diff_cell(&cell, theme))
        .collect();

    // Build pane titles: " /truncated/path/file.txt (3d ago) "
    let pane_width = layout.left.width as usize;
    let left_title = build_diff_pane_title(
        &view.left_root.join(&row.relative_path),
        row.left.as_ref().map(|f| &f.modified),
        pane_width,
    );
    let right_title = build_diff_pane_title(
        &view.right_root.join(&row.relative_path),
        row.right.as_ref().map(|f| &f.modified),
        pane_width,
    );

    let left_p = Paragraph::new(left_lines).block(
        Block::default()
            .title(Span::styled(left_title, Style::default().bold()))
            .borders(Borders::ALL),
    );
    let right_p = Paragraph::new(right_lines).block(
        Block::default()
            .title(Span::styled(right_title, Style::default().bold()))
            .borders(Borders::ALL),
    );

    f.render_widget(left_p, layout.left);
    f.render_widget(right_p, layout.right);
    draw_close_button(f, layout.right);
}

/// Build info spans (size + line ending style + SHA-256 hash) for the diff view info bar.
fn build_diff_info_spans<'a>(
    row: Option<&'a FlatRow>,
    is_left: bool,
    hash: Option<&'a str>,
    line_ending: Option<&'a str>,
    theme: Theme,
) -> Line<'a> {
    let info = row.and_then(|r| {
        if is_left {
            r.left.as_ref()
        } else {
            r.right.as_ref()
        }
    });

    let mut spans = vec![Span::raw(" ")];

    if let Some(fi) = info {
        if !fi.is_dir {
            spans.push(Span::styled(
                format_size(fi.size),
                Style::default().fg(theme.dim),
            ));
            spans.push(Span::raw("  "));
        }
    }

    if let Some(le) = line_ending {
        spans.push(Span::styled(
            format!("[{}]", le),
            Style::default().fg(theme.dim),
        ));
        spans.push(Span::raw("  "));
    }

    if let Some(h) = hash {
        spans.push(Span::styled(
            format!("SHA256: {h}"),
            Style::default().fg(theme.dim),
        ));
    } else {
        spans.push(Span::styled("SHA256: —", Style::default().fg(theme.dim)));
    }

    Line::from(spans)
}
fn build_diff_pane_title(
    full_path: &std::path::Path,
    modified: Option<&SystemTime>,
    pane_width: usize,
) -> String {
    let rel_time = modified.map(format_relative_time).unwrap_or_default();
    // Reserve space for the leading space + " (rel_time) " + borders
    let suffix_len = rel_time.len() + 4; // " (rel_time) "
    let max_path = pane_width.saturating_sub(suffix_len + 2).max(10);
    let display_path = get_display_path(full_path, max_path);
    format!(" {} ({}) ", display_path, rel_time)
}

/// 0-indexed row of the clickable repo-URL line within the `About` topic body (see the
/// `HelpTopic::About` arm of `help_topic_body`) — kept in sync with `handle_mouse`'s click
/// detection in `input.rs`. Stable regardless of update-check state since the URL line always
/// comes before the optional update-hint line.
pub(crate) const ABOUT_REPO_LINE: u16 = 2;

/// Borrowed render state for the Help **body** region (topic list or scrolled body).
///
/// Built by [`App::help_view`]; top bar and footer stay on the [`draw_help`] shell.
#[derive(Clone, Copy, Debug)]
pub struct HelpView<'a> {
    pub topic: HelpTopic,
    pub index_open: bool,
    pub index_sel: usize,
    pub scroll: u16,
    pub theme: Theme,
    /// Latest update version when available (About topic footer line).
    pub update_available: Option<&'a str>,
    pub install_method: &'a crate::upgrade::InstallMethod,
}

fn help_topic_body(
    topic: HelpTopic,
    theme: Theme,
    update_available: Option<&str>,
    install_method: &crate::upgrade::InstallMethod,
) -> Text<'static> {
    match topic {
        HelpTopic::DirectoryTree => Text::from(
            "\
Navigation
  j / Down       move selection down
  k / Up         move selection up
  Ctrl+f         page selection down (about one screen)
  Ctrl+b         page selection up (about one screen)
  h / Left       collapse the selected directory
  l / Right      expand the selected directory
  Space          toggle expand/collapse
  Tab            switch focus between the Left and Right panes
  1 / 2          jump focus directly to the Left / Right pane

Actions
  Enter          open the diff view (or toggle expand, for a directory)
  D              compare the selected file pair with the external diff tool
  E              edit the selected file in $EDITOR/$VISUAL
  L              copy the selected item from the right pane to the left (y/n confirm)
  R              copy the selected item from the left pane to the right (y/n confirm)
  C              open the Config menu
  c              toggle Fast / Precise scan mode (re-scans)
  r              force a manual re-scan
  s              swap the left and right directories
  /              open the filter bar (f while typing: diffs-only toggle)
  ?              show this help
  q / Esc        quit",
        ),
        HelpTopic::FileDiff => Text::from(
            "  Limits         UTF-8 text only, max 10 MiB per side
                 (binary / non-UTF-8 / oversized → toast; use D)
  j / Down       scroll down one line
  k / Up         scroll up one line
  Ctrl+f         page scroll down (about one screen)
  Ctrl+b         page scroll up (about one screen)
  N / Alt+Down   jump to next change block
  P / Alt+Up     jump to previous change block
  Left / Right   scroll horizontally (only while wrap is off)
  Highlighting   mergeable blocks are tinted; the active block and
                 current line are emphasized for `[` / `]` targets
  [              copy the change block under the cursor to the left
  ]              copy the change block under the cursor to the right
  l / L          copy the whole right file to the left side (y/n confirm)
  r / R          copy the whole left file to the right side (y/n confirm)
  w              toggle line wrapping
  f              toggle full-file context vs diff-only
  C              open the Config menu (returns here on Esc/q)
  ?              show this help
  q / Esc        return to the Directory Tree view",
        ),
        HelpTopic::Config => Text::from(
            "  j / k, Down / Up   move the selection
  Enter / Space      select the highlighted external diff tool
                     or toggle Check for updates / Mouse support / Theme
  T                  toggle light/dark theme from anywhere (persists)
  h / l, Left / Right  adjust the Diff context line count
  ?                  show this help
  q / Esc            return to the screen you opened Config from

  Settings are saved to ~/.config/duodiff/config.toml (honors
  XDG_CONFIG_HOME). See config.example.toml in the repo for every
  field, its default, and what it does.",
        ),
        HelpTopic::Mouse => Text::from(
            "  Left Click     select the clicked row
  Right Click    select a row and open the context menu
  Double Click   open diff view for a file, or expand/collapse a directory
  Scroll         scroll the directory tree, diff lines, Config screen, Help
                 topic/index, or the menu/palette list; over the Config
                 screen's Diff context row, scroll adjusts its value

  Mouse is on by default; disable it in Config, in config.toml
  (mouse = false), or for one session with --no-mouse.",
        ),
        HelpTopic::General => Text::from(
            "  ?              show this help
  q / Esc        quit (or back, on any sub-screen)
  T              toggle light/dark theme (persists across restart)
  Tab            (inside Help) open the topic index list
  1-6            (inside Help) jump straight to a topic",
        ),
        HelpTopic::About => {
            let repo = env!("CARGO_PKG_REPOSITORY")
                .trim_start_matches("https://")
                .trim_start_matches("http://");
            let mut lines = vec![
                Line::from(format!("duodiff v{}", env!("CARGO_PKG_VERSION"))),
                Line::from(""),
                Line::from(vec![
                    Span::raw("  "),
                    Span::styled(
                        repo.to_string(),
                        Style::default()
                            .fg(theme.fg)
                            .add_modifier(Modifier::UNDERLINED),
                    ),
                ]),
                Line::from(""),
            ];
            if let Some(version) = update_available {
                lines.push(Line::from(crate::upgrade::update_hint(
                    version,
                    install_method,
                )));
            }
            Text::from(lines)
        }
    }
}

/// Render the Help screen.
///
/// Shell: top bar + footer. Body paints through [`draw_help_content`].
pub fn draw_help(f: &mut Frame, app: &App) {
    let theme = app.theme();
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // Top Bar
            Constraint::Min(0),    // Content
            Constraint::Length(1), // Footer
        ])
        .split(f.area());

    draw_top_bar(f, app, chunks[0]);

    let view = app.help_view();
    draw_help_content(f, &view, chunks[1]);

    let footer = Paragraph::new(Line::from(vec![
        Span::styled(" ; ", Style::default().fg(theme.accent).bold()),
        Span::raw("Menu  ·  "),
        Span::styled(" Ctrl+p ", Style::default().fg(theme.accent).bold()),
        Span::raw("Palette"),
    ]));
    f.render_widget(footer, chunks[2]);
}

/// Paint the Help body (topic index list or scrolled topic text + close button).
pub fn draw_help_content(f: &mut Frame, view: &HelpView<'_>, body_area: Rect) {
    let theme = view.theme;
    if view.index_open {
        let items: Vec<ListItem> = HelpTopic::all()
            .iter()
            .enumerate()
            .map(|(i, t)| ListItem::new(format!("  {}  {}", i + 1, t.title())))
            .collect();
        let list = List::new(items)
            .block(
                Block::default()
                    .title("Help — pick a topic (1-6 / j/k Enter · Esc back)")
                    .borders(Borders::ALL),
            )
            .highlight_style(
                Style::default()
                    .bg(theme.selection_bg)
                    .fg(theme.selection_fg),
            );
        let mut list_state = ListState::default();
        list_state.select(Some(view.index_sel));
        f.render_stateful_widget(list, body_area, &mut list_state);
    } else {
        let title = format!(
            "Help · {} — Tab topics · j/k scroll · Esc back",
            view.topic.title()
        );
        let paragraph = Paragraph::new(help_topic_body(
            view.topic,
            theme,
            view.update_available,
            view.install_method,
        ))
        .scroll((view.scroll, 0))
        .block(Block::default().title(title).borders(Borders::ALL));
        f.render_widget(paragraph, body_area);
    }

    draw_close_button(f, body_area);
}

/// Render state for the Config **list** region.
///
/// Built by [`App::config_view`] after `ensure_config_selection` (shell-side).
/// `rows` is owned because [`App::config_rows`] already allocates a fresh list.
#[derive(Clone, Debug)]
pub struct ConfigView<'a> {
    pub rows: Vec<crate::app::ConfigRowKind>,
    pub selected_idx: usize,
    pub detected_diff_tools: &'a [(crate::diff_tool::ExternalDiffTool, bool)],
    pub external_diff_tool: Option<&'a str>,
    pub check_updates: bool,
    pub mouse: bool,
    pub theme_choice: crate::theme::ThemeChoice,
    pub diff_context: usize,
    pub theme: Theme,
}

/// Render the Config screen.
///
/// Shell: top bar, `ensure_config_selection`, footer. List paints through
/// [`draw_config_content`].
pub fn draw_config(f: &mut Frame, app: &mut App) {
    let theme = app.theme();
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // Top Bar
            Constraint::Min(5),
            Constraint::Length(1),
        ])
        .split(f.area());

    draw_top_bar(f, app, chunks[0]);
    // Mut side effect stays on the shell so content can be pure-read.
    app.ensure_config_selection();
    let view = app.config_view();
    draw_config_content(f, &view, chunks[1]);

    let footer = Paragraph::new(Line::from(vec![
        Span::styled(" ; ", Style::default().fg(theme.accent).bold()),
        Span::raw("Menu  ·  "),
        Span::styled(" Ctrl+p ", Style::default().fg(theme.accent).bold()),
        Span::raw("Palette"),
    ]));
    f.render_widget(footer, chunks[2]);
}

/// Paint the Config list + close button (no top bar / footer).
pub fn draw_config_content(f: &mut Frame, view: &ConfigView<'_>, body_area: Rect) {
    let theme = view.theme;
    let mut items = Vec::new();
    for (row_idx, row) in view.rows.iter().enumerate() {
        let style = if row_idx == view.selected_idx {
            Style::default()
                .bg(theme.selection_bg)
                .fg(theme.selection_fg)
        } else {
            Style::default()
        };
        match row {
            crate::app::ConfigRowKind::Header(label) => {
                items.push(ListItem::new(Line::from(Span::styled(
                    *label,
                    Style::default().fg(theme.warn).bold(),
                ))));
            }
            crate::app::ConfigRowKind::DiffTool(tool_idx) => {
                let (tool, is_avail) = &view.detected_diff_tools[*tool_idx];
                let is_active = view.external_diff_tool == Some(tool.as_str());
                let marker = if is_active { "[x] " } else { "[ ] " };
                let avail_str = if *is_avail {
                    "(Available)"
                } else {
                    "(Not Found)"
                };
                items.push(
                    ListItem::new(format!("  {}{:<5} {}", marker, tool.as_str(), avail_str))
                        .style(style),
                );
            }
            crate::app::ConfigRowKind::CheckUpdates => {
                let marker = if view.check_updates { "[x] " } else { "[ ] " };
                items.push(
                    ListItem::new(format!("  {}Check for updates daily", marker)).style(style),
                );
            }
            crate::app::ConfigRowKind::Mouse => {
                let marker = if view.mouse { "[x] " } else { "[ ] " };
                items.push(ListItem::new(format!("  {}Enable mouse support", marker)).style(style));
            }
            crate::app::ConfigRowKind::Theme => {
                let marker = if view.theme_choice == crate::theme::ThemeChoice::Light {
                    "[x] "
                } else {
                    "[ ] "
                };
                items.push(
                    ListItem::new(format!("  {}Light theme (off = dark)", marker)).style(style),
                );
            }
            crate::app::ConfigRowKind::DiffContext => {
                items.push(
                    ListItem::new(format!(
                        "      Diff context: {} lines (h/l to adjust)",
                        view.diff_context
                    ))
                    .style(style),
                );
            }
        }
    }

    let list = List::new(items).block(
        Block::default()
            .title("Configuration")
            .borders(Borders::ALL),
    );
    f.render_widget(list, body_area);
    draw_close_button(f, body_area);
}

/// The `[x]` close button's rectangle within `area`, or `None` if `area` is too
/// narrow to fit it. Shared by `draw_close_button` (render) and every close-button
/// hit test, so the two cannot drift apart.
pub fn close_button_rect(area: Rect) -> Option<Rect> {
    if area.width < 6 {
        return None;
    }
    Some(Rect {
        x: area.x + area.width.saturating_sub(5),
        y: area.y,
        width: 3,
        height: 1,
    })
}

pub fn draw_close_button(f: &mut Frame, area: Rect) {
    if let Some(button_area) = close_button_rect(area) {
        f.render_widget(Paragraph::new(Span::raw("[x]")), button_area);
    }
}

pub fn centered_rect(width: u16, height: u16, parent: Rect) -> Rect {
    let popup_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length((parent.height.saturating_sub(height)) / 2),
            Constraint::Length(height),
            Constraint::Min(0),
        ])
        .split(parent);

    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Length((parent.width.saturating_sub(width)) / 2),
            Constraint::Length(width),
            Constraint::Min(0),
        ])
        .split(popup_layout[1])[1]
}

/// The rectangle the Command Palette popup occupies for the given mode/item
/// count, centered within `area`. Shared by `draw_palette` (render) and
/// `input::handle_mouse`'s click hit-test, so the two can't drift apart.
pub fn palette_popup_rect(mode: PaletteMode, item_count: usize, area: Rect) -> Rect {
    let (pop_w, pop_h) = match mode {
        PaletteMode::Menu => (50, (item_count + 2).max(4) as u16),
        PaletteMode::Command => (55, 12),
    };
    centered_rect(pop_w, pop_h, area)
}

/// The dispatch key a palette/menu entry carries. `App::build_palette_actions`
/// constructs it; `actions::execute_palette_action` matches on it exhaustively —
/// adding a variant without a matching dispatch arm is a compile error.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PaletteActionId {
    ExternalDiff,
    ExternalEdit,
    CopyLeftToRight,
    CopyRightToLeft,
    BuiltinDiff,
    SwapPaths,
    ToggleScan,
    Refresh,
    Config,
    Help,
    Filter,
    Quit,
    ToggleWrap,
    ToggleFullDiff,
    NextChange,
    PrevChange,
    CopyHunkLeftToRight,
    CopyHunkRightToLeft,
    Back,
}

/// A single palette/menu entry — pure view-model data (what a row looks like and
/// which dispatch key it carries). `App::build_palette_actions` only constructs it;
/// `actions::execute_palette_action` only matches on its `action_id` field — nothing
/// pattern-matches the struct itself, so it lives here rather than on `App` (unlike
/// `ConfigRowKind`, which is genuine `App`-domain selection logic).
#[derive(Clone, Debug)]
pub struct PaletteAction {
    pub key: String,
    pub label: String,
    pub action_id: PaletteActionId,
    pub enabled: bool,
}

/// Borrowed render state for the Command Palette / Menu popup.
///
/// Built by [`App::palette_view`] after shell-side [`App::refresh_palette_items`].
#[derive(Clone, Copy, Debug)]
pub struct PaletteView<'a> {
    pub mode: PaletteMode,
    pub items: &'a [PaletteAction],
    pub selected_idx: usize,
    pub query: &'a str,
    pub theme: Theme,
}

/// Render the palette/menu popup.
///
/// Shell: `refresh_palette_items` (mut). Content paints through
/// [`draw_palette_content`].
pub fn draw_palette(f: &mut Frame, app: &mut App) {
    app.refresh_palette_items();
    let view = app.palette_view();
    draw_palette_content(f, &view, f.area());
}

/// Paint the palette/menu popup inside `frame_area` (computes popup rect itself).
pub fn draw_palette_content(f: &mut Frame, view: &PaletteView<'_>, frame_area: Rect) {
    let theme = view.theme;
    let mode = view.mode;
    let count = view.items.len();

    let area = palette_popup_rect(mode, count, frame_area);
    f.render_widget(Clear, area);

    let title = match mode {
        PaletteMode::Menu => " Menu ".to_string(),
        PaletteMode::Command => " Palette (Ctrl+p) ".to_string(),
    };

    let block = Block::default()
        .title(Span::styled(title, Style::default().bold()))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(theme.warn));

    match mode {
        PaletteMode::Menu => {
            let mut list_items = Vec::new();
            for (i, action) in view.items.iter().enumerate() {
                let display_text = format!("  {:<5}  {}", action.key, action.label);
                let mut style = if i == view.selected_idx {
                    Style::default().bg(theme.info).fg(theme.selection_fg)
                } else {
                    Style::default()
                };
                if !action.enabled {
                    style = style.fg(theme.dim);
                }
                list_items.push(ListItem::new(display_text).style(style));
            }
            let list = List::new(list_items).block(block);
            f.render_widget(list, area);
            draw_close_button(f, area);
        }
        PaletteMode::Command => {
            // Internal layout of command palette
            let inner_chunks = Layout::default()
                .direction(Direction::Vertical)
                .constraints([
                    Constraint::Length(1), // Query input line
                    Constraint::Length(1), // Separator line
                    Constraint::Min(0),    // List of matches
                ])
                .split(block.inner(area));

            // Query text paragraph
            let query_text = Line::from(vec![
                Span::styled(" Query: ", Style::default().fg(theme.accent)),
                Span::raw(view.query),
                Span::styled("", Style::default().fg(theme.emphasis)),
            ]);
            f.render_widget(Paragraph::new(query_text), inner_chunks[0]);

            // Separator
            let separator = Paragraph::new(Line::from(vec![Span::styled(
                "".repeat(inner_chunks[1].width as usize),
                Style::default().fg(theme.dim),
            )]));
            f.render_widget(separator, inner_chunks[1]);

            // List of matching actions
            let mut list_items = Vec::new();
            for (i, action) in view.items.iter().enumerate() {
                let display_text = format!("  {:<5}  {}", action.key, action.label);
                let mut style = if i == view.selected_idx {
                    Style::default().bg(theme.info).fg(theme.selection_fg)
                } else {
                    Style::default()
                };
                if !action.enabled {
                    style = style.fg(theme.dim);
                }
                list_items.push(ListItem::new(display_text).style(style));
            }
            let list = List::new(list_items);
            f.render_widget(list, inner_chunks[2]);

            // Render block borders around the entire popup
            f.render_widget(block, area);
            draw_close_button(f, area);
        }
    }
}

/// Borrowed confirm-dialog state (message + theme).
#[derive(Clone, Copy, Debug)]
pub struct ConfirmView<'a> {
    pub message: &'a str,
    pub theme: Theme,
}

/// Render the confirm modal from an [`App`].
pub fn draw_confirm_modal(f: &mut Frame, app: &App) {
    let view = app.confirm_view();
    draw_confirm_content(f, &view, f.area());
}

/// Paint the confirm popup (no full `App` required).
pub fn draw_confirm_content(f: &mut Frame, view: &ConfirmView<'_>, frame_area: Rect) {
    let theme = view.theme;
    let area = centered_rect(60, 7, frame_area);
    f.render_widget(Clear, area);

    let block = Block::default()
        .title(" Confirm Action ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(theme.warn));

    let text = vec![
        Line::from(""),
        Line::from(Span::raw(view.message)).alignment(Alignment::Center),
        Line::from(""),
        Line::from(Span::styled(
            " [Y] Yes   [N] No (Cancel) ",
            Style::default().fg(theme.accent),
        ))
        .alignment(Alignment::Center),
    ];

    let paragraph = Paragraph::new(text).block(block);
    f.render_widget(paragraph, area);
    draw_close_button(f, area);
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::backend::TestBackend;
    use ratatui::Terminal;
    use std::path::PathBuf;

    /// Render one frame the way the event loop does: sync the viewport for the
    /// current terminal size first, then draw. Drawing without the sync would
    /// render against stale (on the first frame, zero-sized) geometry.
    fn draw_frame(terminal: &mut Terminal<TestBackend>, app: &mut App) {
        app.sync_viewport(terminal.size().unwrap().into());
        terminal.draw(|f| draw(f, app)).unwrap();
    }

    /// `(visible_height, content_width)` for a [`DiffLayout`]'s left pane, the same way
    /// `App::sync_viewport` derives it — used by diff-content tests that build their own
    /// `DiffView`/`DiffLayout` via [`diff_layout`] instead of a full `App`.
    fn diff_content_geometry(layout: &DiffLayout) -> (usize, usize) {
        (
            layout.left.height.saturating_sub(2) as usize,
            layout.left.width.saturating_sub(2) as usize,
        )
    }

    /// Owned data backing a hand-built [`DiffView`] for content-only diff tests, so each
    /// test only spells out what it actually varies (rows, theme, hashes, ...) instead of
    /// repeating the same defaulted fields (`left_root`/`right_root`/`install_method`/etc.).
    struct DiffViewFixture {
        rows: Vec<crate::diff_view::DiffRow>,
        flat: FlatRow,
        left_root: PathBuf,
        right_root: PathBuf,
        method: crate::upgrade::InstallMethod,
        theme: Theme,
        left_hash: Option<String>,
        right_hash: Option<String>,
    }

    impl DiffViewFixture {
        fn new(rows: Vec<crate::diff_view::DiffRow>, flat: FlatRow) -> Self {
            Self {
                rows,
                flat,
                left_root: PathBuf::from("/left"),
                right_root: PathBuf::from("/right"),
                method: crate::upgrade::InstallMethod::Standalone,
                theme: Theme::DARK,
                left_hash: None,
                right_hash: None,
            }
        }

        /// Same rule `FileDiffState::has_changes` uses: at least one added/removed line.
        fn has_changes(&self) -> bool {
            self.rows.iter().any(crate::diff_view::diff_row_is_change)
        }

        fn view(
            &self,
            wrap: bool,
            scroll: usize,
            h_scroll: usize,
            visible_height: usize,
            content_width: usize,
        ) -> DiffView<'_> {
            DiffView {
                rows: &self.rows,
                wrap,
                scroll,
                h_scroll,
                visible_height,
                content_width,
                left_root: &self.left_root,
                right_root: &self.right_root,
                row: Some(&self.flat),
                left_hash: self.left_hash.as_deref(),
                right_hash: self.right_hash.as_deref(),
                left_line_ending: None,
                right_line_ending: None,
                theme: self.theme,
                status_toast: None,
                has_changes: self.has_changes(),
                update_available: None,
                install_method: &self.method,
            }
        }
    }

    #[test]
    fn test_ui_drawing() {
        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = App::new(PathBuf::from("/left"), PathBuf::from("/right"));

        draw_frame(&mut terminal, &mut app);

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        println!("Buffer output:\n{:?}", buffer);

        assert!(
            buffer_string.contains("[1]") && buffer_string.contains("/left"),
            "Left pane title should show [1] before the path"
        );
        assert!(
            buffer_string.contains("[2]") && buffer_string.contains("/right"),
            "Right pane title should show [2] before the path"
        );
        // The State column title was removed; verify indicator symbols render
        assert!(
            !buffer_string.contains("\"State\""),
            "State column title should be removed"
        );
    }

    #[test]
    fn test_draw_help_topic_body_shows_title_and_bindings() {
        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = App::new(PathBuf::from("/left"), PathBuf::from("/right"));
        app.set_view_mode(ViewMode::Help);
        app.help_mut()
            .select_topic(crate::app::HelpTopic::DirectoryTree);

        draw_frame(&mut terminal, &mut app);

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        assert!(
            buffer_string.contains("Help · Directory Tree — Tab topics · j/k scroll · Esc back"),
            "Help topic-body header should show the topic title and operation hints"
        );
    }

    /// Content seam: top bar from a hand-built [`TopBarView`] (no full `App`).
    #[test]
    fn test_draw_top_bar_content_without_full_app() {
        let backend = TestBackend::new(80, 3);
        let mut terminal = Terminal::new(backend).unwrap();
        let view = TopBarView {
            view_mode: ViewMode::DirectoryTree,
            precise_mode: true,
            diff_show_full: false,
            diff_wrap: false,
            theme: Theme::DARK,
        };
        let area = Rect::new(0, 0, 80, 1);

        terminal
            .draw(|f| draw_top_bar_content(f, &view, area))
            .unwrap();

        let buffer_string = format!("{:?}", terminal.backend().buffer());
        assert!(
            buffer_string.contains("Directory Tree") && buffer_string.contains("Precise"),
            "top bar content should show precise tree title: {buffer_string}"
        );
        assert!(
            buffer_string.contains("Config") || buffer_string.contains("Help"),
            "top bar content should show Config/Help hints: {buffer_string}"
        );
    }

    /// Content seam: confirm dialog from a hand-built [`ConfirmView`] (no full `App`).
    #[test]
    fn test_draw_confirm_content_without_full_app() {
        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let view = ConfirmView {
            message: "Copy foo.txt to right side?",
            theme: Theme::DARK,
        };

        terminal
            .draw(|f| draw_confirm_content(f, &view, f.area()))
            .unwrap();

        let buffer_string = format!("{:?}", terminal.backend().buffer());
        assert!(
            buffer_string.contains("Confirm Action"),
            "confirm content should show title: {buffer_string}"
        );
        assert!(
            buffer_string.contains("Copy foo.txt to right side?"),
            "confirm content should show message: {buffer_string}"
        );
        assert!(
            buffer_string.contains("[Y]") && buffer_string.contains("[N]"),
            "confirm content should show y/n hints: {buffer_string}"
        );
    }

    /// Content seam: palette Menu from a hand-built [`PaletteView`] (no full `App`).
    #[test]
    fn test_draw_palette_content_without_full_app() {
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let items = vec![
            PaletteAction {
                key: "q".to_string(),
                label: "Quit".to_string(),
                action_id: PaletteActionId::Quit,
                enabled: true,
            },
            PaletteAction {
                key: "?".to_string(),
                label: "Help".to_string(),
                action_id: PaletteActionId::Help,
                enabled: true,
            },
        ];
        let view = PaletteView {
            mode: PaletteMode::Menu,
            items: &items,
            selected_idx: 0,
            query: "",
            theme: Theme::DARK,
        };

        terminal
            .draw(|f| draw_palette_content(f, &view, f.area()))
            .unwrap();

        let buffer_string = format!("{:?}", terminal.backend().buffer());
        assert!(
            buffer_string.contains("Menu"),
            "palette content should show Menu title: {buffer_string}"
        );
        assert!(
            buffer_string.contains("Quit") && buffer_string.contains("Help"),
            "palette content should list actions: {buffer_string}"
        );
    }

    /// Content seam: Help body from a hand-built [`HelpView`] only (no full `App`).
    #[test]
    fn test_draw_help_content_without_full_app() {
        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let method = crate::upgrade::InstallMethod::Standalone;
        let view = HelpView {
            topic: HelpTopic::DirectoryTree,
            index_open: false,
            index_sel: 0,
            scroll: 0,
            theme: Theme::DARK,
            update_available: None,
            install_method: &method,
        };
        let body_area = Rect::new(0, 1, 120, 17);

        terminal
            .draw(|f| draw_help_content(f, &view, body_area))
            .unwrap();

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        assert!(
            buffer_string.contains("Help · Directory Tree"),
            "help content should show topic title: {buffer_string}"
        );
        assert!(
            buffer_string.contains("j / Down"),
            "help content should list topic bindings: {buffer_string}"
        );
    }

    #[test]
    fn test_draw_help_topic_body_first_line_keeps_leading_indent() {
        // Regression test: `"\` line-continuation in a Rust string literal strips ALL
        // leading whitespace off the following line, not just the newline. Topics whose
        // first content line is an indented key entry (not a header like DirectoryTree's
        // "Navigation") must not lose that indentation relative to the rest of the block.
        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = App::new(PathBuf::from("/left"), PathBuf::from("/right"));
        app.set_view_mode(ViewMode::Help);
        app.help_mut().select_topic(crate::app::HelpTopic::FileDiff);

        draw_frame(&mut terminal, &mut app);

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        assert!(
            buffer_string.contains("  j / Down       scroll down one line"),
            "FileDiff topic's first content line should keep its 2-space indent, matching every other line in the block"
        );
    }

    #[test]
    fn test_draw_help_index_shows_all_six_topic_titles() {
        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = App::new(PathBuf::from("/left"), PathBuf::from("/right"));
        app.set_view_mode(ViewMode::Help);
        app.help_mut().set_index_open(true);

        draw_frame(&mut terminal, &mut app);

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        for title in crate::app::HelpTopic::all().iter().map(|t| t.title()) {
            assert!(
                buffer_string.contains(title),
                "Help index should list topic '{title}'"
            );
        }
    }

    #[test]
    fn test_draw_config_shows_flat_header_and_tools() {
        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = App::new(PathBuf::from("/left"), PathBuf::from("/right"));
        app.set_detected_diff_tools(vec![
            (crate::diff_tool::ExternalDiffTool::Vim, true),
            (crate::diff_tool::ExternalDiffTool::Code, false),
        ]);
        app.set_view_mode(ViewMode::ConfigMenu);

        draw_frame(&mut terminal, &mut app);

        let buffer_string = format!("{:?}", terminal.backend().buffer());
        assert!(
            buffer_string.contains("Configuration"),
            "Config screen title should be shown"
        );
        assert!(
            buffer_string.contains("External Diff Tool"),
            "Config header row should be shown inline"
        );
        assert!(
            buffer_string.contains("vim") && buffer_string.contains("code"),
            "Diff tool fields should render in the same list"
        );
        assert!(
            !buffer_string.contains("Configuration Categories"),
            "Old category menu should be removed"
        );
    }

    /// Content seam: Config list from a hand-built [`ConfigView`] (no full `App`).
    #[test]
    fn test_draw_config_content_without_full_app() {
        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let tools = vec![
            (crate::diff_tool::ExternalDiffTool::Vim, true),
            (crate::diff_tool::ExternalDiffTool::Code, false),
        ];
        let view = ConfigView {
            rows: vec![
                crate::app::ConfigRowKind::Header("External Diff Tool"),
                crate::app::ConfigRowKind::DiffTool(0),
                crate::app::ConfigRowKind::DiffTool(1),
                crate::app::ConfigRowKind::Header("Updates"),
                crate::app::ConfigRowKind::CheckUpdates,
            ],
            selected_idx: 1,
            detected_diff_tools: &tools,
            external_diff_tool: Some("vim"),
            check_updates: true,
            mouse: true,
            theme_choice: crate::theme::ThemeChoice::Dark,
            diff_context: 3,
            theme: Theme::DARK,
        };
        let body_area = Rect::new(0, 1, 120, 16);

        terminal
            .draw(|f| draw_config_content(f, &view, body_area))
            .unwrap();

        let buffer_string = format!("{:?}", terminal.backend().buffer());
        assert!(
            buffer_string.contains("Configuration"),
            "config content should show title: {buffer_string}"
        );
        assert!(
            buffer_string.contains("External Diff Tool"),
            "config content should show header: {buffer_string}"
        );
        assert!(
            buffer_string.contains("vim") && buffer_string.contains("code"),
            "config content should list tools: {buffer_string}"
        );
    }

    /// Content seam: dual panes + indicator from a hand-built [`TreeView`] only
    /// (no `App`, no top bar / footer). Part of #128 fixture-cost goal.
    #[test]
    fn test_draw_tree_content_without_full_app() {
        use crate::diff::FileInfo;
        use std::time::SystemTime;

        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).unwrap();

        let rows = vec![
            FlatRow {
                depth: 0,
                relative_path: PathBuf::from(""),
                name: "root".to_string(),
                state: DiffState::Identical,
                left: Some(FileInfo {
                    is_dir: true,
                    size: 0,
                    modified: SystemTime::UNIX_EPOCH,
                }),
                right: Some(FileInfo {
                    is_dir: true,
                    size: 0,
                    modified: SystemTime::UNIX_EPOCH,
                }),
            },
            FlatRow {
                depth: 1,
                relative_path: PathBuf::from("only-left.txt"),
                name: "only-left.txt".to_string(),
                state: DiffState::LeftOnly,
                left: Some(FileInfo {
                    is_dir: false,
                    size: 10,
                    modified: SystemTime::UNIX_EPOCH,
                }),
                right: None,
            },
        ];
        let left_root = PathBuf::from("/left");
        let right_root = PathBuf::from("/right");
        let view = TreeView {
            rows: &rows,
            scroll_offset: 0,
            selected_idx: 1,
            visible_height: 15,
            left_root: &left_root,
            right_root: &right_root,
            active_side_left: true,
            theme: Theme::DARK,
        };
        let layout = TreeLayout {
            top_bar: Rect::new(0, 0, 120, 1),
            left: Rect::new(0, 1, 55, 16),
            indicator: Rect::new(55, 1, 4, 16),
            right: Rect::new(59, 1, 61, 16),
            footer: Rect::new(0, 17, 120, 3),
        };

        terminal
            .draw(|f| draw_tree_content(f, &view, &layout))
            .unwrap();

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        assert!(
            buffer_string.contains("[1]") && buffer_string.contains("/left"),
            "tree content should show left pane path title: {buffer_string}"
        );
        assert!(
            buffer_string.contains("[2]") && buffer_string.contains("/right"),
            "tree content should show right pane path title: {buffer_string}"
        );
        assert!(
            buffer_string.contains("only-left.txt"),
            "tree content should list the LeftOnly row: {buffer_string}"
        );
    }

    #[test]
    fn test_draw_tree_footer_mentions_help_key() {
        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).unwrap();

        let rows: Vec<FlatRow> = Vec::new();
        let left_root = PathBuf::from("/left");
        let right_root = PathBuf::from("/right");
        let method = crate::upgrade::InstallMethod::Standalone;
        let filter_input = crate::text_input::TextInput::default();

        let inputs = TreeLayoutInputs {
            has_detail: false,
            has_status: false,
            has_filter: false,
            has_update: false,
        };
        let area = Rect::new(0, 0, 120, 20);
        let layout = tree_layout(&inputs, area);
        let top_bar_view = TopBarView {
            view_mode: ViewMode::DirectoryTree,
            precise_mode: false,
            diff_show_full: false,
            diff_wrap: false,
            theme: Theme::DARK,
        };
        let tree_view = TreeView {
            rows: &rows,
            scroll_offset: 0,
            selected_idx: 0,
            visible_height: layout.left.height.saturating_sub(2) as usize,
            left_root: &left_root,
            right_root: &right_root,
            active_side_left: true,
            theme: Theme::DARK,
        };
        let footer_view = TreeFooterView {
            row: None,
            status_toast: None,
            filter_active: false,
            filter_input: &filter_input,
            filter_pattern: "",
            filter_diffs_only: false,
            scan_in_progress: false,
            update_available: None,
            install_method: &method,
            theme: Theme::DARK,
        };

        terminal
            .draw(|f| {
                draw_top_bar_content(f, &top_bar_view, layout.top_bar);
                draw_tree_content(f, &tree_view, &layout);
                draw_tree_footer(f, &footer_view, &layout);
            })
            .unwrap();

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        assert!(
            buffer_string.contains("(?)Help"),
            "Top bar should hint at the ? Help key"
        );
        assert!(
            buffer_string.contains("[1]") && buffer_string.contains("[2]"),
            "Pane titles should show [1]/[2] focus shortcuts"
        );
        assert!(
            !buffer_string.contains("Left  ·") && !buffer_string.contains("Right  ·"),
            "Footer should not duplicate 1/2 pane focus hints"
        );
    }

    #[test]
    fn test_selected_row_detail_newer_left() {
        use crate::diff::FileInfo;
        use std::time::{Duration, SystemTime};

        let row = FlatRow {
            depth: 0,
            relative_path: PathBuf::from("file.txt"),
            name: "file.txt".to_string(),
            state: DiffState::DifferentNewerLeft,
            left: Some(FileInfo {
                is_dir: false,
                size: 2048,
                modified: SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000),
            }),
            right: Some(FileInfo {
                is_dir: false,
                size: 1024,
                modified: SystemTime::UNIX_EPOCH + Duration::from_secs(1_600_000_000),
            }),
        };

        let (left_detail, right_detail) = selected_row_detail(Some(&row)).unwrap();
        assert!(
            left_detail.contains("(newer)"),
            "Left side should contain '(newer)': {}",
            left_detail
        );
        assert!(
            !right_detail.contains("(newer)"),
            "Right side should not contain '(newer)': {}",
            right_detail
        );
        assert!(
            left_detail.contains("2.0 KB"),
            "Should show left size: {}",
            left_detail
        );
        assert!(
            right_detail.contains("1.0 KB"),
            "Should show right size: {}",
            right_detail
        );
    }

    #[test]
    fn test_selected_row_detail_identical_returns_none() {
        use crate::diff::FileInfo;
        use std::time::SystemTime;

        let row = FlatRow {
            depth: 0,
            relative_path: PathBuf::from("same.txt"),
            name: "same.txt".to_string(),
            state: DiffState::Identical,
            left: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
            right: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
        };

        assert!(selected_row_detail(Some(&row)).is_none());
    }

    #[test]
    fn test_format_size() {
        assert_eq!(format_size(0), "0 B");
        assert_eq!(format_size(512), "512 B");
        assert_eq!(format_size(1023), "1023 B");
        assert_eq!(format_size(1024), "1.0 KB");
        assert_eq!(format_size(1536), "1.5 KB");
        assert_eq!(format_size(1048576), "1.0 MB");
        assert_eq!(format_size(1073741824), "1.0 GB");
    }

    #[test]
    fn test_selected_row_detail_newer_right() {
        use crate::diff::FileInfo;
        use std::time::{Duration, SystemTime};

        let row = FlatRow {
            depth: 0,
            relative_path: PathBuf::from("file.txt"),
            name: "file.txt".to_string(),
            state: DiffState::DifferentNewerRight,
            left: Some(FileInfo {
                is_dir: false,
                size: 512,
                modified: SystemTime::UNIX_EPOCH + Duration::from_secs(1_600_000_000),
            }),
            right: Some(FileInfo {
                is_dir: false,
                size: 2048,
                modified: SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000),
            }),
        };

        let (left_detail, right_detail) = selected_row_detail(Some(&row)).unwrap();
        assert!(
            right_detail.contains("(newer)"),
            "Right side should contain '(newer)': {}",
            right_detail
        );
        assert!(
            !left_detail.contains("(newer)"),
            "Left side should not contain '(newer)': {}",
            left_detail
        );
        assert!(
            left_detail.contains("512 B"),
            "Should show left size: {}",
            left_detail
        );
        assert!(
            right_detail.contains("2.0 KB"),
            "Should show right size: {}",
            right_detail
        );
    }

    #[test]
    fn test_selected_row_detail_same_time() {
        use crate::diff::FileInfo;
        use std::time::{Duration, SystemTime};

        let mtime = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
        let row = FlatRow {
            depth: 0,
            relative_path: PathBuf::from("file.txt"),
            name: "file.txt".to_string(),
            state: DiffState::DifferentSameTime,
            left: Some(FileInfo {
                is_dir: false,
                size: 2048,
                modified: mtime,
            }),
            right: Some(FileInfo {
                is_dir: false,
                size: 1024,
                modified: mtime,
            }),
        };

        let (left_detail, right_detail) = selected_row_detail(Some(&row)).unwrap();
        assert!(
            !left_detail.contains("(newer)"),
            "Left side should not mark as newer: {}",
            left_detail
        );
        assert!(
            !right_detail.contains("(newer)"),
            "Right side should not mark as newer: {}",
            right_detail
        );
        assert!(left_detail.contains("2.0 KB"), "Should contain left size");
        assert!(right_detail.contains("1.0 KB"), "Should contain right size");
    }

    #[test]
    fn test_selected_row_detail_directory() {
        use crate::diff::FileInfo;
        use std::time::{Duration, SystemTime};

        let row = FlatRow {
            depth: 0,
            relative_path: PathBuf::from("subdir"),
            name: "subdir".to_string(),
            state: DiffState::DifferentNewerLeft,
            left: Some(FileInfo {
                is_dir: true,
                size: 0,
                modified: SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000),
            }),
            right: Some(FileInfo {
                is_dir: true,
                size: 0,
                modified: SystemTime::UNIX_EPOCH + Duration::from_secs(1_600_000_000),
            }),
        };

        let (left_detail, right_detail) = selected_row_detail(Some(&row)).unwrap();
        assert!(
            !left_detail.contains("KB") && !left_detail.contains("MB"),
            "Left detail should not show size: {}",
            left_detail
        );
        assert!(
            !right_detail.contains("KB") && !right_detail.contains("MB"),
            "Right detail should not show size: {}",
            right_detail
        );
        assert!(left_detail.contains("(newer)"), "Should mark left as newer");
        assert!(
            !right_detail.contains("(newer)"),
            "Should not mark right as newer"
        );
    }

    #[test]
    fn test_selected_row_detail_none_for_single_sided() {
        use crate::diff::FileInfo;
        use std::time::SystemTime;

        // LeftOnly should return None
        let row = FlatRow {
            depth: 0,
            relative_path: PathBuf::from("only_left.txt"),
            name: "only_left.txt".to_string(),
            state: DiffState::LeftOnly,
            left: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
            right: None,
        };
        assert!(selected_row_detail(Some(&row)).is_none());

        // RightOnly should return None
        let row = FlatRow {
            depth: 0,
            relative_path: PathBuf::from("only_right.txt"),
            name: "only_right.txt".to_string(),
            state: DiffState::RightOnly,
            left: None,
            right: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
        };
        assert!(selected_row_detail(Some(&row)).is_none());
    }

    #[test]
    fn test_selected_row_detail_none_for_missing_row() {
        assert!(selected_row_detail(None).is_none());
    }

    #[test]
    fn test_state_column_does_not_show_side_indicators() {
        // After the readability improvement, the State column should NOT contain
        // (L) or (R) side markers — that info moved to the footer detail line.
        // Content-only concern (the State/indicator column), no footer involved.
        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).unwrap();

        let rows: Vec<FlatRow> = Vec::new();
        let left_root = PathBuf::from("/left");
        let right_root = PathBuf::from("/right");
        let view = TreeView {
            rows: &rows,
            scroll_offset: 0,
            selected_idx: 0,
            visible_height: 17,
            left_root: &left_root,
            right_root: &right_root,
            active_side_left: true,
            theme: Theme::DARK,
        };
        let layout = TreeLayout {
            top_bar: Rect::new(0, 0, 120, 1),
            left: Rect::new(0, 1, 58, 18),
            indicator: Rect::new(58, 1, 4, 18),
            right: Rect::new(62, 1, 58, 18),
            footer: Rect::new(0, 19, 120, 1),
        };

        terminal
            .draw(|f| draw_tree_content(f, &view, &layout))
            .unwrap();

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        // The old "(L)" / "(R)" indicators should no longer appear in the State column
        assert!(
            !buffer_string.contains("(L)"),
            "State column should not contain '(L)' anymore"
        );
        assert!(
            !buffer_string.contains("(R)"),
            "State column should not contain '(R)' anymore"
        );
    }

    #[test]
    fn test_footer_detail_line_shown_for_different_file() {
        use crate::diff::FileInfo;
        use std::time::{Duration, SystemTime};

        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).unwrap();

        // A row with a difference so the detail line appears in the footer.
        let flat = FlatRow {
            depth: 0,
            relative_path: PathBuf::from("diff.txt"),
            name: "diff.txt".to_string(),
            state: DiffState::DifferentNewerLeft,
            left: Some(FileInfo {
                is_dir: false,
                size: 2048,
                modified: SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000),
            }),
            right: Some(FileInfo {
                is_dir: false,
                size: 1024,
                modified: SystemTime::UNIX_EPOCH + Duration::from_secs(1_600_000_000),
            }),
        };
        let method = crate::upgrade::InstallMethod::Standalone;
        let filter_input = crate::text_input::TextInput::default();

        let inputs = TreeLayoutInputs {
            has_detail: true,
            has_status: false,
            has_filter: false,
            has_update: false,
        };
        let layout = tree_layout(&inputs, Rect::new(0, 0, 120, 20));
        let view = TreeFooterView {
            row: Some(&flat),
            status_toast: None,
            filter_active: false,
            filter_input: &filter_input,
            filter_pattern: "",
            filter_diffs_only: false,
            scan_in_progress: false,
            update_available: None,
            install_method: &method,
            theme: Theme::DARK,
        };

        terminal
            .draw(|f| draw_tree_footer(f, &view, &layout))
            .unwrap();

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        assert!(
            buffer_string.contains("(newer)"),
            "Footer should show '(newer)' tag for the detail line: {}",
            buffer_string
        );
    }

    #[test]
    fn test_diff_view_shows_file_paths_and_identical_notice() {
        use crate::diff::FileInfo;
        use crate::diff_view::{DiffLine, DiffRow};
        use similar::ChangeTag;
        use std::time::SystemTime;

        let backend = TestBackend::new(120, 30);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = App::new(PathBuf::from("/left"), PathBuf::from("/right"));

        // Inject an identical file pair
        app.push_flat_row(FlatRow {
            depth: 0,
            relative_path: PathBuf::from("same.txt"),
            name: "same.txt".to_string(),
            state: DiffState::Identical,
            left: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
            right: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
        });
        app.apply_filter();
        app.set_selected_idx(0);
        app.set_view_mode(ViewMode::FileDiff);

        // diff rows with only Equal tags → files are identical
        app.diff_mut().set_rows(vec![DiffRow::from((
            Some(DiffLine {
                tag: ChangeTag::Equal,
                text: "hello".to_string(),
            }),
            Some(DiffLine {
                tag: ChangeTag::Equal,
                text: "hello".to_string(),
            }),
        ))]);

        draw_frame(&mut terminal, &mut app);

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);

        // Should show full paths for both sides in pane titles (OS-agnostic separators).
        let left_path = app.left_path().join("same.txt");
        let right_path = app.right_path().join("same.txt");
        assert!(
            buffer_string.contains(left_path.to_string_lossy().as_ref()),
            "Diff view should show left full path in title: {}",
            buffer_string
        );
        assert!(
            buffer_string.contains(right_path.to_string_lossy().as_ref()),
            "Diff view should show right full path in title: {}",
            buffer_string
        );
        // Should show the identical notice
        assert!(
            buffer_string.contains("identical"),
            "Diff view should show identical notice: {}",
            buffer_string
        );
        // Should show relative time in title
        assert!(
            buffer_string.contains("ago"),
            "Diff view title should show relative time: {}",
            buffer_string
        );
    }

    /// Content seam: paint info bar + panes from a hand-built [`DiffView`] only
    /// (no `App`, no top bar / footer). Guards the #128 fixture-cost goal.
    #[test]
    fn test_draw_diff_content_without_full_app() {
        use crate::diff::FileInfo;
        use crate::diff_view::{DiffLine, DiffRow};
        use similar::ChangeTag;
        use std::time::SystemTime;

        let backend = TestBackend::new(120, 28);
        let mut terminal = Terminal::new(backend).unwrap();

        let rows = vec![DiffRow::from((
            Some(DiffLine {
                tag: ChangeTag::Equal,
                text: "hello".to_string(),
            }),
            Some(DiffLine {
                tag: ChangeTag::Equal,
                text: "hello".to_string(),
            }),
        ))];
        let flat = FlatRow {
            depth: 0,
            relative_path: PathBuf::from("same.txt"),
            name: "same.txt".to_string(),
            state: DiffState::Identical,
            left: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
            right: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
        };
        let left_root = PathBuf::from("/left");
        let right_root = PathBuf::from("/right");
        let method = crate::upgrade::InstallMethod::Standalone;
        let view = DiffView {
            rows: &rows,
            wrap: false,
            scroll: 0,
            h_scroll: 0,
            visible_height: 20,
            content_width: 50,
            left_root: &left_root,
            right_root: &right_root,
            row: Some(&flat),
            left_hash: Some("aabbccdd11223344"),
            right_hash: Some("aabbccdd11223344"),
            left_line_ending: Some("LF"),
            right_line_ending: Some("LF"),
            theme: Theme::DARK,
            status_toast: None,
            has_changes: false,
            update_available: None,
            install_method: &method,
        };
        // Fixed geometry for a 120×28 content shell (notice + info + panes).
        let layout = DiffLayout {
            top_bar: Rect::new(0, 0, 120, 1),
            notice: Rect::new(0, 1, 120, 1),
            info_left: Rect::new(0, 2, 60, 1),
            info_right: Rect::new(60, 2, 60, 1),
            left: Rect::new(0, 3, 60, 22),
            right: Rect::new(60, 3, 60, 22),
            footer: Rect::new(0, 25, 120, 3),
            show_identical: true,
        };

        terminal
            .draw(|f| draw_diff_content(f, &view, &layout))
            .unwrap();

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        assert!(
            buffer_string.contains("identical"),
            "content-only draw should show identical notice: {buffer_string}"
        );
        assert!(
            buffer_string.contains("same.txt") || buffer_string.contains("/left"),
            "content-only draw should show pane path titles: {buffer_string}"
        );
        assert!(
            buffer_string.contains("aabbccdd11223344"),
            "content-only draw should show SHA256 on the info bar: {buffer_string}"
        );
    }

    #[test]
    fn test_diff_view_intraline_highlight_splits_replacement_line() {
        use crate::diff::FileInfo;
        use crate::diff_view::{DiffLine, DiffRow};
        use similar::ChangeTag;
        use std::time::SystemTime;

        let backend = TestBackend::new(120, 30);
        let mut terminal = Terminal::new(backend).unwrap();

        let rows = vec![DiffRow::from((
            Some(DiffLine {
                tag: ChangeTag::Delete,
                text: "let foo = 1;".to_string(),
            }),
            Some(DiffLine {
                tag: ChangeTag::Insert,
                text: "let bar = 1;".to_string(),
            }),
        ))];
        let flat = FlatRow {
            depth: 0,
            relative_path: PathBuf::from("file.rs"),
            name: "file.rs".to_string(),
            state: DiffState::DifferentNewerLeft,
            left: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
            right: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
        };
        let fixture = DiffViewFixture::new(rows, flat);

        let inputs = DiffLayoutInputs {
            has_changes: fixture.has_changes(),
            row_has_content: true,
            has_status: false,
            has_update: false,
        };
        let layout = diff_layout(&inputs, Rect::new(0, 0, 120, 30));
        let (visible_height, content_width) = diff_content_geometry(&layout);
        let view = fixture.view(false, 0, 0, visible_height, content_width);

        terminal
            .draw(|f| draw_diff_content(f, &view, &layout))
            .unwrap();

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        assert!(
            buffer_string.contains("foo") && buffer_string.contains("bar"),
            "Replacement line content should render: {buffer_string}"
        );
        assert!(
            buffer_string.contains("underline")
                || buffer_string.contains("Underlined")
                || buffer_string.contains("UNDERLINED"),
            "Changed spans should use underline styling: {buffer_string}"
        );
    }

    #[test]
    fn test_diff_view_no_identical_notice_when_files_differ() {
        use crate::diff::FileInfo;
        use crate::diff_view::{DiffLine, DiffRow};
        use similar::ChangeTag;
        use std::time::SystemTime;

        let backend = TestBackend::new(120, 30);
        let mut terminal = Terminal::new(backend).unwrap();

        // diff rows with a Delete tag → files differ
        let rows = vec![DiffRow::from((
            Some(DiffLine {
                tag: ChangeTag::Delete,
                text: "old line".to_string(),
            }),
            None,
        ))];
        let flat = FlatRow {
            depth: 0,
            relative_path: PathBuf::from("diff.txt"),
            name: "diff.txt".to_string(),
            state: DiffState::DifferentNewerLeft,
            left: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
            right: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
        };
        let fixture = DiffViewFixture::new(rows, flat);

        let inputs = DiffLayoutInputs {
            has_changes: fixture.has_changes(),
            row_has_content: true,
            has_status: false,
            has_update: false,
        };
        let layout = diff_layout(&inputs, Rect::new(0, 0, 120, 30));
        let (visible_height, content_width) = diff_content_geometry(&layout);
        let view = fixture.view(false, 0, 0, visible_height, content_width);

        terminal
            .draw(|f| draw_diff_content(f, &view, &layout))
            .unwrap();

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        assert!(
            !buffer_string.contains("identical"),
            "Diff view should NOT show identical notice when files differ: {}",
            buffer_string
        );
    }

    #[test]
    fn test_diff_view_shows_size_and_sha256_above_border() {
        use crate::diff::FileInfo;
        use crate::diff_view::{DiffLine, DiffRow};
        use similar::ChangeTag;
        use std::time::SystemTime;

        let backend = TestBackend::new(120, 30);
        let mut terminal = Terminal::new(backend).unwrap();

        let rows = vec![DiffRow::from((
            Some(DiffLine {
                tag: ChangeTag::Delete,
                text: "old".to_string(),
            }),
            None,
        ))];
        let flat = FlatRow {
            depth: 0,
            relative_path: PathBuf::from("file.txt"),
            name: "file.txt".to_string(),
            state: DiffState::DifferentNewerLeft,
            left: Some(FileInfo {
                is_dir: false,
                size: 2048,
                modified: SystemTime::UNIX_EPOCH,
            }),
            right: Some(FileInfo {
                is_dir: false,
                size: 1024,
                modified: SystemTime::UNIX_EPOCH,
            }),
        };
        let mut fixture = DiffViewFixture::new(rows, flat);
        fixture.left_hash = Some("aabbccdd11223344".to_string());
        fixture.right_hash = Some("eeff001122334455".to_string());

        let inputs = DiffLayoutInputs {
            has_changes: fixture.has_changes(),
            row_has_content: true,
            has_status: false,
            has_update: false,
        };
        let layout = diff_layout(&inputs, Rect::new(0, 0, 120, 30));
        let (visible_height, content_width) = diff_content_geometry(&layout);
        let view = fixture.view(false, 0, 0, visible_height, content_width);

        terminal
            .draw(|f| draw_diff_content(f, &view, &layout))
            .unwrap();

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        // Size info should appear above the pane borders in the info bar
        assert!(
            buffer_string.contains("2.0 KB"),
            "Diff view should show left size in info bar: {}",
            buffer_string
        );
        assert!(
            buffer_string.contains("1.0 KB"),
            "Diff view should show right size in info bar: {}",
            buffer_string
        );
        // SHA-256 hashes should be displayed
        assert!(
            buffer_string.contains("SHA256: aabbccdd11223344"),
            "Diff view should show left SHA-256 hash: {}",
            buffer_string
        );
        assert!(
            buffer_string.contains("SHA256: eeff001122334455"),
            "Diff view should show right SHA-256 hash: {}",
            buffer_string
        );
    }

    #[test]
    fn test_format_system_time_is_utc() {
        use std::time::{Duration, SystemTime};
        assert_eq!(
            format_system_time(&SystemTime::UNIX_EPOCH),
            "1970-01-01 00:00:00 UTC"
        );
        // 1970-01-01 01:02:03 UTC
        assert_eq!(
            format_system_time(&(SystemTime::UNIX_EPOCH + Duration::from_secs(3723))),
            "1970-01-01 01:02:03 UTC"
        );
        // 1970-01-02 00:00:00 UTC
        assert_eq!(
            format_system_time(&(SystemTime::UNIX_EPOCH + Duration::from_secs(86_400))),
            "1970-01-02 00:00:00 UTC"
        );
    }

    #[test]
    fn test_format_relative_time() {
        use std::time::{Duration, SystemTime};

        let now = SystemTime::now();
        assert_eq!(
            format_relative_time(&(now - Duration::from_secs(30))),
            "just now"
        );
        assert_eq!(
            format_relative_time(&(now - Duration::from_secs(300))),
            "5m ago"
        );
        assert_eq!(
            format_relative_time(&(now - Duration::from_secs(7200))),
            "2h ago"
        );
        assert_eq!(
            format_relative_time(&(now - Duration::from_secs(259_200))),
            "3d ago"
        );
    }

    #[test]
    fn test_build_diff_pane_title_truncates_long_path() {
        use std::time::SystemTime;
        let long_path =
            std::path::PathBuf::from("/very/long/path/that/exceeds/the/pane/width/file.txt");
        let title = build_diff_pane_title(&long_path, Some(&SystemTime::UNIX_EPOCH), 40);
        assert!(
            !title.contains("Left:") && !title.contains("Right:"),
            "Title should not contain a Left:/Right: prefix: {}",
            title
        );
        assert!(title.contains("ago"), "Title should contain relative time");
        // Long path should be truncated with "..."
        assert!(
            title.contains("..."),
            "Long path should be truncated: {}",
            title
        );
    }

    #[test]
    fn test_build_diff_pane_title_short_path() {
        use std::time::SystemTime;
        let short_path = std::path::PathBuf::from("/left/file.txt");
        let title = build_diff_pane_title(&short_path, Some(&SystemTime::UNIX_EPOCH), 80);
        assert!(
            title.contains("/left/file.txt"),
            "Short path should not be truncated: {}",
            title
        );
        assert!(
            !title.contains("Left:") && !title.contains("Right:"),
            "Title should not contain a Left:/Right: prefix: {}",
            title
        );
        assert!(
            title.contains("ago"),
            "Title should contain relative time: {}",
            title
        );
    }

    #[test]
    fn test_wrap_text_splits_long_lines() {
        let text = "abcdefghijklmnopqrstuvwxyz";
        let wrapped = wrap_text(text, 10);
        assert_eq!(wrapped, vec!["abcdefghij", "klmnopqrst", "uvwxyz"]);
    }

    #[test]
    fn test_wrap_text_preserves_short_lines() {
        let text = "hello";
        let wrapped = wrap_text(text, 10);
        assert_eq!(wrapped, vec!["hello"]);
    }

    #[test]
    fn test_wrap_text_empty_input() {
        let wrapped = wrap_text("", 10);
        assert_eq!(wrapped, vec![""]);
    }

    #[test]
    fn test_scrolled_text_basic() {
        assert_eq!(scrolled_text("hello world", 0, 5), "hello");
        assert_eq!(scrolled_text("hello world", 6, 5), "world");
        assert_eq!(scrolled_text("hello world", 20, 5), "");
    }

    #[test]
    fn test_diff_view_wrap_mode_increases_physical_rows() {
        use crate::diff::FileInfo;
        use crate::diff_view::{DiffLine, DiffRow};
        use similar::ChangeTag;
        use std::time::SystemTime;

        // Assertion is on `app.viewport()`, computed entirely by `App::sync_viewport`
        // (via `resync_diff_geometry`) — no rendering needed, so no `Terminal`/`draw`.
        let area = Rect::new(0, 0, 40, 30);
        let mut app = App::new(PathBuf::from("/left"), PathBuf::from("/right"));

        app.push_flat_row(FlatRow {
            depth: 0,
            relative_path: PathBuf::from("wide.txt"),
            name: "wide.txt".to_string(),
            state: DiffState::Identical,
            left: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
            right: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
        });
        app.apply_filter();
        app.set_selected_idx(0);
        app.set_view_mode(ViewMode::FileDiff);

        // One logical row with a long line (52 chars). At 40-column terminal,
        // content width is ~18, so wrapping should produce multiple physical rows.
        app.diff_mut().set_rows(vec![DiffRow::from((
            Some(DiffLine {
                tag: ChangeTag::Equal,
                text: "this is a very long line that exceeds the pane width".to_string(),
            }),
            Some(DiffLine {
                tag: ChangeTag::Equal,
                text: "this is a very long line that exceeds the pane width".to_string(),
            }),
        ))]);

        app.diff_mut().set_wrap(false);
        app.sync_viewport(area);
        let no_wrap_rows = app.viewport().diff_physical_rows;

        app.diff_mut().set_wrap(true);
        app.sync_viewport(area);
        let wrap_rows = app.viewport().diff_physical_rows;

        assert_eq!(
            no_wrap_rows, 1,
            "Without wrapping one logical row is one physical row"
        );
        assert!(
            wrap_rows > no_wrap_rows,
            "Wrapping should produce more physical rows: {} > {}",
            wrap_rows,
            no_wrap_rows
        );
    }

    #[test]
    fn test_diff_view_horizontal_scroll_offset() {
        use crate::diff::FileInfo;
        use crate::diff_view::{DiffLine, DiffRow};
        use similar::ChangeTag;
        use std::time::SystemTime;

        let backend = TestBackend::new(80, 30);
        let mut terminal = Terminal::new(backend).unwrap();

        // Longer than the 38-column pane, so an offset of 5 is a legal scroll
        // position rather than one `sync_viewport` would clamp away.
        let rows = vec![DiffRow::from((
            Some(DiffLine {
                tag: ChangeTag::Equal,
                text: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ".to_string(),
            }),
            Some(DiffLine {
                tag: ChangeTag::Equal,
                text: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ".to_string(),
            }),
        ))];
        let flat = FlatRow {
            depth: 0,
            relative_path: PathBuf::from("wide.txt"),
            name: "wide.txt".to_string(),
            state: DiffState::Identical,
            left: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
            right: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
        };
        let fixture = DiffViewFixture::new(rows, flat);

        // No changes (all Equal rows) → identical notice shown, same as `App` would compute.
        let inputs = DiffLayoutInputs {
            has_changes: fixture.has_changes(),
            row_has_content: true,
            has_status: false,
            has_update: false,
        };
        let layout = diff_layout(&inputs, Rect::new(0, 0, 80, 30));
        let (visible_height, content_width) = diff_content_geometry(&layout);
        let view = fixture.view(false, 0, 5, visible_height, content_width);

        terminal
            .draw(|f| draw_diff_content(f, &view, &layout))
            .unwrap();

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        assert!(
            buffer_string.contains("56789abcdefghijklmno"),
            "Horizontally scrolled content should start after the offset: {}",
            buffer_string
        );
        assert!(
            !buffer_string.contains("01234"),
            "Content before the horizontal scroll offset should not be visible: {}",
            buffer_string
        );
    }

    #[test]
    fn test_diff_line_highlight_priority() {
        assert_eq!(
            diff_line_highlight(true, true, true),
            DiffLineHighlight::Cursor
        );
        assert_eq!(
            diff_line_highlight(true, true, false),
            DiffLineHighlight::ActiveHunk
        );
        assert_eq!(
            diff_line_highlight(true, false, false),
            DiffLineHighlight::ChangeHunk
        );
        assert_eq!(
            diff_line_highlight(false, false, false),
            DiffLineHighlight::None
        );
    }

    #[test]
    fn test_diff_view_highlights_mergeable_blocks_and_cursor() {
        use crate::diff::FileInfo;
        use crate::diff_view::{DiffLine, DiffRow};
        use similar::ChangeTag;
        use std::time::SystemTime;

        let backend = TestBackend::new(120, 30);
        let mut terminal = Terminal::new(backend).unwrap();

        let rows = vec![
            DiffRow::from((
                Some(DiffLine {
                    tag: ChangeTag::Equal,
                    text: "context".to_string(),
                }),
                Some(DiffLine {
                    tag: ChangeTag::Equal,
                    text: "context".to_string(),
                }),
            )),
            DiffRow::from((
                Some(DiffLine {
                    tag: ChangeTag::Delete,
                    text: "old-line".to_string(),
                }),
                Some(DiffLine {
                    tag: ChangeTag::Insert,
                    text: "new-line".to_string(),
                }),
            )),
            DiffRow::from((
                Some(DiffLine {
                    tag: ChangeTag::Equal,
                    text: "tail".to_string(),
                }),
                Some(DiffLine {
                    tag: ChangeTag::Equal,
                    text: "tail".to_string(),
                }),
            )),
        ];
        let flat = FlatRow {
            depth: 0,
            relative_path: PathBuf::from("diff.txt"),
            name: "diff.txt".to_string(),
            state: DiffState::DifferentNewerLeft,
            left: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
            right: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
        };
        let fixture = DiffViewFixture::new(rows, flat);

        let inputs = DiffLayoutInputs {
            has_changes: fixture.has_changes(),
            row_has_content: true,
            has_status: false,
            has_update: false,
        };
        let layout = diff_layout(&inputs, Rect::new(0, 0, 120, 30));
        let (visible_height, content_width) = diff_content_geometry(&layout);
        // Cursor on context line (scroll: 0); the nearest change hunk row should
        // still be emphasized.
        let view = fixture.view(false, 0, 0, visible_height, content_width);

        terminal
            .draw(|f| draw_diff_content(f, &view, &layout))
            .unwrap();

        let buffer_string = format!("{:?}", terminal.backend().buffer());
        assert!(
            buffer_string.contains("Rgb(48, 48, 88)"),
            "Active mergeable hunk should use emphasized background: {}",
            buffer_string
        );
        assert!(
            buffer_string.contains("Rgb(64, 64, 64)"),
            "Cursor line should use distinct background: {}",
            buffer_string
        );
    }

    #[test]
    fn test_light_theme_changes_diff_hunk_background() {
        use crate::diff::FileInfo;
        use crate::diff_view::{DiffLine, DiffRow};
        use similar::ChangeTag;
        use std::time::SystemTime;

        let backend = TestBackend::new(120, 30);
        let mut terminal = Terminal::new(backend).unwrap();

        let rows = vec![
            DiffRow::from((
                Some(DiffLine {
                    tag: ChangeTag::Equal,
                    text: "context".to_string(),
                }),
                Some(DiffLine {
                    tag: ChangeTag::Equal,
                    text: "context".to_string(),
                }),
            )),
            DiffRow::from((
                Some(DiffLine {
                    tag: ChangeTag::Delete,
                    text: "old-line".to_string(),
                }),
                Some(DiffLine {
                    tag: ChangeTag::Insert,
                    text: "new-line".to_string(),
                }),
            )),
            DiffRow::from((
                Some(DiffLine {
                    tag: ChangeTag::Equal,
                    text: "tail".to_string(),
                }),
                Some(DiffLine {
                    tag: ChangeTag::Equal,
                    text: "tail".to_string(),
                }),
            )),
        ];
        let flat = FlatRow {
            depth: 0,
            relative_path: PathBuf::from("diff.txt"),
            name: "diff.txt".to_string(),
            state: DiffState::DifferentNewerLeft,
            left: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
            right: Some(FileInfo {
                is_dir: false,
                size: 100,
                modified: SystemTime::UNIX_EPOCH,
            }),
        };
        let mut fixture = DiffViewFixture::new(rows, flat);
        fixture.theme = Theme::LIGHT;

        let inputs = DiffLayoutInputs {
            has_changes: fixture.has_changes(),
            row_has_content: true,
            has_status: false,
            has_update: false,
        };
        let layout = diff_layout(&inputs, Rect::new(0, 0, 120, 30));
        let (visible_height, content_width) = diff_content_geometry(&layout);
        // Cursor on context line (scroll: 0), same as the dark-theme equivalent test,
        // so the nearest change hunk (not the cursor row) is the one under assertion.
        let view = fixture.view(false, 0, 0, visible_height, content_width);

        terminal
            .draw(|f| draw_diff_content(f, &view, &layout))
            .unwrap();

        let buffer_string = format!("{:?}", terminal.backend().buffer());
        assert!(
            buffer_string.contains("Rgb(205, 205, 240)"),
            "Light theme should use its own active-hunk background, not the dark default: {}",
            buffer_string
        );
        assert!(
            !buffer_string.contains("Rgb(48, 48, 88)"),
            "Light theme must not fall back to the dark-theme active-hunk background: {}",
            buffer_string
        );
    }

    #[test]
    fn test_light_theme_changes_top_bar_title_colour() {
        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = App::new(PathBuf::from("/left"), PathBuf::from("/right"));
        app.set_theme(crate::theme::ThemeChoice::Light);

        draw_frame(&mut terminal, &mut app);

        let light_buffer_string = format!("{:?}", terminal.backend().buffer());
        assert!(
            light_buffer_string.contains("Black"),
            "Light theme top-bar title should use a dark (Black) foreground: {}",
            light_buffer_string
        );

        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = App::new(PathBuf::from("/left"), PathBuf::from("/right"));
        // Set explicitly rather than relying on the loaded default: other tests in this
        // binary persist `settings.theme` to the real config file, and `App::new` reloads
        // from disk, so a bare default here would be flaky under parallel test execution.
        app.set_theme(crate::theme::ThemeChoice::Dark);
        draw_frame(&mut terminal, &mut app);
        let dark_buffer_string = format!("{:?}", terminal.backend().buffer());
        assert!(
            !dark_buffer_string.contains("Black"),
            "Dark theme top-bar title should not use Black: {}",
            dark_buffer_string
        );
    }

    #[test]
    fn test_light_theme_paints_full_canvas_background() {
        // Regression guard: `draw()` must paint the whole frame with the theme's canvas
        // background before drawing any view, otherwise cells left unpainted by inner
        // widgets (e.g. gaps between panes) keep the terminal's native colour instead of
        // showing the theme's chosen background (Issue: Light theme background stayed
        // terminal-native because nothing called `Theme::base_style()`).
        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = App::new(PathBuf::from("/left"), PathBuf::from("/right"));
        app.set_theme(crate::theme::ThemeChoice::Light);
        draw_frame(&mut terminal, &mut app);
        let light_buffer_string = format!("{:?}", terminal.backend().buffer());
        assert!(
            light_buffer_string.contains("bg: White"),
            "Light theme should paint the canvas background White: {}",
            light_buffer_string
        );

        let backend = TestBackend::new(120, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        let mut app = App::new(PathBuf::from("/left"), PathBuf::from("/right"));
        app.set_theme(crate::theme::ThemeChoice::Dark);
        draw_frame(&mut terminal, &mut app);
        let dark_buffer_string = format!("{:?}", terminal.backend().buffer());
        assert!(
            !dark_buffer_string.contains("bg: White"),
            "Dark theme should not paint the canvas background White: {}",
            dark_buffer_string
        );
    }

    #[test]
    fn test_diff_view_header_shows_wrap_state() {
        // "Wrap" is painted by the shared top bar (`TopBarView`/`draw_top_bar_content`),
        // not the diff content/footer — no `App` or `DiffView` needed for this one.
        let backend = TestBackend::new(80, 1);
        let mut terminal = Terminal::new(backend).unwrap();
        let view = TopBarView {
            view_mode: ViewMode::FileDiff,
            precise_mode: false,
            diff_show_full: false,
            diff_wrap: true,
            theme: Theme::DARK,
        };
        let area = Rect::new(0, 0, 80, 1);

        terminal
            .draw(|f| draw_top_bar_content(f, &view, area))
            .unwrap();

        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        assert!(
            buffer_string.contains("Wrap"),
            "Header should show Wrap state: {}",
            buffer_string
        );
    }

    #[test]
    fn test_draw_close_button() {
        let backend = TestBackend::new(20, 3);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| {
                let area = f.area();
                draw_close_button(f, area);
            })
            .unwrap();
        let buffer = terminal.backend().buffer();
        let buffer_string = format!("{:?}", buffer);
        assert!(
            buffer_string.contains("[x]"),
            "Buffer should contain close button [x]"
        );
    }
}