tix-tracker 0.6.0

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

use crate::config::BoardConfiguration;
use crate::model::{Issue, Priority};
use crate::search::{Corpus, StructuredFilter};
use crate::storage::Store;

use super::widgets;

#[derive(Debug, Clone)]
struct GroupSection {
    name: String,
    start: usize,
    end: usize,
    done: usize,
    total: usize,
}

#[derive(Debug, Clone)]
pub struct Card {
    pub number: u32,
    pub title: String,
    pub priority: Priority,
    pub labels: Vec<String>,
    pub assignee: Option<String>,
    pub filename: String,
    pub commit: Option<String>,
    pub created: String,
    pub due_date: Option<String>,
    pub status: String,
    /// The issue's resolved category label, from the service's own `label()`
    /// (WP05 T022, FR-004).
    ///
    /// `Some` for a column the board configures, `None` for one it does not — a
    /// configuration error the user should be able to *see*, rather than a
    /// transition-policy default silently applied to a display. The renderer shows
    /// `(unmapped)` for `None`.
    ///
    /// **The label carries the meaning, not the color.** A board or terminal with no
    /// color must still convey the category, so the label is always rendered and the
    /// `color_hint` only ever tints it (T022 step 3, research R6).
    pub category: Option<String>,
    /// The category's color hint, for tinting. Advisory only: dropping it changes
    /// the display's color and nothing else.
    pub category_color: Option<crate::workflow::ColorHint>,
    /// Whether the service considers this issue **complete** (WP05, C-004).
    ///
    /// Was `issue.status.is(done_column)` — a column-*name* comparison. On a board
    /// whose `category_map` puts `completed` somewhere other than its `done_column`
    /// that is a different question from the one the service answers, and this flag
    /// drives the card's completion styling and the group's rollup.
    pub done: bool,
    pub cycle: Option<String>,
    pub milestone: Option<String>,
    /// The issue's blocked reason, from the relationship service, or `None`.
    ///
    /// Derived, never stored (data-model §4, C-003): recomputed from the graph
    /// on every board build, so a card cannot show a stale blocked state after
    /// its blocker moved.
    pub blocked: Option<String>,
    /// The issue's hierarchy marker: `3` for three children, `3 1/3` when one is
    /// complete, or `None` for a leaf.
    ///
    /// `None` for a leaf rather than `Some("0")`, so a card cannot show a child
    /// count for an issue that is not a parent. Built from the service's
    /// [`crate::commands::parent::HierarchyFacts`] on every board build, so it
    /// cannot go stale when a child is created or moved — the same discipline
    /// `blocked` follows.
    pub children: Option<String>,
    /// The issue's decomposition parent, when it has one (tix #1399).
    ///
    /// Carried on the card rather than looked up at render time, so the board can
    /// place a sub-issue beneath its parent without a second pass over the issues.
    pub parent: Option<u32>,
    /// How deeply the card is nested in the board's tree rendering (tix #1399).
    ///
    /// `0` for a top-level card, `1` for a sub-issue shown directly under its
    /// parent. Never above `1`: only one level is rendered, so a grandchild stays
    /// at `0` and is drawn as a normal top-level card.
    pub depth: u8,
    /// Whether this issue is **archived** — its file is dot-prefixed (issue #1492).
    ///
    /// A card only ever carries `true` on a board built with archived issues
    /// included (the TUI's archive toggle); the default board is enumerated from
    /// the active set and never sees one. Rendered as the `[archived]` token, in the
    /// same bracketed language as `[~]` and `[N]`.
    pub archived: bool,
    /// How many `related_issues` entries the issue carries (tix #1513).
    ///
    /// A plain count, computed from the issue set the board was built over, so the
    /// card cannot go stale when the field is edited — the same discipline `blocked`
    /// and `children` follow. `0` means no marker at all, which keeps a column of
    /// cards scannable.
    pub related: usize,
}

impl crate::config::OrderBy {
    /// Sort cards in place per the board's `order_by` setting. `none` is a
    /// no-op. `sort_by` is stable, so equal creation dates keep the
    /// underlying store order (relative filename ascending) — deterministic
    /// ties with no extra key. Dates are zero-padded `YYYY-MM-DD`, so
    /// lexicographic comparison is chronological.
    pub fn sort(&self, cards: &mut [Card]) {
        match self {
            crate::config::OrderBy::CreatedAtDesc => {
                cards.sort_by(|a, b| b.created.cmp(&a.created))
            }
            crate::config::OrderBy::CreatedAtAsc => cards.sort_by(|a, b| a.created.cmp(&b.created)),
            crate::config::OrderBy::None => {}
        }
    }
}

fn sort_by_default_order(board_config: &BoardConfiguration, cards: &mut [Card]) {
    match board_config.order_by {
        crate::config::OrderBy::CreatedAtDesc => {
            cards.sort_by(|a, b| {
                b.created
                    .cmp(&a.created)
                    .then_with(|| a.filename.cmp(&b.filename))
            });
        }
        crate::config::OrderBy::CreatedAtAsc => {
            cards.sort_by(|a, b| {
                a.created
                    .cmp(&b.created)
                    .then_with(|| a.filename.cmp(&b.filename))
            });
        }
        crate::config::OrderBy::None => {
            cards.sort_by(|a, b| a.filename.cmp(&b.filename));
        }
    }
}

fn sort_cards(board_config: &BoardConfiguration, cards: &mut [Card]) {
    if board_config.card_order.is_empty() {
        sort_by_default_order(board_config, cards);
        return;
    }

    let mut baseline = cards.to_vec();
    sort_by_default_order(board_config, &mut baseline);

    let manual_cards: Vec<Card> = board_config
        .card_order
        .iter()
        .filter_map(|filename| {
            baseline
                .iter()
                .find(|card| card.filename == *filename)
                .cloned()
        })
        .collect();
    let touched: HashSet<String> = manual_cards
        .iter()
        .map(|card| card.filename.clone())
        .collect();
    let mut manual_iter = manual_cards.into_iter();
    let mut ordered = Vec::with_capacity(baseline.len());

    for card in baseline {
        if touched.contains(card.filename.as_str()) {
            if let Some(manual_card) = manual_iter.next() {
                ordered.push(manual_card);
            } else {
                ordered.push(card);
            }
        } else {
            ordered.push(card);
        }
    }

    cards.clone_from_slice(&ordered);
}

/// Reorder one column so each card's sub-issues sit **immediately after it**,
/// marking them `depth = 1` (tix #1399).
///
/// Only **one** level is ever nested. A card is placed under its parent only when
/// that parent is itself a *top-level* card of this column — meaning the parent has
/// no parent of its own present here. A grandchild (a card whose parent is itself a
/// sub-issue) therefore stays `depth = 0` in its normal position rather than
/// stacking under the child, so the tree cannot grow past one indent.
///
/// The ordering is settled **here, at build time**, not in the renderer: the
/// selection index and the pointer hit-test both address cards by their index in
/// the column, so a reorder only the renderer knew about would make a click or a
/// `j` land on the wrong card.
///
/// Every card is emitted exactly once: a nested card is dropped from the top-level
/// sequence and re-emitted under its parent, and nothing else moves.
fn nest_children(cards: &mut Vec<Card>) {
    let count = cards.len();
    if count == 0 {
        return;
    }
    let position: std::collections::HashMap<u32, usize> = cards
        .iter()
        .enumerate()
        .map(|(i, card)| (card.number, i))
        .collect();
    // A card is a root of *this* column when it has no parent here: no parent at
    // all, or a parent living in another column.
    let is_root = |index: usize| match cards[index].parent {
        None => true,
        Some(parent) => !position.contains_key(&parent),
    };

    let mut adopted: Vec<Vec<usize>> = vec![Vec::new(); count];
    let mut top_level: Vec<usize> = Vec::with_capacity(count);
    for (index, card) in cards.iter().enumerate() {
        match card
            .parent
            .and_then(|parent| position.get(&parent).copied())
        {
            Some(parent) if is_root(parent) => adopted[parent].push(index),
            _ => top_level.push(index),
        }
    }

    let mut ordered: Vec<Card> = Vec::with_capacity(count);
    for index in top_level {
        let mut card = cards[index].clone();
        card.depth = 0;
        ordered.push(card);
        for &child in &adopted[index] {
            let mut child_card = cards[child].clone();
            child_card.depth = 1;
            ordered.push(child_card);
        }
    }
    *cards = ordered;
}

pub(crate) fn sparse_card_order(board_config: &BoardConfiguration, cards: &[Card]) -> Vec<String> {
    let mut baseline = cards.to_vec();
    sort_by_default_order(board_config, &mut baseline);
    baseline
        .iter()
        .zip(cards.iter())
        .filter(|(baseline_card, current_card)| baseline_card.filename != current_card.filename)
        .map(|(_, current_card)| current_card.filename.clone())
        .collect()
}

#[derive(Debug, Clone)]
pub struct BoardColumn {
    pub name: String,
    pub cards: Vec<Card>,
}

/// What a pointer position over the board resolves to (D3). `row` is the
/// card's index inside its column — the same index [`BoardState::selected`]
/// uses — so the caller can compare it directly against the selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HitTarget {
    Card { col: usize, row: usize },
    Column { col: usize },
}

#[derive(Debug, Clone)]
pub struct BoardState {
    /// Visible columns only — configured columns not listed in the active
    /// board's `hidden_columns`, in declaration order (FR-002/FR-003). Hidden
    /// columns live in [`BoardState::hidden`].
    pub columns: Vec<BoardColumn>,
    /// Columns hidden from the active board configuration. Their cards stay
    /// in board state (keyed by column name) and remain reachable via
    /// filters/search (DM-01M2MHJB884WCTVCDHPD2T3GE7); they never render.
    pub hidden: Vec<BoardColumn>,
    pub mismatch: BoardColumn,
    /// Whether the computed "Mismatched" pseudo-column is part of the
    /// navigation/render surface (C-002 / FR-003). Cards in unknown statuses
    /// are always collected into [`BoardState::mismatch`]; the column is only
    /// shown when the effective configuration sets `show_mismatch`.
    pub show_mismatch: bool,
    pub active_col: usize,
    pub selected: usize,
    /// The `(col, card index)` the pointer is hovering (D8), set by `Moved`
    /// events and cleared on `Up` / when the pointer leaves the board.
    /// Rendered as a highlight only — it never changes the selection.
    pub hover: Option<(usize, usize)>,
    /// The column the pointer is over, set for **any** position inside a column —
    /// including empty space below the last card, where `hover` is `None`. The
    /// renderer marks the hovered column from this, so an empty column lights up
    /// too. Cleared with `hover`.
    pub hover_col: Option<usize>,
    pub filter: Option<String>,
}

/// Shorten `msg` to at most `budget` **display cells**, appending an ellipsis
/// when anything was dropped.
///
/// The marker is appended *within* the budget rather than after it, so the result
/// is never wider than the area it is rendered into. A combining mark or a
/// zero-width control contributes no width, so it is kept without consuming
/// budget rather than being dropped.
pub fn truncate_to_cells(msg: &str, budget: usize) -> String {
    use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

    const ELLIPSIS: char = '\u{2026}';
    if budget == 0 {
        return String::new();
    }
    if UnicodeWidthStr::width(msg) <= budget {
        return msg.to_string();
    }

    // Reserve one cell for the marker. A double-width character cannot fit in
    // the last cell, so the loop stops on a width overflow rather than on a
    // character count.
    let marker_width = UnicodeWidthChar::width(ELLIPSIS).unwrap_or(1);
    let mut out = String::new();
    let mut used = 0usize;
    for ch in msg.chars() {
        let w = UnicodeWidthChar::width(ch).unwrap_or(0);
        if used + w + marker_width > budget {
            break;
        }
        out.push(ch);
        used += w;
    }
    out.push(ELLIPSIS);
    out
}

/// The blocked reason for every issue, read from the relationship service.
///
/// One graph over the **whole** set, so the answer does not depend on which
/// issues the board happens to be showing (see [`BoardState::blocked`]).
fn blocked_reasons(
    issues: &[crate::model::Issue],
    done_column: &str,
) -> std::collections::BTreeMap<u32, String> {
    let views: Vec<crate::relationships::IssueView<'_>> =
        issues.iter().map(crate::model::Issue::issue_view).collect();
    let graph = crate::relationships::RelationshipGraph::new(&views, done_column);
    issues
        .iter()
        .filter_map(|issue| {
            crate::commands::blocked_note(&graph.blocked_state(issue.number))
                .map(|note| (issue.number, note))
        })
        .collect()
}

/// The child-count marker for every issue that has children, keyed by number.
///
/// One index over the whole set, so the marker does not depend on which issues the
/// board is showing. The text comes from the shared `HierarchyFacts`, which is what
/// `tix parent show`, `tix show` and `tix list --show progress` read, so the four
/// surfaces cannot report different figures.
fn child_markers(
    issues: &[crate::model::Issue],
    done_column: &str,
) -> std::collections::BTreeMap<u32, String> {
    let views: Vec<crate::relationships::IssueView<'_>> =
        issues.iter().map(crate::model::Issue::issue_view).collect();
    let index = crate::hierarchy::HierarchyIndex::build(&views);
    issues
        .iter()
        .filter_map(|issue| {
            let facts =
                crate::commands::parent::facts_for(&index, issues, issue.number, done_column);
            facts.has_children().then(|| {
                (
                    issue.number,
                    format!(
                        "{} {}/{}",
                        facts.rollup.direct_children,
                        facts.rollup.completed_children,
                        facts.rollup.progress.total
                    ),
                )
            })
        })
        .collect()
}

impl BoardState {
    /// WP05: the resolution must be for the board this call is building, not for
    /// whichever board happens to be `default`.
    ///
    /// `board_config` can be any of the configured boards, and a board selected in
    /// the TUI is not necessarily the default one. Resolving against the default
    /// would give a card on the `staging` board the categories configured for
    /// `default` — a wrong answer rather than a missing one, which is worse.
    ///
    /// The board is identified by **pointer identity** against the config's boards,
    /// because `build` receives a `&BoardConfiguration` and not a name. That is exact
    /// and needs no name plumbing; a board not found in the config falls back to its
    /// own columns with the global vocabulary, which is the honest reading of a
    /// configuration `tix` did not load.
    /// Public so the startup path can build a board from a single shared
    /// enumeration (tix #1518) instead of each caller re-deriving it.
    pub fn resolution_for(
        store: &Store,
        board_config: &BoardConfiguration,
    ) -> crate::workflow::CategoryResolution {
        let name = store
            .config
            .configs()
            .find(|(_, board)| std::ptr::eq(*board, board_config))
            .map(|(name, _)| name)
            .unwrap_or("default");
        crate::workflow::resolution(&store.config, board_config, name)
    }

    pub fn build(store: &Store, board_config: &BoardConfiguration) -> Self {
        Self::build_with(store, board_config, false, false)
    }

    /// [`BoardState::build`], optionally including **archived** issues (issue #1492).
    ///
    /// `include_archived == false` is the default and the fast path: enumeration reads
    /// [`Store::list`], which drops a dot-prefixed filename from the directory entry
    /// without opening the file. `true` reads [`Store::list_all`], which is what the
    /// TUI's archive toggle asks for *on demand* — the point being that a repository
    /// with thousands of archived issues is never walked for a board that does not
    /// show them.
    pub fn build_with_archived(
        store: &Store,
        board_config: &BoardConfiguration,
        include_archived: bool,
    ) -> Self {
        Self::build_with(store, board_config, include_archived, false)
    }

    /// [`BoardState::build_with_archived`], optionally rendering sub-issues under
    /// their parents (tix #1399).
    ///
    /// `show_children == true` reorders every column so a card's direct sub-issues
    /// follow it, marked `depth = 1` (see [`nest_children`]). The reorder happens at
    /// **build** time, not at draw time, because the selection index and the pointer
    /// hit-test both address cards by their index inside a column — a tree only the
    /// renderer knew about would make a click or a `j` land on the wrong card.
    pub fn build_with(
        store: &Store,
        board_config: &BoardConfiguration,
        include_archived: bool,
        show_children: bool,
    ) -> Self {
        let issues = if include_archived {
            store.list_all()
        } else {
            store.list()
        }
        .unwrap_or_default();
        let resolution = Self::resolution_for(store, board_config);
        Self::build_from_issues(
            &issues,
            board_config,
            &store.config,
            &resolution,
            show_children,
        )
    }

    /// Build a board from an in-memory slice of issues (issue #10 follow-up).
    ///
    /// The single build path: [`BoardState::build_with`] reads the store and
    /// delegates here, and the TUI's incremental refresh rebuilds from its
    /// in-memory corpus without re-reading the tree. `config` supplies the
    /// completion column; `resolution` is the category resolution of the board
    /// being built (see [`BoardState::resolution_for`]).
    pub fn build_from_issues(
        issues: &[Issue],
        board_config: &BoardConfiguration,
        config: &crate::config::Config,
        resolution: &crate::workflow::CategoryResolution,
        show_children: bool,
    ) -> Self {
        // WP09: the **service's** completion column, not `done_column`. The
        // `blocked_reasons` and `child_markers` helpers take a column *name* — that is
        // their existing signature and it is not what makes them wrong. What was
        // wrong is which name they were handed: on a board whose `category_map` puts
        // `completed` on `shipped` while `done_column` is `done`, the TUI's blocked
        // marker was computed against `done_column` while `tix list`'s was computed
        // against the service, so the same issue read as blocked in the TUI and clear
        // in the CLI. The name is now resolved once, by the service.
        let done_column = crate::workflow::completion_column_or_default(board_config, config);
        let done_column = done_column.as_str();
        let blocked = blocked_reasons(issues, done_column);
        let children = child_markers(issues, done_column);
        let show_mismatch = board_config.show_mismatch;
        let hidden_names: Vec<&str> = board_config
            .hidden_columns
            .iter()
            .map(String::as_str)
            .collect();
        let mut column_map: Vec<Vec<Card>> =
            board_config.columns.iter().map(|_| Vec::new()).collect();
        let mut mismatch_cards = Vec::new();

        for issue in issues {
            let card = Card {
                number: issue.number,
                title: issue.title.clone(),
                priority: issue.priority.clone(),
                labels: issue.labels.clone(),
                assignee: issue.assignee.clone(),
                filename: issue.filename.clone(),
                commit: issue.commit.clone(),
                created: issue.created.clone(),
                due_date: issue.due_date.clone(),
                status: issue.status.display().to_string(),
                category: crate::workflow::category_of(issue, resolution)
                    .map(|c| c.label().to_string()),
                category_color: crate::workflow::category_of(issue, resolution)
                    .and_then(|c| c.color_hint()),
                done: crate::workflow::is_completed(issue, resolution),
                cycle: issue.cycles.as_ref().and_then(|v| v.first().cloned()),
                milestone: issue.milestones.as_ref().and_then(|v| v.first().cloned()),
                blocked: blocked.get(&issue.number).cloned(),
                children: children.get(&issue.number).cloned(),
                parent: issue.parent,
                depth: 0,
                archived: issue.archived,
                related: issue.related_issues.len(),
            };
            if let Some(idx) = board_config
                .columns
                .iter()
                .position(|c| c == issue.status.display())
            {
                column_map[idx].push(card);
            } else {
                mismatch_cards.push(card);
            }
        }

        for cards in column_map.iter_mut() {
            sort_cards(board_config, cards);
        }
        sort_cards(board_config, &mut mismatch_cards);

        let mut columns: Vec<BoardColumn> = Vec::new();
        let mut hidden: Vec<BoardColumn> = Vec::new();
        for (cards, name) in column_map.into_iter().zip(board_config.columns.iter()) {
            let col = BoardColumn {
                name: name.clone(),
                cards,
            };
            if hidden_names.contains(&name.as_str()) {
                hidden.push(col);
            } else {
                columns.push(col);
            }
        }

        let mismatch = BoardColumn {
            name: "Mismatched".to_string(),
            cards: mismatch_cards,
        };

        let mut state = BoardState {
            columns,
            hidden,
            mismatch,
            show_mismatch,
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
        };
        state.apply_child_order(show_children);
        state
    }

    /// Nest each column's sub-issues beneath their parents when `show_children` is
    /// on (tix #1399). A no-op when it is off, so the default build is untouched.
    ///
    /// Applied to the visible columns and the "Mismatched" pseudo-column — every
    /// surface `render` and `hit_test` actually address. Hidden columns have no
    /// rendered presence, so they are left in their flat order.
    fn apply_child_order(&mut self, show_children: bool) {
        if !show_children {
            return;
        }
        for column in &mut self.columns {
            nest_children(&mut column.cards);
        }
        nest_children(&mut self.mismatch.cards);
    }

    /// Build a board from the search corpus, keeping only cards whose full
    /// serialized text matches **both** the fuzzy `query` layer and the
    /// structured `filter` layer (FR-012/FR-013). Both predicates run in a
    /// single pass over the corpus via [`crate::search::matches`] (NFR-001).
    ///
    /// When a filter is active (non-empty query or structured criteria set),
    /// hidden columns' matching cards are **revealed** in the rendered surface
    /// (DM-01M2MHJB884WCTVCDHPD2T3GE7: hidden-column cards reachable via
    /// filters/search). When no filter is active, matching cards from hidden
    /// columns are stashed in [`BoardState::hidden`] (no visual presence).
    pub fn build_filtered(
        board_config: &BoardConfiguration,
        config: &crate::config::Config,
        corpus: &Corpus,
        query: &str,
        filter: &StructuredFilter,
        resolution: &crate::workflow::CategoryResolution,
    ) -> Self {
        Self::build_filtered_with(
            board_config,
            config,
            corpus,
            query,
            filter,
            resolution,
            false,
        )
    }

    /// [`BoardState::build_filtered`], optionally rendering sub-issues under their
    /// parents (tix #1399).
    ///
    /// The `u` toggle is global, so it must keep working while a search or
    /// structured filter is active: `build_filtered` delegates here with
    /// `show_children == false` and the TUI passes its flag through.
    pub fn build_filtered_with(
        board_config: &BoardConfiguration,
        config: &crate::config::Config,
        corpus: &Corpus,
        query: &str,
        filter: &StructuredFilter,
        resolution: &crate::workflow::CategoryResolution,
        show_children: bool,
    ) -> Self {
        let show_mismatch = board_config.show_mismatch;
        // WP09, as in `build`: the service's completion column, so the filtered and
        // unfiltered boards agree on which column is blocked and which is complete.
        let done_column = crate::workflow::completion_column_or_default(board_config, config);
        let done_column = done_column.as_str();
        // Built from the corpus, not from the filtered slice below: a blocker the
        // query happens to exclude must still count as a blocker.
        let blocked = blocked_reasons(&corpus.issues, done_column);
        // Same reason, same discipline: a child the query excludes is still a
        // child, so a parent's marker must not shrink because the board is
        // filtered.
        let children = child_markers(&corpus.issues, done_column);
        let filtering = !query.is_empty() || filter.has_active_criteria();
        let sort_key = crate::search::control_token(query, "sort");
        // A bare-number query (all-ASCII-digit after trim) is an exact issue
        // number match, not a fuzzy digit search: only the issue whose
        // `number` equals it survives, still ANDed with the structured
        // filter (board-filtering FR-02 / FR-03). Any other query keeps the
        // fuzzy-text path.
        let number = crate::search::number_query(query);
        let hidden_names: Vec<&str> = board_config
            .hidden_columns
            .iter()
            .map(String::as_str)
            .collect();
        let mut column_map: Vec<Vec<Card>> =
            board_config.columns.iter().map(|_| Vec::new()).collect();
        let mut mismatch_cards = Vec::new();
        let mut matched_issues: Vec<&crate::model::Issue> = Vec::new();

        for (issue, text) in corpus.issues.iter().zip(corpus.texts.iter()) {
            // Bare-number query: exact issue-number match replaces the fuzzy
            // text layer (board-filtering FR-02); the structured filter still
            // runs (FR-03). Otherwise the composite fuzzy+structured
            // predicate applies unchanged.
            // `matches_issue`, not `matches` (WP08 T035): the TUI filter modal can
            // set a `category` criterion, and `matches` cannot judge it — it would
            // silently drop the criterion and show the **unfiltered** board while
            // the modal showed `category: completed` as active. The board already
            // holds the `resolution` (it is a parameter, because WP05 needed it for
            // the card labels), so the criterion costs one hash lookup per issue.
            let keep = if let Some(n) = number {
                issue.number == n && filter.evaluate_issue(issue, text, resolution)
            } else {
                crate::search::matches_issue(query, filter, issue, text, resolution)
            };
            if !keep {
                continue;
            }
            matched_issues.push(issue);
        }

        Self::sort_filtered_issues(&mut matched_issues, sort_key.as_deref());

        for issue in matched_issues {
            let card = Card {
                number: issue.number,
                title: issue.title.clone(),
                priority: issue.priority.clone(),
                labels: issue.labels.clone(),
                assignee: issue.assignee.clone(),
                filename: issue.filename.clone(),
                commit: issue.commit.clone(),
                created: issue.created.clone(),
                due_date: issue.due_date.clone(),
                status: issue.status.display().to_string(),
                category: crate::workflow::category_of(issue, resolution)
                    .map(|c| c.label().to_string()),
                category_color: crate::workflow::category_of(issue, resolution)
                    .and_then(|c| c.color_hint()),
                done: crate::workflow::is_completed(issue, resolution),
                cycle: issue.cycles.as_ref().and_then(|v| v.first().cloned()),
                milestone: issue.milestones.as_ref().and_then(|v| v.first().cloned()),
                blocked: blocked.get(&issue.number).cloned(),
                children: children.get(&issue.number).cloned(),
                parent: issue.parent,
                depth: 0,
                archived: issue.archived,
                related: issue.related_issues.len(),
            };
            if let Some(idx) = board_config
                .columns
                .iter()
                .position(|c| c == issue.status.display())
            {
                column_map[idx].push(card);
            } else {
                mismatch_cards.push(card);
            }
        }

        if sort_key.is_none() {
            for cards in column_map.iter_mut() {
                sort_cards(board_config, cards);
            }
            sort_cards(board_config, &mut mismatch_cards);
        }

        let mut columns: Vec<BoardColumn> = Vec::new();
        let mut hidden: Vec<BoardColumn> = Vec::new();
        for (cards, name) in column_map.into_iter().zip(board_config.columns.iter()) {
            let col = BoardColumn {
                name: name.clone(),
                cards,
            };
            if hidden_names.contains(&name.as_str()) {
                if filtering {
                    // Reveal hidden column when a filter is active so
                    // matching cards appear in the rendered surface
                    // (DM-01M2MHJB884WCTVCDHPD2T3GE7).
                    columns.push(col);
                } else {
                    hidden.push(col);
                }
            } else {
                columns.push(col);
            }
        }

        let mut state = BoardState {
            columns,
            hidden,
            mismatch: BoardColumn {
                name: "Mismatched".to_string(),
                cards: mismatch_cards,
            },
            show_mismatch,
            active_col: 0,
            selected: 0,
            filter: Some(query.to_string()),
            hover: None,
            hover_col: None,
        };
        state.apply_child_order(show_children);
        state
    }

    fn sort_filtered_issues(issues: &mut [&crate::model::Issue], sort: Option<&str>) {
        match sort.unwrap_or("created") {
            "due" => {
                issues.sort_by(|a, b| a.due_date.cmp(&b.due_date).then(a.number.cmp(&b.number)))
            }
            "start" => issues.sort_by(|a, b| {
                a.start_date
                    .cmp(&b.start_date)
                    .then(a.number.cmp(&b.number))
            }),
            "reviewer" => {
                issues.sort_by(|a, b| a.reviewer.cmp(&b.reviewer).then(a.number.cmp(&b.number)))
            }
            "cycle" => issues.sort_by(|a, b| {
                a.cycles
                    .as_ref()
                    .and_then(|v| v.first())
                    .cmp(&b.cycles.as_ref().and_then(|v| v.first()))
                    .then(a.number.cmp(&b.number))
            }),
            "milestone" => issues.sort_by(|a, b| {
                a.milestones
                    .as_ref()
                    .and_then(|v| v.first())
                    .cmp(&b.milestones.as_ref().and_then(|v| v.first()))
                    .then(a.number.cmp(&b.number))
            }),
            "status" => issues.sort_by(|a, b| {
                a.status
                    .display()
                    .cmp(b.status.display())
                    .then(a.number.cmp(&b.number))
            }),
            "priority" => issues.sort_by(|a, b| {
                a.priority
                    .to_string()
                    .cmp(&b.priority.to_string())
                    .then(a.number.cmp(&b.number))
            }),
            _ => issues.sort_by(|a, b| a.created.cmp(&b.created).then(a.number.cmp(&b.number))),
        }
    }

    /// True when no card anywhere is visible (used for zero-match feedback).
    pub fn is_empty(&self) -> bool {
        self.columns.iter().all(|c| c.cards.is_empty())
            && (!self.show_mismatch || self.mismatch.cards.is_empty())
    }

    pub fn total_cols(&self) -> usize {
        if self.show_mismatch {
            self.columns.len() + 1
        } else {
            self.columns.len()
        }
    }

    /// Map a terminal pointer `(x, y)` — given against the same `area` passed
    /// to [`render`] — to the card or column underneath. `status` mirrors
    /// whether [`render`] is drawing a status message, so the status row (not
    /// part of any column) never resolves to a target. Returns `None` for
    /// positions outside the board area (`y` above the columns or beyond the
    /// board) or when nothing is drawn. Uses [`compute_column_rects`] and
    /// [`super::widgets::card_line_count`] — the geometry `render` draws with —
    /// so the hit-tested layout matches the rendered one by construction (D3).
    pub fn hit_test(
        &self,
        area: Rect,
        display: BoardDisplay,
        status: bool,
        x: u16,
        y: u16,
    ) -> Option<HitTarget> {
        if area.height < 2 || area.width < 4 || self.total_cols() == 0 {
            return None;
        }
        let board_height = area.height.saturating_sub(u16::from(status));
        if y >= area.y + board_height {
            return None;
        }
        let board_area = Rect {
            height: board_height,
            ..area
        };

        let rects = compute_column_rects(board_area, self.total_cols());
        let (col, col_rect) = rects
            .iter()
            .enumerate()
            .find(|(_, r)| r.contains(Position::new(x, y)))?;

        let cards: &[Card] = if col < self.columns.len() {
            &self.columns[col].cards
        } else {
            &self.mismatch.cards
        };

        let group_mode = self
            .filter
            .as_deref()
            .and_then(|q| crate::search::control_token(q, "group"));

        // Items stack top-down exactly as `render` pushes them: group headers
        // occupy one row each, cards occupy `card_line_count` rows.
        let mut items: Vec<Option<usize>> = Vec::new();
        if let Some(mode) = group_mode.as_deref() {
            if let Some(sections) = Self::group_sections(cards, Some(mode)) {
                for section in sections {
                    items.push(None);
                    for (j, card) in cards
                        .iter()
                        .enumerate()
                        .take(section.end)
                        .skip(section.start)
                    {
                        let count = widgets::card_line_count(
                            card,
                            col_rect.width as usize,
                            display.wrap_titles,
                            display.title_lines,
                        );
                        for _ in 0..count {
                            items.push(Some(j));
                        }
                    }
                }
            }
        } else {
            for (j, card) in cards.iter().enumerate() {
                let count = widgets::card_line_count(
                    card,
                    col_rect.width as usize,
                    display.wrap_titles,
                    display.title_lines,
                );
                for _ in 0..count {
                    items.push(Some(j));
                }
            }
        }

        let has_footer = BoardState::group_footer(cards, group_mode.as_deref()).is_some();
        let list_height = col_rect.height.saturating_sub(u16::from(has_footer));
        // Content rows live between the block's top border and bottom border.
        let content_top = col_rect.y + 1;
        let content_end = col_rect.y + list_height.saturating_sub(1);
        if y >= content_top && y < content_end {
            let offset = usize::from(y - content_top);
            if let Some(Some(row)) = items.get(offset) {
                return Some(HitTarget::Card { col, row: *row });
            }
        }
        Some(HitTarget::Column { col })
    }

    /// Columns a card can be moved into: the configured columns plus (when
    /// shown) the "Mismatched" sentinel, which is never a move target. The
    /// `</>` move keys navigate *among movable columns* only.
    pub fn real_cols(&self) -> usize {
        self.columns.len()
    }

    pub fn column_name(&self, idx: usize) -> &str {
        if idx < self.columns.len() {
            &self.columns[idx].name
        } else if idx == self.columns.len() && self.show_mismatch {
            &self.mismatch.name
        } else {
            "Unknown"
        }
    }

    /// The name under the active cursor, resolving **hidden** columns too
    /// (visible region first, then hidden, then Unknown). Lets `toggle` keep a
    /// logical cursor on a just-hidden column so a second press re-shows it
    /// (T017: "a second press on the same column re-shows it").
    pub fn active_column_name(&self) -> &str {
        let visible = self.columns.len();
        if self.active_col < visible {
            &self.columns[self.active_col].name
        } else {
            let hidden_idx = self.active_col - visible;
            if hidden_idx < self.hidden.len() {
                &self.hidden[hidden_idx].name
            } else {
                "Unknown"
            }
        }
    }

    pub fn column_cards(&self, idx: usize) -> &[Card] {
        if idx < self.columns.len() {
            &self.columns[idx].cards
        } else if idx == self.columns.len() && self.show_mismatch {
            &self.mismatch.cards
        } else {
            &[]
        }
    }

    pub fn get_selected_card(&self) -> Option<&Card> {
        self.column_cards(self.active_col).get(self.selected)
    }

    pub fn move_left(&mut self) {
        let total = self.real_cols();
        self.active_col = if total == 0 {
            0
        } else if self.active_col >= total {
            total - 1
        } else {
            (self.active_col + total - 1) % total
        };
        self.clamp_selection();
    }

    pub fn move_right(&mut self) {
        let total = self.real_cols();
        self.active_col = if total == 0 || self.active_col >= total {
            0
        } else {
            (self.active_col + 1) % total
        };
        self.clamp_selection();
    }

    pub fn move_up(&mut self) {
        if self.selected > 0 {
            self.selected -= 1;
        }
    }

    pub fn move_down(&mut self) {
        let cards = self.column_cards(self.active_col);
        if self.selected + 1 < cards.len() {
            self.selected += 1;
        }
    }

    /// Move the selection by `cards` (negative moves up), clamped to the column
    /// (tix #1442 follow-up).
    ///
    /// The page step: `move_up`/`move_down` are the one-card steps, this is the same
    /// move by a screenful. It clamps for the reason the detail pane's scroll does — a
    /// jump past the end should land on the last card, not walk off it.
    pub fn move_selection_by(&mut self, cards: i32) {
        let len = self.column_cards(self.active_col).len();
        if len == 0 {
            self.selected = 0;
            return;
        }
        let next = i32::try_from(self.selected)
            .unwrap_or(i32::MAX)
            .saturating_add(cards);
        self.selected = next.clamp(0, i32::try_from(len).unwrap_or(i32::MAX) - 1) as usize;
    }

    pub fn clamp_selection(&mut self) {
        let cards = self.column_cards(self.active_col);
        if cards.is_empty() {
            self.selected = 0;
        } else if self.selected >= cards.len() {
            self.selected = cards.len() - 1;
        }
    }

    pub fn select_column(&mut self, col: usize) {
        let total = self.real_cols();
        if total > 0 {
            self.active_col = col % total;
        }
        self.clamp_selection();
    }

    fn group_footer(cards: &[Card], mode: Option<&str>) -> Option<String> {
        let sections = Self::group_sections(cards, mode)?;
        let text = sections
            .into_iter()
            .map(|section| {
                let pct = if section.total == 0 {
                    0
                } else {
                    (section.done * 100) / section.total
                };
                format!("{} {}/{} {pct}%", section.name, section.done, section.total)
            })
            .collect::<Vec<_>>()
            .join(" | ");
        Some(text)
    }

    fn card_group(card: &Card, key: &str) -> String {
        match key {
            "cycle" => card.cycle.clone().unwrap_or_else(|| "(none)".to_string()),
            "milestone" => card
                .milestone
                .clone()
                .unwrap_or_else(|| "(none)".to_string()),
            _ => "(none)".to_string(),
        }
    }

    fn group_sections(cards: &[Card], mode: Option<&str>) -> Option<Vec<GroupSection>> {
        let key = mode.filter(|m| *m == "cycle" || *m == "milestone")?;
        if cards.is_empty() {
            return None;
        }
        let mut sections = Vec::new();
        let mut current = String::new();
        let mut start = 0usize;
        let mut done = 0usize;
        let mut total = 0usize;
        for (idx, card) in cards.iter().enumerate() {
            let group = Self::card_group(card, key);
            if idx == 0 {
                current = group;
            } else if group != current {
                sections.push(GroupSection {
                    name: std::mem::take(&mut current),
                    start,
                    end: idx,
                    done,
                    total,
                });
                current = group;
                start = idx;
                done = 0;
                total = 0;
            }
            total += 1;
            if card.done {
                done += 1;
            }
        }
        sections.push(GroupSection {
            name: current,
            start,
            end: cards.len(),
            done,
            total,
        });
        Some(sections)
    }
}

/// Render options carried from the active board configuration into the board
/// draw. Kept tiny and copyable so tests and call sites stay light.
#[derive(Debug, Clone, Copy)]
pub struct BoardDisplay {
    pub wrap_titles: bool,
    pub title_lines: usize,
}

impl Default for BoardDisplay {
    fn default() -> Self {
        BoardDisplay {
            wrap_titles: true,
            title_lines: 3,
        }
    }
}

impl From<&crate::config::BoardConfiguration> for BoardDisplay {
    fn from(config: &crate::config::BoardConfiguration) -> Self {
        BoardDisplay {
            wrap_titles: config.wrap_titles,
            title_lines: config.title_lines,
        }
    }
}

/// Equal-width column slices for a board of `total_cols` columns (the same
/// `Constraint::Ratio` layout `render` draws), shared so hit-testing can map a
/// pointer position back to a column without re-deriving geometry (D3).
pub fn compute_column_rects(area: Rect, total_cols: usize) -> Vec<Rect> {
    if total_cols == 0 {
        return Vec::new();
    }
    Layout::default()
        .direction(Direction::Horizontal)
        .constraints(vec![Constraint::Ratio(1, total_cols as u32); total_cols])
        .split(area)
        .to_vec()
}

pub fn render(
    board: &BoardState,
    f: &mut Frame,
    area: Rect,
    status_msg: &Option<String>,
    drag_preview_col: Option<usize>,
    display: BoardDisplay,
) -> usize {
    // How many cards one screen of the **active** column holds (tix #1442 follow-up).
    //
    // Returned rather than re-derived by the caller: this is the only place that knows
    // the column's inner height *and* each card's rendered height, and a page key needs
    // both. `0` when nothing was drawn, so the caller cannot page a column that is not
    // on screen.
    let mut page_cards = 0usize;

    if area.height < 2 || area.width < 4 {
        return 0;
    }

    let status_height: u16 = if status_msg.is_some() { 1 } else { 0 };
    let board_height = area.height.saturating_sub(status_height);
    let board_area = Rect {
        height: board_height,
        ..area
    };
    let status_area = Rect {
        y: area.y + board_height,
        height: status_height,
        ..area
    };

    let total = board.total_cols();
    if total == 0 {
        return 0;
    }

    let chunks = compute_column_rects(board_area, total);

    for (i, chunk) in chunks.iter().enumerate() {
        let col = if i < board.columns.len() {
            &board.columns[i]
        } else {
            &board.mismatch
        };
        let group_mode = board
            .filter
            .as_deref()
            .and_then(|q| crate::search::control_token(q, "group"));

        let is_active = i == board.active_col;
        let is_mismatch_col = i == board.columns.len();
        let is_mismatch_highlight = is_mismatch_col && !col.cards.is_empty();
        // The column the pointer sits in — set for empty columns too, so hovering
        // anywhere in a column lights the whole column up (not just a card).
        let hovered_col = board.hover_col;

        let mut selected_row: Option<usize> = None;
        let items: Vec<ListItem> = if let Some(mode) = group_mode.as_deref() {
            if let Some(sections) = BoardState::group_sections(&col.cards, Some(mode)) {
                let mut items = Vec::new();
                for section in sections {
                    let pct = if section.total == 0 {
                        0
                    } else {
                        (section.done * 100) / section.total
                    };
                    let header = format!(
                        "-- {mode}: {} ({}/{} done, {pct}%) --",
                        section.name, section.done, section.total
                    );
                    items.push(ListItem::new(Line::from(Span::styled(
                        header,
                        Style::default()
                            .fg(Color::Yellow)
                            .add_modifier(Modifier::BOLD),
                    ))));
                    for j in section.start..section.end {
                        let card = &col.cards[j];
                        let lines = widgets::card_lines(
                            card,
                            chunk.width as usize,
                            display.wrap_titles,
                            display.title_lines,
                        );
                        let style = if is_active && j == board.selected {
                            selected_row = Some(items.len());
                            Style::default()
                                .bg(Color::DarkGray)
                                .add_modifier(Modifier::BOLD)
                        } else if board.hover == Some((i, j)) {
                            // Hover highlight only — selection is untouched (D8).
                            if drag_preview_col == Some(i) {
                                Style::default()
                                    .fg(Color::Yellow)
                                    .add_modifier(Modifier::BOLD)
                            } else {
                                Style::default().fg(Color::Cyan)
                            }
                        } else if is_mismatch_highlight {
                            Style::default().fg(Color::Red)
                        } else {
                            Style::default()
                        };
                        items.push(ListItem::new(lines).style(style));
                    }
                }
                items
            } else {
                Vec::new()
            }
        } else {
            col.cards
                .iter()
                .enumerate()
                .map(|(j, card)| {
                    let lines = widgets::card_lines(
                        card,
                        chunk.width as usize,
                        display.wrap_titles,
                        display.title_lines,
                    );
                    let style = if is_active && j == board.selected {
                        selected_row = Some(j);
                        Style::default()
                            .bg(Color::DarkGray)
                            .add_modifier(Modifier::BOLD)
                    } else if board.hover == Some((i, j)) {
                        if drag_preview_col == Some(i) {
                            Style::default()
                                .fg(Color::Yellow)
                                .add_modifier(Modifier::BOLD)
                        } else {
                            Style::default().fg(Color::Cyan)
                        }
                    } else if is_mismatch_highlight {
                        Style::default().fg(Color::Red)
                    } else {
                        Style::default()
                    };
                    ListItem::new(lines).style(style)
                })
                .collect()
        };

        let title = format!("{} ({})", col.name, col.cards.len());
        let border_style = if drag_preview_col == Some(i) {
            Style::default().fg(Color::Yellow)
        } else if is_active {
            Style::default().fg(Color::Cyan)
        } else if is_mismatch_highlight {
            Style::default().fg(Color::Red)
        } else if hovered_col == Some(i) {
            // The hovered column gets its own accent so the pointer's column is
            // visible even when the card itself is small.
            Style::default()
                .fg(Color::Blue)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default()
        };

        let block = Block::default()
            .borders(Borders::ALL)
            .title(title)
            .border_style(border_style);

        let col_chunks = if BoardState::group_footer(&col.cards, group_mode.as_deref()).is_some() {
            Layout::default()
                .direction(Direction::Vertical)
                .constraints([Constraint::Min(1), Constraint::Length(1)])
                .split(*chunk)
        } else {
            Layout::default()
                .direction(Direction::Vertical)
                .constraints([Constraint::Min(1), Constraint::Length(0)])
                .split(*chunk)
        };

        let list = List::new(items).block(block);

        if is_active {
            // A page is what the reader can see: the column's inner height against the
            // heights the cards actually render at.
            page_cards = cards_per_screen(
                &col.cards,
                chunk.width as usize,
                col_chunks[0].height.saturating_sub(2),
                display,
            );
            let mut state = ListState::default();
            if let Some(row) = selected_row {
                state.select(Some(row));
            }
            f.render_stateful_widget(list, col_chunks[0], &mut state);
        } else {
            f.render_widget(list, col_chunks[0]);
        }
        if let Some(footer) = BoardState::group_footer(&col.cards, group_mode.as_deref()) {
            let para = Paragraph::new(Line::from(Span::styled(
                footer,
                Style::default().fg(Color::DarkGray),
            )));
            f.render_widget(para, col_chunks[1]);
        }
    }

    if let Some(msg) = status_msg {
        // The status area is one row and does not wrap, so anything longer is cut
        // by the widget with no indication at all. Mark the cut instead: a
        // silently shortened warning reads as a complete one, and the
        // retired-`links:` disclosure runs to ~100 characters before the filename,
        // which is routinely longer still.
        //
        // `Paragraph` is handed the truncated string rather than the full one, so
        // the ellipsis cannot itself be pushed off the right edge.
        //
        // Truncation is measured in **display cells**, not scalar values. A CJK
        // character occupies two cells, so `chars().take(budget)` yields a string
        // up to twice as wide as the area; the widget then hard-cuts it at the
        // right edge and discards the marker appended at the end of the
        // overflowed string — silently reinstating the exact failure this
        // truncation exists to prevent. `unicode-width` is already a dependency,
        // so this costs no new one.
        let budget = (status_area.width as usize).saturating_sub(1);
        let text = truncate_to_cells(msg, budget);
        let para =
            Paragraph::new(Line::from(Span::raw(text))).style(Style::default().fg(Color::Yellow));
        f.render_widget(para, status_area);
    }

    page_cards
}

/// How many of `cards` fit into `rows` of a column `width` cells wide.
///
/// Measured with the same [`widgets::card_lines`] the renderer draws, so the answer is
/// the height the reader actually sees rather than an estimate from a constant. Group
/// headers and the group footer are **not** counted: the result is a step size for a
/// page key, and a step that overshoots by a header or two is friendlier than one that
/// undershoots and leaves the reader pressing the key again.
///
/// Zero for an empty column — "there is nothing to page" — and at least one otherwise,
/// so a page key in a column shorter than a single card still moves somewhere.
fn cards_per_screen(cards: &[Card], width: usize, rows: u16, display: BoardDisplay) -> usize {
    if cards.is_empty() {
        return 0;
    }
    let mut used: u16 = 0;
    let mut fits = 0usize;
    for card in cards {
        let height = u16::try_from(
            widgets::card_lines(card, width, display.wrap_titles, display.title_lines).len(),
        )
        .unwrap_or(u16::MAX);
        if fits > 0 && used.saturating_add(height) > rows {
            break;
        }
        used = used.saturating_add(height);
        fits += 1;
        if used >= rows {
            break;
        }
    }
    fits.max(1)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;

    #[test]
    fn compute_column_rects_splits_into_equal_columns() {
        let area = Rect::new(5, 7, 90, 30);
        let rects = compute_column_rects(area, 3);
        assert_eq!(rects.len(), 3);
        assert_eq!((rects[0].x, rects[0].width), (5, 30));
        assert_eq!((rects[1].x, rects[1].width), (35, 30));
        assert_eq!((rects[2].x, rects[2].width), (65, 30));
        assert_eq!((rects[0].y, rects[0].height), (7, 30));
        assert_eq!((rects[2].y, rects[2].height), (7, 30));
    }

    #[test]
    fn compute_column_rects_zero_columns_is_empty() {
        assert!(compute_column_rects(Rect::new(0, 0, 10, 10), 0).is_empty());
    }

    #[test]
    fn card_line_count_matches_rendered_card_heights() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let wrapped = "A deliberately long card title that cannot fit on a single line inside the narrow column and must wrap over several rows";
        let cards = vec![
            Card {
                number: 1,
                title: "Short".into(),
                priority: crate::model::Priority::Medium,
                labels: vec![],
                assignee: None,
                filename: "1.md".into(),
                commit: None,
                created: "2026-01-01".into(),
                due_date: None,
                status: "todo".into(),
                category: None,
                category_color: None,
                done: false,
                cycle: None,
                milestone: None,
                blocked: None,
                children: None,
                parent: None,
                depth: 0,
                archived: false,
                related: 0,
            },
            Card {
                number: 2,
                title: wrapped.into(),
                priority: crate::model::Priority::Medium,
                labels: vec![],
                assignee: None,
                filename: "2.md".into(),
                commit: None,
                created: "2026-01-01".into(),
                due_date: None,
                status: "todo".into(),
                category: None,
                category_color: None,
                done: false,
                cycle: None,
                milestone: None,
                blocked: None,
                children: None,
                parent: None,
                depth: 0,
                archived: false,
                related: 0,
            },
            Card {
                number: 3,
                title: "Another long title card that also wraps".into(),
                priority: crate::model::Priority::Medium,
                labels: vec![],
                assignee: None,
                filename: "3.md".into(),
                commit: None,
                created: "2026-01-01".into(),
                due_date: None,
                status: "todo".into(),
                category: None,
                category_color: None,
                done: false,
                cycle: None,
                milestone: None,
                blocked: None,
                children: None,
                parent: None,
                depth: 0,
                archived: false,
                related: 0,
            },
        ];
        let board = BoardState {
            columns: vec![BoardColumn {
                name: "todo".into(),
                cards,
            }],
            hidden: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            show_mismatch: false,
        };
        let display = BoardDisplay {
            wrap_titles: true,
            title_lines: 3,
        };
        let width = 80u16;
        let height = 30u16;
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| {
                render(&board, f, f.area(), &None, None, display);
            })
            .unwrap();
        let buffer = terminal.backend().buffer();

        let col_width = compute_column_rects(Rect::new(0, 0, width, height), 1)[0].width as usize;

        let mut starts: Vec<(u32, u16)> = Vec::new();
        for y in 0..height {
            let line: String = (1..width.min(24))
                .map(|x| buffer[(x, y)].symbol())
                .collect();
            for card in &board.columns[0].cards {
                if line.starts_with(&format!("#{} ", card.number))
                    && !starts.iter().any(|(n, _)| *n == card.number)
                {
                    starts.push((card.number, y));
                    break;
                }
            }
        }
        starts.sort_by_key(|(_, y)| *y);
        assert_eq!(
            starts.len(),
            3,
            "every card found in the buffer: {starts:?}"
        );
        for (idx, (number, y)) in starts.iter().enumerate() {
            let span: u16 = if idx + 1 < starts.len() {
                starts[idx + 1].1 - y
            } else {
                u16::try_from(
                    (*y..height)
                        .filter(|&rw| {
                            rw != height - 1
                                && (1..(width - 1)).any(|x| buffer[(x, rw)].symbol() != " ")
                        })
                        .count(),
                )
                .unwrap()
            };
            let card = board.columns[0]
                .cards
                .iter()
                .find(|c| c.number == *number)
                .expect("card on the board");
            let expected =
                widgets::card_line_count(card, col_width, display.wrap_titles, display.title_lines);
            assert_eq!(
                span, expected,
                "rendered height of card #{number} must match card_line_count"
            );
        }
    }

    #[test]
    fn hit_test_cards_and_column_fallback() {
        let tall = "A deliberately long card title that cannot fit on a single line inside the narrow column and wraps over several rows";
        let cards = vec![
            Card {
                number: 1,
                title: "one".into(),
                priority: Priority::Medium,
                labels: vec![],
                assignee: None,
                filename: "1.md".into(),
                commit: None,
                created: "2026-01-01".into(),
                due_date: None,
                status: "todo".into(),
                category: None,
                category_color: None,
                done: false,
                cycle: None,
                milestone: None,
                blocked: None,
                children: None,
                parent: None,
                depth: 0,
                archived: false,
                related: 0,
            },
            Card {
                number: 2,
                title: tall.into(),
                priority: Priority::Medium,
                labels: vec![],
                assignee: None,
                filename: "2.md".into(),
                commit: None,
                created: "2026-01-02".into(),
                due_date: None,
                status: "todo".into(),
                category: None,
                category_color: None,
                done: false,
                cycle: None,
                milestone: None,
                blocked: None,
                children: None,
                parent: None,
                depth: 0,
                archived: false,
                related: 0,
            },
        ];
        let board = BoardState {
            columns: vec![
                BoardColumn {
                    name: "todo".into(),
                    cards,
                },
                BoardColumn {
                    name: "done".into(),
                    cards: vec![Card {
                        number: 3,
                        title: "three".into(),
                        priority: Priority::Medium,
                        labels: vec![],
                        assignee: None,
                        filename: "3.md".into(),
                        commit: None,
                        created: "2026-01-03".into(),
                        due_date: None,
                        status: "done".into(),
                        category: None,
                        category_color: None,
                        done: true,
                        cycle: None,
                        milestone: None,
                        blocked: None,
                        children: None,
                        parent: None,
                        depth: 0,
                        archived: false,
                        related: 0,
                    }],
                },
            ],
            hidden: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            show_mismatch: false,
        };
        let display = BoardDisplay::default();
        let area = Rect::new(0, 0, 80, 30);
        let widths = compute_column_rects(area, 2);
        let col0 = widths[0].width as usize;
        let card1_height = widgets::card_line_count(&board.columns[0].cards[0], col0, true, 3);

        // First card occupies a single row right below the top border.
        assert_eq!(
            board.hit_test(area, display, false, 3, 1),
            Some(HitTarget::Card { col: 0, row: 0 })
        );
        // Second (wrapping) card starts where the first one ends, row-wise.
        assert_eq!(
            board.hit_test(area, display, false, 3, 1 + card1_height),
            Some(HitTarget::Card { col: 0, row: 1 })
        );
        // Blank area below the stacked cards selects the column itself.
        assert_eq!(
            board.hit_test(area, display, false, 3, 10),
            Some(HitTarget::Column { col: 0 })
        );
        // The block border still resolves to its column.
        assert_eq!(
            board.hit_test(area, display, false, 0, 5),
            Some(HitTarget::Column { col: 0 })
        );
        // Second column, single card in the first content row.
        assert_eq!(
            board.hit_test(area, display, false, 55, 0),
            Some(HitTarget::Column { col: 1 })
        );
        assert_eq!(
            board.hit_test(area, display, false, 55, 1),
            Some(HitTarget::Card { col: 1, row: 0 })
        );
        // The block's bottom border still resolves to its column.
        assert_eq!(
            board.hit_test(area, display, false, 3, 29),
            Some(HitTarget::Column { col: 0 })
        );
    }

    #[test]
    fn hit_test_outside_area_is_none() {
        let board = BoardState {
            columns: vec![BoardColumn {
                name: "todo".into(),
                cards: vec![Card {
                    number: 1,
                    title: "one".into(),
                    priority: Priority::Medium,
                    labels: vec![],
                    assignee: None,
                    filename: "1.md".into(),
                    commit: None,
                    created: "2026-01-01".into(),
                    due_date: None,
                    status: "todo".into(),
                    category: None,
                    category_color: None,
                    done: false,
                    cycle: None,
                    milestone: None,
                    blocked: None,
                    children: None,
                    parent: None,
                    depth: 0,
                    archived: false,
                    related: 0,
                }],
            }],
            hidden: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            show_mismatch: false,
        };
        let display = BoardDisplay::default();
        let area = Rect::new(0, 5, 40, 12);
        // Above the area.
        assert_eq!(board.hit_test(area, display, false, 3, 3), None);
        // Inside the area on a card (content starts one row below the top border).
        assert_eq!(
            board.hit_test(area, display, false, 3, 6),
            Some(HitTarget::Card { col: 0, row: 0 })
        );
        // Beyond the right edge of the area.
        assert_eq!(board.hit_test(area, display, false, 44, 7), None);
    }

    #[test]
    fn hit_test_respects_status_row() {
        let board = BoardState {
            columns: vec![BoardColumn {
                name: "todo".into(),
                cards: vec![Card {
                    number: 1,
                    title: "one".into(),
                    priority: Priority::Medium,
                    labels: vec![],
                    assignee: None,
                    filename: "1.md".into(),
                    commit: None,
                    created: "2026-01-01".into(),
                    due_date: None,
                    status: "todo".into(),
                    category: None,
                    category_color: None,
                    done: false,
                    cycle: None,
                    milestone: None,
                    blocked: None,
                    children: None,
                    parent: None,
                    depth: 0,
                    archived: false,
                    related: 0,
                }],
            }],
            hidden: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            show_mismatch: false,
        };
        let display = BoardDisplay::default();
        let area = Rect::new(0, 0, 80, 30);
        // With a status message the last row belongs to the status line, not a
        // column, so it must not resolve.
        assert_eq!(board.hit_test(area, display, true, 3, 29), None);
        assert_eq!(
            board.hit_test(area, display, true, 3, 1),
            Some(HitTarget::Card { col: 0, row: 0 })
        );
    }

    #[test]
    fn hit_test_group_header_is_not_a_card() {
        let cycle_card = |number: u32, cycle: &str| Card {
            number,
            title: format!("task {number}"),
            priority: Priority::Medium,
            labels: vec![],
            assignee: None,
            filename: format!("{number}.md"),
            commit: None,
            created: format!("2026-01-{number:02}"),
            due_date: None,
            status: "todo".into(),
            category: None,
            category_color: None,
            done: false,
            cycle: Some(cycle.into()),
            milestone: None,
            blocked: None,
            children: None,
            parent: None,
            depth: 0,
            archived: false,
            related: 0,
        };
        let board = BoardState {
            columns: vec![
                BoardColumn {
                    name: "todo".into(),
                    cards: vec![cycle_card(1, "alpha"), cycle_card(2, "beta")],
                },
                BoardColumn {
                    name: "done".into(),
                    cards: vec![],
                },
            ],
            hidden: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: Some("group:cycle".into()),
            hover: None,
            hover_col: None,
            show_mismatch: false,
        };
        let display = BoardDisplay::default();
        let area = Rect::new(0, 0, 80, 30);
        let col0 = area.width / 2;
        let first_height =
            widgets::card_line_count(&board.columns[0].cards[0], col0 as usize, true, 3);

        // Header row for the "alpha" section selects the column, not a card.
        assert_eq!(
            board.hit_test(area, display, false, 5, 1),
            Some(HitTarget::Column { col: 0 })
        );
        // The card below its header maps to its real column index.
        assert_eq!(
            board.hit_test(area, display, false, 5, 2),
            Some(HitTarget::Card { col: 0, row: 0 })
        );
        // Second section header sits below the first card's rows.
        assert_eq!(
            board.hit_test(area, display, false, 5, 2 + first_height),
            Some(HitTarget::Column { col: 0 })
        );
        assert_eq!(
            board.hit_test(area, display, false, 5, 3 + first_height),
            Some(HitTarget::Card { col: 0, row: 1 })
        );
    }

    #[test]
    fn hit_test_mismatch_column_resolves() {
        let board = BoardState {
            columns: vec![BoardColumn {
                name: "todo".into(),
                cards: vec![],
            }],
            hidden: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![Card {
                    number: 9,
                    title: "oddball".into(),
                    priority: Priority::Medium,
                    labels: vec![],
                    assignee: None,
                    filename: "9.md".into(),
                    commit: None,
                    created: "2026-01-09".into(),
                    due_date: None,
                    status: "weird".into(),
                    category: None,
                    category_color: None,
                    done: false,
                    cycle: None,
                    milestone: None,
                    blocked: None,
                    children: None,
                    parent: None,
                    depth: 0,
                    archived: false,
                    related: 0,
                }],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            show_mismatch: true,
        };
        let display = BoardDisplay::default();
        let area = Rect::new(0, 0, 90, 30);
        let mismatch_col = board.columns.len();
        // The mismatch column is the last (3rd) of the equal-width columns.
        assert_eq!(
            board.hit_test(area, display, false, 70, 1),
            Some(HitTarget::Card {
                col: mismatch_col,
                row: 0
            })
        );
    }

    #[test]
    fn render_highlights_hovered_card_without_selecting() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;
        let board = BoardState {
            columns: vec![BoardColumn {
                name: "todo".into(),
                cards: vec![
                    Card {
                        number: 1,
                        title: "Alpha".into(),
                        priority: Priority::Medium,
                        labels: vec![],
                        assignee: None,
                        filename: "1.md".into(),
                        commit: None,
                        created: "2026-01-01".into(),
                        due_date: None,
                        status: "todo".into(),
                        category: None,
                        category_color: None,
                        done: false,
                        cycle: None,
                        milestone: None,
                        blocked: None,
                        children: None,
                        parent: None,
                        depth: 0,
                        archived: false,
                        related: 0,
                    },
                    Card {
                        number: 2,
                        title: "Beta".into(),
                        priority: Priority::Medium,
                        labels: vec![],
                        assignee: None,
                        filename: "2.md".into(),
                        commit: None,
                        created: "2026-01-02".into(),
                        due_date: None,
                        status: "todo".into(),
                        category: None,
                        category_color: None,
                        done: false,
                        cycle: None,
                        milestone: None,
                        blocked: None,
                        children: None,
                        parent: None,
                        depth: 0,
                        archived: false,
                        related: 0,
                    },
                ],
            }],
            hidden: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            show_mismatch: false,
            active_col: 0,
            selected: 0,
            hover: Some((0, 1)),
            hover_col: Some(0),
            filter: None,
        };
        let display = BoardDisplay::default();
        let backend = TestBackend::new(80, 30);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| {
                render(&board, f, f.area(), &None, None, display);
            })
            .unwrap();
        let buffer = terminal.backend().buffer();

        let mut rows = [None, None];
        for y in 0..30u16 {
            let line: String = (1..12).map(|x| buffer[(x, y)].symbol()).collect();
            if line.starts_with("#1") {
                rows[0] = Some(y);
            }
            if line.starts_with("#2") {
                rows[1] = Some(y);
            }
        }
        let y1 = rows[0].expect("first card rendered");
        let y2 = rows[1].expect("second card rendered");

        // The selected card keeps its selection style (dark-gray background)...
        assert_eq!(buffer[(3, y1)].style().bg, Some(Color::DarkGray));
        // ...while the hovered card is highlighted in cyan...
        assert_eq!(buffer[(3, y2)].style().fg, Some(Color::Cyan));
        // ...and hovering changed nothing about the selection.
        assert_eq!((board.active_col, board.selected), (0, 0));
    }

    #[test]
    fn render_highlights_the_hovered_cards_column() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let card = |number: u32, title: &str, status: &str| Card {
            number,
            title: title.into(),
            priority: Priority::Medium,
            labels: vec![],
            assignee: None,
            filename: format!("{number}.md"),
            commit: None,
            created: "2026-01-01".into(),
            due_date: None,
            status: status.into(),
            category: None,
            category_color: None,
            done: false,
            cycle: None,
            milestone: None,
            blocked: None,
            children: None,
            parent: None,
            depth: 0,
            archived: false,
            related: 0,
        };
        let board = BoardState {
            columns: vec![
                BoardColumn {
                    name: "todo".into(),
                    cards: vec![card(1, "Alpha", "todo")],
                },
                BoardColumn {
                    name: "doing".into(),
                    cards: vec![card(2, "Beta", "doing")],
                },
            ],
            hidden: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            show_mismatch: false,
            active_col: 0,
            selected: 0,
            // Hovering the card in the *second* column.
            hover: Some((1, 0)),
            hover_col: Some(1),
            filter: None,
        };
        let display = BoardDisplay::default();
        let area = Rect::new(0, 0, 80, 30);
        let backend = TestBackend::new(80, 30);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| {
                render(&board, f, f.area(), &None, None, display);
            })
            .unwrap();
        let buffer = terminal.backend().buffer();

        let chunks = compute_column_rects(area, board.total_cols());
        let hovered = chunks[1];
        let active = chunks[0];
        assert_eq!(
            buffer[(hovered.x, hovered.y)].style().fg,
            Some(Color::Blue),
            "the hovered column is outlined"
        );
        assert_eq!(
            buffer[(active.x, active.y)].style().fg,
            Some(Color::Cyan),
            "the active column keeps its own colour"
        );
    }

    #[test]
    fn render_marks_an_empty_hovered_column() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let board = BoardState {
            columns: vec![
                BoardColumn {
                    name: "todo".into(),
                    cards: vec![],
                },
                BoardColumn {
                    name: "doing".into(),
                    cards: vec![],
                },
            ],
            hidden: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            show_mismatch: false,
            active_col: 0,
            selected: 0,
            hover: None,
            // The pointer is over the *empty* second column.
            hover_col: Some(1),
            filter: None,
        };
        let display = BoardDisplay::default();
        let area = Rect::new(0, 0, 80, 30);
        let backend = TestBackend::new(80, 30);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| {
                render(&board, f, f.area(), &None, None, display);
            })
            .unwrap();
        let buffer = terminal.backend().buffer();

        let chunks = compute_column_rects(area, board.total_cols());
        assert_eq!(
            buffer[(chunks[1].x, chunks[1].y)].style().fg,
            Some(Color::Blue),
            "an empty column with no cards is still outlined when hovered"
        );
        assert_eq!(
            buffer[(chunks[0].x, chunks[0].y)].style().fg,
            Some(Color::Cyan),
            "the active column keeps its own colour"
        );
    }

    #[test]
    fn total_cols_includes_mismatch() {
        let board = BoardState {
            columns: vec![
                BoardColumn {
                    name: "a".into(),
                    cards: vec![],
                },
                BoardColumn {
                    name: "b".into(),
                    cards: vec![],
                },
            ],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            hidden: vec![],
            show_mismatch: true,
        };
        assert_eq!(board.total_cols(), 3);
    }

    #[test]
    fn column_name_mismatch_index() {
        let board = BoardState {
            columns: vec![BoardColumn {
                name: "todo".into(),
                cards: vec![],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            hidden: vec![],
            show_mismatch: true,
        };
        assert_eq!(board.column_name(0), "todo");
        assert_eq!(board.column_name(1), "Mismatched");
    }

    #[test]
    fn move_left_wraps_around() {
        let mut board = BoardState {
            columns: vec![
                BoardColumn {
                    name: "a".into(),
                    cards: vec![],
                },
                BoardColumn {
                    name: "b".into(),
                    cards: vec![],
                },
            ],
            hidden: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            show_mismatch: true,
        };
        board.move_left();
        assert_eq!(board.active_col, 1);
    }

    #[test]
    fn move_right_wraps_around() {
        let mut board = BoardState {
            columns: vec![
                BoardColumn {
                    name: "a".into(),
                    cards: vec![],
                },
                BoardColumn {
                    name: "b".into(),
                    cards: vec![],
                },
            ],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 2,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            hidden: vec![],
            show_mismatch: true,
        };
        board.move_right();
        assert_eq!(board.active_col, 0);
    }

    #[test]
    fn clamp_selection_empty_column() {
        let mut board = BoardState {
            columns: vec![BoardColumn {
                name: "a".into(),
                cards: vec![],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 5,
            filter: None,
            hover: None,
            hover_col: None,
            hidden: vec![],
            show_mismatch: true,
        };
        board.clamp_selection();
        assert_eq!(board.selected, 0);
    }

    #[test]
    fn clamp_selection_single_card() {
        let mut board = BoardState {
            columns: vec![BoardColumn {
                name: "a".into(),
                cards: vec![Card {
                    number: 1,
                    title: "X".into(),
                    priority: crate::model::Priority::Medium,
                    labels: vec![],
                    assignee: None,
                    filename: "x.md".into(),
                    commit: None,
                    created: "2026-01-01".into(),
                    due_date: None,
                    status: "todo".into(),
                    category: None,
                    category_color: None,
                    done: false,
                    cycle: None,
                    milestone: None,
                    blocked: None,
                    children: None,
                    parent: None,
                    depth: 0,
                    archived: false,
                    related: 0,
                }],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 5,
            filter: None,
            hover: None,
            hover_col: None,
            hidden: vec![],
            show_mismatch: true,
        };
        board.clamp_selection();
        assert_eq!(board.selected, 0);
    }

    #[test]
    fn move_up_clamps_at_top() {
        let mut board = BoardState {
            columns: vec![BoardColumn {
                name: "a".into(),
                cards: vec![Card {
                    number: 1,
                    title: "X".into(),
                    priority: crate::model::Priority::Medium,
                    labels: vec![],
                    assignee: None,
                    filename: "x.md".into(),
                    commit: None,
                    created: "2026-01-01".into(),
                    due_date: None,
                    status: "todo".into(),
                    category: None,
                    category_color: None,
                    done: false,
                    cycle: None,
                    milestone: None,
                    blocked: None,
                    children: None,
                    parent: None,
                    depth: 0,
                    archived: false,
                    related: 0,
                }],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            hidden: vec![],
            show_mismatch: true,
        };
        board.move_up();
        assert_eq!(board.selected, 0);
    }

    #[test]
    fn move_down_clamps_at_bottom() {
        let mut board = BoardState {
            columns: vec![BoardColumn {
                name: "a".into(),
                cards: vec![Card {
                    number: 1,
                    title: "X".into(),
                    priority: crate::model::Priority::Medium,
                    labels: vec![],
                    assignee: None,
                    filename: "x.md".into(),
                    commit: None,
                    created: "2026-01-01".into(),
                    due_date: None,
                    status: "todo".into(),
                    category: None,
                    category_color: None,
                    done: false,
                    cycle: None,
                    milestone: None,
                    blocked: None,
                    children: None,
                    parent: None,
                    depth: 0,
                    archived: false,
                    related: 0,
                }],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            hidden: vec![],
            show_mismatch: true,
        };
        board.move_down();
        assert_eq!(board.selected, 0);
    }

    #[test]
    fn render_smoke_does_not_panic_on_tiny_frame() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let backend = TestBackend::new(5, 3);
        let mut terminal = Terminal::new(backend).unwrap();
        let board = BoardState {
            columns: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            hidden: vec![],
            show_mismatch: true,
        };
        terminal
            .draw(|f| {
                render(&board, f, f.area(), &None, None, BoardDisplay::default());
            })
            .unwrap();
    }

    #[test]
    fn render_smoke_full_board() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let board = BoardState {
            columns: vec![
                BoardColumn {
                    name: "todo".into(),
                    cards: vec![],
                },
                BoardColumn {
                    name: "done".into(),
                    cards: vec![],
                },
            ],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            hidden: vec![],
            show_mismatch: true,
        };
        terminal
            .draw(|f| {
                render(
                    &board,
                    f,
                    f.area(),
                    &Some("test msg".into()),
                    None,
                    BoardDisplay::default(),
                );
            })
            .unwrap();
    }

    #[test]
    fn render_selected_multiline_card_highlights_all_wrapped_lines() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let title = "This is a deliberately long card title that will not fit on a single line inside the column and must wrap more than once";
        let card = crate::ui::board::Card {
            number: 7,
            title: title.into(),
            priority: crate::model::Priority::Medium,
            labels: vec![],
            assignee: None,
            filename: "x.md".into(),
            commit: None,
            created: "2026-01-01".into(),
            due_date: None,
            status: "todo".into(),
            category: None,
            category_color: None,
            done: false,
            cycle: None,
            milestone: None,
            blocked: None,
            children: None,
            parent: None,
            depth: 0,
            archived: false,
            related: 0,
        };
        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let board = BoardState {
            columns: vec![BoardColumn {
                name: "todo".into(),
                cards: vec![card],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            hidden: vec![],
            show_mismatch: false,
        };
        let display = BoardDisplay {
            wrap_titles: true,
            title_lines: 3,
        };
        terminal
            .draw(|f| {
                render(&board, f, f.area(), &None, None, display);
            })
            .unwrap();
        let buffer = terminal.backend().buffer();

        // The card is the only item in the only column; its block top border
        // sits on y=0, so the ListItem starts at y=1 and each wrapped line
        // must carry the selected-card highlight (DarkGray bg + BOLD).
        let mut highlighted = 0;
        for y in 1..buffer.area().height - 1 {
            let cell = &buffer[(2, y)];
            if cell.bg != Color::DarkGray {
                break;
            }
            assert!(
                cell.modifier.contains(Modifier::BOLD),
                "highlighted continuation line must stay bold: {cell:?}"
            );
            highlighted += 1;
        }
        assert!(
            highlighted >= 2,
            "wrapped card highlights every line, got {highlighted}"
        );
        assert!(
            highlighted <= display.title_lines,
            "highlight never exceeds the line limit: {highlighted}"
        );
    }

    #[test]
    fn render_grouped_mode_shows_section_headers() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).unwrap();
        let board = BoardState {
            columns: vec![BoardColumn {
                name: "todo".into(),
                cards: vec![
                    Card {
                        number: 1,
                        title: "A".into(),
                        priority: crate::model::Priority::Medium,
                        labels: vec![],
                        assignee: None,
                        filename: "a.md".into(),
                        commit: None,
                        created: "2026-01-01".into(),
                        due_date: None,
                        status: "todo".into(),
                        category: None,
                        category_color: None,
                        done: false,
                        cycle: Some("Cycle 1".into()),
                        milestone: None,
                        blocked: None,
                        children: None,
                        parent: None,
                        depth: 0,
                        archived: false,
                        related: 0,
                    },
                    Card {
                        number: 2,
                        title: "B".into(),
                        priority: crate::model::Priority::Medium,
                        labels: vec![],
                        assignee: None,
                        filename: "b.md".into(),
                        commit: None,
                        created: "2026-01-01".into(),
                        due_date: None,
                        status: "todo".into(),
                        category: None,
                        category_color: None,
                        done: true,
                        cycle: Some("Cycle 1".into()),
                        milestone: None,
                        blocked: None,
                        children: None,
                        parent: None,
                        depth: 0,
                        archived: false,
                        related: 0,
                    },
                    Card {
                        number: 3,
                        title: "C".into(),
                        priority: crate::model::Priority::Medium,
                        labels: vec![],
                        assignee: None,
                        filename: "c.md".into(),
                        commit: None,
                        created: "2026-01-01".into(),
                        due_date: None,
                        status: "todo".into(),
                        category: None,
                        category_color: None,
                        done: false,
                        cycle: Some("Cycle 2".into()),
                        milestone: None,
                        blocked: None,
                        children: None,
                        parent: None,
                        depth: 0,
                        archived: false,
                        related: 0,
                    },
                ],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: Some("group:cycle".into()),
            hover: None,
            hover_col: None,
            hidden: vec![],
            show_mismatch: false,
        };
        terminal
            .draw(|f| {
                render(&board, f, f.area(), &None, None, BoardDisplay::default());
            })
            .unwrap();

        let buffer = terminal.backend().buffer();
        let mut lines = Vec::new();
        for y in 0..buffer.area.height {
            let line = (0..buffer.area.width)
                .map(|x| buffer[(x, y)].symbol())
                .collect::<String>();
            lines.push(line);
        }
        let rendered = lines.join("\n");
        assert!(rendered.contains("-- cycle: Cycle 1 (1/2 done, 50%) --"));
        assert!(rendered.contains("-- cycle: Cycle 2 (0/1 done, 0%) --"));
    }

    #[test]
    fn build_filtered_keeps_only_fuzzy_matches() {
        use crate::model::Issue;
        use crate::search::Corpus;

        let to_issue = |number: u32, title: &str| Issue {
            number,
            title: title.to_string(),
            status: crate::model::Status::new("todo"),
            labels: vec![],
            priority: crate::model::Priority::Medium,
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            relationships: vec![],
            related_issues: vec![],
            files: vec![],
            cycles: None,
            milestones: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            created: "2026-01-01".into(),
            type_: None,
            updated: "2026-01-01".into(),
            filename: format!("2026-01-01-{number}.md"),
            body: String::new(),
            history: crate::model::History::new(),
            has_retired_links_key: false,
            parent: None,
            extra_frontmatter: std::collections::BTreeMap::new(),
            archived: false,
            entered_at: None,
            source: None,
        };
        let corpus = Corpus {
            issues: vec![to_issue(1, "Fix login bug"), to_issue(2, "Polish exports")],
            texts: vec!["Fix login bug".to_string(), "Polish exports".to_string()],
        };
        let config = Config::default();
        let (_, resolution) = crate::workflow::active_resolution(&config);
        let board_config = config.default_config();

        let board = BoardState::build_filtered(
            board_config,
            &config,
            &corpus,
            "log",
            &StructuredFilter::default(),
            &resolution,
        );
        assert_eq!(board.columns.len(), board_config.columns.len());
        assert_eq!(board.column_cards(0).len(), 1);
        assert_eq!(board.column_cards(0)[0].title, "Fix login bug");
        assert_eq!(board.filter.as_deref(), Some("log"));

        let none = BoardState::build_filtered(
            board_config,
            &config,
            &corpus,
            "zzw",
            &StructuredFilter::default(),
            &resolution,
        );
        assert!(none.is_empty());

        let empty = BoardState::build_filtered(
            board_config,
            &config,
            &corpus,
            "",
            &StructuredFilter::default(),
            &resolution,
        );
        assert_eq!(empty.column_cards(0).len(), 2, "empty query keeps all");
        assert!(empty.filter.is_some());
    }

    #[test]
    fn build_filtered_group_cycle_keeps_original_titles() {
        use crate::model::Issue;
        use crate::search::Corpus;

        let issue = |number: u32, title: &str, status: &str, cycles: &[&str]| Issue {
            number,
            title: title.to_string(),
            status: crate::model::Status::new(status),
            labels: vec![],
            priority: crate::model::Priority::Medium,
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            relationships: vec![],
            related_issues: vec![],
            files: vec![],
            cycles: Some(cycles.iter().map(|c| (*c).to_string()).collect()),
            milestones: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            created: "2026-01-01".into(),
            type_: None,
            updated: "2026-01-01".into(),
            filename: format!("2026-01-01-{number}.md"),
            body: String::new(),
            history: crate::model::History::new(),
            has_retired_links_key: false,
            parent: None,
            extra_frontmatter: std::collections::BTreeMap::new(),
            archived: false,
            entered_at: None,
            source: None,
        };

        let corpus = Corpus {
            issues: vec![
                issue(1, "A", "todo", &["Cycle 1"]),
                issue(2, "B", "done", &["Cycle 1"]),
                issue(3, "C", "todo", &["Cycle 2"]),
            ],
            texts: vec![
                "cycle: Cycle 1\nstatus: todo".to_string(),
                "cycle: Cycle 1\nstatus: done".to_string(),
                "cycle: Cycle 2\nstatus: todo".to_string(),
            ],
        };

        let config = Config::default();
        let (_, resolution) = crate::workflow::active_resolution(&config);
        let board = BoardState::build_filtered(
            config.default_config(),
            &config,
            &corpus,
            "group:cycle",
            &StructuredFilter::default(),
            &resolution,
        );
        let titles: Vec<String> = board
            .columns
            .iter()
            .flat_map(|col| col.cards.iter().map(|c| c.title.clone()))
            .collect();
        assert!(titles.iter().any(|t| t == "A"));
        assert!(titles.iter().any(|t| t == "B"));
        assert!(titles.iter().any(|t| t == "C"));
    }

    #[test]
    fn group_footer_reports_done_progress() {
        let cards = vec![
            Card {
                number: 1,
                title: "A".into(),
                priority: crate::model::Priority::Medium,
                labels: vec![],
                assignee: None,
                filename: "a.md".into(),
                commit: None,
                created: "2026-01-01".into(),
                due_date: None,
                status: "todo".into(),
                category: None,
                category_color: None,
                done: false,
                cycle: Some("Cycle 1".into()),
                milestone: None,
                blocked: None,
                children: None,
                parent: None,
                depth: 0,
                archived: false,
                related: 0,
            },
            Card {
                number: 2,
                title: "B".into(),
                priority: crate::model::Priority::Medium,
                labels: vec![],
                assignee: None,
                filename: "b.md".into(),
                commit: None,
                created: "2026-01-01".into(),
                due_date: None,
                status: "done".into(),
                category: None,
                category_color: None,
                done: true,
                cycle: Some("Cycle 1".into()),
                milestone: None,
                blocked: None,
                children: None,
                parent: None,
                depth: 0,
                archived: false,
                related: 0,
            },
        ];
        let text = BoardState::group_footer(&cards, Some("cycle")).unwrap();
        assert!(text.contains("Cycle 1 1/2 50%"));
    }

    #[test]
    fn build_filtered_bare_number_matches_exact_issue_only() {
        use crate::model::Issue;
        use crate::search::Corpus;

        let to_issue = |number: u32, title: &str, status: &str| Issue {
            number,
            title: title.to_string(),
            status: crate::model::Status::new(status),
            labels: vec![],
            priority: crate::model::Priority::Medium,
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            relationships: vec![],
            related_issues: vec![],
            files: vec![],
            cycles: None,
            milestones: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            created: "2026-01-01".into(),
            type_: None,
            updated: "2026-01-01".into(),
            filename: format!("2026-01-01-{number}.md"),
            body: String::new(),
            history: crate::model::History::new(),
            has_retired_links_key: false,
            parent: None,
            extra_frontmatter: std::collections::BTreeMap::new(),
            archived: false,
            entered_at: None,
            source: None,
        };
        let corpus = Corpus {
            issues: vec![
                to_issue(55, "Concrete target", "todo"),
                to_issue(155, "Digit-rich title", "todo"),
                to_issue(3, "Login bug", "todo"),
            ],
            texts: vec![
                "Concrete target".to_string(),
                "Digit-rich title".to_string(),
                "Login bug".to_string(),
            ],
        };
        let config = Config::default();
        let (_, resolution) = crate::workflow::active_resolution(&config);
        let board_config = config.default_config();

        let exact = BoardState::build_filtered(
            board_config,
            &config,
            &corpus,
            "55",
            &StructuredFilter::default(),
            &resolution,
        );
        assert_eq!(exact.column_cards(0).len(), 1, "only issue 55 matches");
        assert_eq!(exact.column_cards(0)[0].title, "Concrete target");
        assert_eq!(
            exact.column_cards(0)[0].number,
            55,
            "issue 155's digit sequence must not qualify"
        );
        assert_eq!(exact.filter.as_deref(), Some("55"));

        // Number miss -> empty board.
        let miss = BoardState::build_filtered(
            board_config,
            &config,
            &corpus,
            "999",
            &StructuredFilter::default(),
            &resolution,
        );
        assert!(miss.is_empty(), "no issue 999 => zero matches");

        // Non-numeric query keeps fuzzy behavior (login finds issue 3 only).
        let fuzzy = BoardState::build_filtered(
            board_config,
            &config,
            &corpus,
            "login",
            &StructuredFilter::default(),
            &resolution,
        );
        assert_eq!(fuzzy.column_cards(0).len(), 1);
        assert_eq!(fuzzy.column_cards(0)[0].title, "Login bug");
    }

    #[test]
    fn build_filtered_mixed_query_keeps_fuzzy_not_number() {
        use crate::model::Issue;
        use crate::search::Corpus;

        let to_issue = |number: u32, title: &str| Issue {
            number,
            title: title.to_string(),
            status: crate::model::Status::new("todo"),
            labels: vec![],
            priority: crate::model::Priority::Medium,
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            relationships: vec![],
            related_issues: vec![],
            files: vec![],
            cycles: None,
            milestones: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            created: "2026-01-01".into(),
            type_: None,
            updated: "2026-01-01".into(),
            filename: format!("2026-01-01-{number}.md"),
            body: String::new(),
            history: crate::model::History::new(),
            has_retired_links_key: false,
            parent: None,
            extra_frontmatter: std::collections::BTreeMap::new(),
            archived: false,
            entered_at: None,
            source: None,
        };
        let corpus = Corpus {
            issues: vec![
                to_issue(55, "Concrete target"),
                to_issue(155, "Digit-rich title"),
            ],
            texts: vec![
                "Concrete target".to_string(),
                "Digit-rich title".to_string(),
            ],
        };
        let config = Config::default();
        let (_, resolution) = crate::workflow::active_resolution(&config);
        let board_config = config.default_config();

        // "55bug" is not a bare number: fuzzy path applies (no such text, so
        // zero matches rather than exact issue 55).
        let mixed = BoardState::build_filtered(
            board_config,
            &config,
            &corpus,
            "55bug",
            &StructuredFilter::default(),
            &resolution,
        );
        assert!(mixed.is_empty(), "mixed query is not an exact-number query");
    }

    #[test]
    fn build_filtered_number_composes_with_structured_filter_and() {
        use crate::model::Issue;
        use crate::search::Corpus;

        let cases = [
            (55u32, "Issue 55 todo", "todo"),
            (156u32, "Issue 156 todo", "todo"),
            (57u32, "Issue 57 done", "done"),
        ];
        let corpus = Corpus {
            issues: cases
                .iter()
                .map(|&(number, title, status)| Issue {
                    number,
                    title: title.to_string(),
                    status: crate::model::Status::new(status),
                    labels: vec![],
                    priority: crate::model::Priority::Medium,
                    assignee: None,
                    estimate: None,
                    commit: None,
                    gitlab_id: None,
                    linear_id: None,
                    mission: None,
                    task: None,
                    relationships: vec![],
                    related_issues: vec![],
                    files: vec![],
                    cycles: None,
                    milestones: None,
                    reviewer: None,
                    start_date: None,
                    due_date: None,
                    created: "2026-01-01".into(),
                    type_: None,
                    updated: "2026-01-01".into(),
                    filename: format!("2026-01-01-{}.md", number),
                    body: String::new(),
                    history: crate::model::History::new(),
                    has_retired_links_key: false,
                    parent: None,
                    extra_frontmatter: std::collections::BTreeMap::new(),
                    archived: false,
                    entered_at: None,
                    source: None,
                })
                .collect(),
            texts: cases
                .iter()
                .map(|(_, title, _)| title.to_string())
                .collect(),
        };
        let config = Config::default();
        let (_, resolution) = crate::workflow::active_resolution(&config);
        let board_config = config.default_config();
        let status_todo = StructuredFilter {
            status: Some("todo".to_string()),
            ..Default::default()
        };
        let status_done = StructuredFilter {
            status: Some("done".to_string()),
            ..Default::default()
        };

        // AND holds on the positive side: 55 must match number AND todo;
        // 156 matches the criteria but is dropped by the number gate.
        let matches = BoardState::build_filtered(
            board_config,
            &config,
            &corpus,
            "55",
            &status_todo,
            &resolution,
        );
        assert_eq!(matches.column_cards(0).len(), 1);
        assert_eq!(matches.column_cards(0)[0].title, "Issue 55 todo");

        // Requirement scenario: number matches but the criterion fails
        // (issue 55 is "todo" here) => board shows nothing.
        let done_criteria = BoardState::build_filtered(
            board_config,
            &config,
            &corpus,
            "55",
            &status_done,
            &resolution,
        );
        assert!(done_criteria.is_empty(), "criteria failure hides issue 55");
    }

    #[test]
    fn is_empty_true_only_with_no_cards_anywhere() {
        let board = BoardState {
            columns: vec![BoardColumn {
                name: "a".into(),
                cards: vec![],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            hidden: vec![],
            show_mismatch: true,
        };
        assert!(board.is_empty());

        let populated = BoardState {
            columns: vec![BoardColumn {
                name: "a".into(),
                cards: vec![Card {
                    number: 1,
                    title: "X".into(),
                    priority: crate::model::Priority::Medium,
                    labels: vec![],
                    assignee: None,
                    filename: "x.md".into(),
                    commit: None,
                    created: "2026-01-01".into(),
                    due_date: None,
                    status: "todo".into(),
                    category: None,
                    category_color: None,
                    done: false,
                    cycle: None,
                    milestone: None,
                    blocked: None,
                    children: None,
                    parent: None,
                    depth: 0,
                    archived: false,
                    related: 0,
                }],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            hidden: vec![],
            show_mismatch: true,
        };
        assert!(!populated.is_empty());
    }

    #[test]
    fn build_splits_hidden_columns_out_of_visible_surface() {
        use crate::config::{BoardConfiguration, Config};

        let mut config = Config::default();
        config.kanban.configurations.insert(
            "default".to_string(),
            BoardConfiguration {
                columns: vec!["todo".into(), "done".into()],
                hidden_columns: vec!["done".into()],
                ..BoardConfiguration::default()
            },
        );
        let store = crate::storage::Store::open(&config).unwrap();
        let board = BoardState::build(&store, config.default_config());
        assert_eq!(board.columns.len(), 1);
        assert_eq!(board.columns[0].name, "todo");
        assert_eq!(board.hidden.len(), 1);
        assert_eq!(board.hidden[0].name, "done");
        assert_eq!(board.total_cols(), 1);
    }

    #[test]
    fn move_left_skips_hidden_column() {
        let mut board = BoardState {
            columns: vec![BoardColumn {
                name: "visible-a".into(),
                cards: vec![],
            }],
            hidden: vec![BoardColumn {
                name: "hidden-b".into(),
                cards: vec![],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            show_mismatch: true,
        };
        board.move_left();
        assert_eq!(board.active_col, 0, "single visible column wraps to itself");
    }

    #[test]
    fn move_right_skips_hidden_column() {
        let mut board = BoardState {
            columns: vec![BoardColumn {
                name: "visible-a".into(),
                cards: vec![],
            }],
            hidden: vec![BoardColumn {
                name: "hidden-b".into(),
                cards: vec![],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            show_mismatch: true,
        };
        board.move_right();
        assert_eq!(board.active_col, 0, "single visible column wraps to itself");
    }

    #[test]
    fn all_columns_hidden_board_is_displayable_and_navigation_safe() {
        let mut board = BoardState {
            columns: vec![],
            hidden: vec![BoardColumn {
                name: "only-hidden".into(),
                cards: vec![],
            }],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            show_mismatch: false,
        };
        assert_eq!(board.total_cols(), 0);
        board.move_left();
        board.move_right();
        assert_eq!(board.active_col, 0, "zero-column board must not panic");
        let board2 = BoardState {
            columns: vec![],
            hidden: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            show_mismatch: false,
        };
        assert_eq!(board2.total_cols(), 0);
    }

    fn write_issue_md(
        dir: &std::path::Path,
        name: &str,
        number: u32,
        title: &str,
        status: &str,
        created: &str,
    ) {
        let contents = format!(
            "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"{status}\"\nlabels: []\npriority: \"medium\"\ncreated: \"{created}\"\nupdated: \"{created}\"\n---\n\nBody text."
        );
        std::fs::write(dir.join(name), contents).unwrap();
    }

    #[test]
    fn order_by_sort_desc_asc_none() {
        let mk = |created: &str| Card {
            number: 1,
            title: created.to_string(),
            priority: crate::model::Priority::Medium,
            labels: vec![],
            assignee: None,
            filename: "x.md".into(),
            commit: None,
            created: created.to_string(),
            due_date: None,
            status: "todo".into(),
            category: None,
            category_color: None,
            done: false,
            cycle: None,
            milestone: None,
            blocked: None,
            children: None,
            parent: None,
            depth: 0,
            archived: false,
            related: 0,
        };
        let dates =
            |cards: &[Card]| -> Vec<String> { cards.iter().map(|c| c.created.clone()).collect() };

        let mut cards = vec![mk("2026-01-01"), mk("2026-03-01"), mk("2026-02-01")];
        crate::config::OrderBy::CreatedAtDesc.sort(&mut cards);
        assert_eq!(dates(&cards), ["2026-03-01", "2026-02-01", "2026-01-01"]);

        let mut cards = vec![mk("2026-01-01"), mk("2026-03-01"), mk("2026-02-01")];
        crate::config::OrderBy::CreatedAtAsc.sort(&mut cards);
        assert_eq!(dates(&cards), ["2026-01-01", "2026-02-01", "2026-03-01"]);

        let mut cards = vec![mk("2026-03-01"), mk("2026-01-01")];
        crate::config::OrderBy::None.sort(&mut cards);
        assert_eq!(
            dates(&cards),
            ["2026-03-01", "2026-01-01"],
            "none is a no-op"
        );
    }

    #[test]
    fn build_orders_most_recent_first_by_default() {
        use crate::config::Config;
        use std::path::PathBuf;
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        std::fs::create_dir_all(&dir).unwrap();
        write_issue_md(&dir, "2026-01-01-old.md", 1, "old", "todo", "2026-01-01");
        write_issue_md(&dir, "2026-02-01-mid.md", 2, "mid", "todo", "2026-02-01");
        write_issue_md(&dir, "2026-03-01-new.md", 3, "new", "todo", "2026-03-01");
        let config = Config {
            issues_dir: PathBuf::from(&dir),
            ..Config::default()
        };
        let store = crate::storage::Store::open(&config).unwrap();
        let board = BoardState::build(&store, config.default_config());
        let titles: Vec<&str> = board
            .column_cards(0)
            .iter()
            .map(|c| c.title.as_str())
            .collect();
        assert_eq!(titles, ["new", "mid", "old"], "default desc: newest first");
    }

    #[test]
    fn build_applies_created_at_asc_and_none() {
        use crate::config::OrderBy;
        use std::path::PathBuf;
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        std::fs::create_dir_all(&dir).unwrap();
        write_issue_md(&dir, "2026-01-01-old.md", 1, "old", "todo", "2026-01-01");
        write_issue_md(&dir, "2026-02-01-mid.md", 2, "mid", "todo", "2026-02-01");
        write_issue_md(&dir, "2026-03-01-new.md", 3, "new", "todo", "2026-03-01");
        let config = crate::config::Config {
            issues_dir: PathBuf::from(&dir),
            ..crate::config::Config::default()
        };
        let store = crate::storage::Store::open(&config).unwrap();

        let mut cfg_asc = config.clone();
        cfg_asc
            .kanban
            .configurations
            .get_mut("default")
            .unwrap()
            .order_by = OrderBy::CreatedAtAsc;
        let board_asc = BoardState::build(&store, cfg_asc.default_config());
        let titles: Vec<&str> = board_asc
            .column_cards(0)
            .iter()
            .map(|c| c.title.as_str())
            .collect();
        assert_eq!(titles, ["old", "mid", "new"]);

        let mut cfg_none = config;
        cfg_none
            .kanban
            .configurations
            .get_mut("default")
            .unwrap()
            .order_by = OrderBy::None;
        let board_none = BoardState::build(&store, cfg_none.default_config());
        let titles: Vec<&str> = board_none
            .column_cards(0)
            .iter()
            .map(|c| c.title.as_str())
            .collect();
        assert_eq!(
            titles,
            ["old", "mid", "new"],
            "none keeps the store's filename-ascending order"
        );
    }

    #[test]
    fn build_applies_sparse_manual_card_order_when_present() {
        use crate::config::Config;
        use std::path::PathBuf;
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        std::fs::create_dir_all(&dir).unwrap();
        write_issue_md(&dir, "2026-01-01-old.md", 1, "old", "todo", "2026-01-01");
        write_issue_md(&dir, "2026-02-01-mid.md", 2, "mid", "todo", "2026-02-01");
        write_issue_md(&dir, "2026-03-01-new.md", 3, "new", "todo", "2026-03-01");
        let config = Config {
            issues_dir: PathBuf::from(&dir),
            ..Config::default()
        };
        let store = crate::storage::Store::open(&config).unwrap();
        let mut board_cfg = config.default_config().clone();
        board_cfg.card_order = vec!["2026-02-01-mid.md".into(), "2026-03-01-new.md".into()];
        let board = BoardState::build(&store, &board_cfg);
        let titles: Vec<&str> = board
            .column_cards(0)
            .iter()
            .map(|c| c.title.as_str())
            .collect();
        assert_eq!(titles, ["mid", "new", "old"], "manual order wins");
    }

    #[test]
    fn sparse_card_order_only_returns_changed_cards() {
        use crate::config::Config;
        use std::path::PathBuf;

        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        std::fs::create_dir_all(&dir).unwrap();
        write_issue_md(&dir, "2026-01-01-old.md", 1, "old", "todo", "2026-01-01");
        write_issue_md(&dir, "2026-02-01-mid.md", 2, "mid", "todo", "2026-02-01");
        write_issue_md(&dir, "2026-03-01-new.md", 3, "new", "todo", "2026-03-01");
        let config = Config {
            issues_dir: PathBuf::from(&dir),
            ..Config::default()
        };
        let store = crate::storage::Store::open(&config).unwrap();
        let board_cfg = config.default_config().clone();
        let mut cards = BoardState::build(&store, &board_cfg)
            .column_cards(0)
            .to_vec();
        cards.swap(0, 1);
        let sparse = sparse_card_order(&board_cfg, &cards);
        assert_eq!(sparse, ["2026-02-01-mid.md", "2026-03-01-new.md"]);
    }

    #[test]
    fn build_filtered_applies_order_by() {
        use crate::model::Issue;
        use crate::search::{Corpus, StructuredFilter};

        let to_issue = |number: u32, title: &str, created: &str| Issue {
            number,
            title: title.to_string(),
            status: crate::model::Status::new("todo"),
            labels: vec![],
            priority: crate::model::Priority::Medium,
            assignee: None,
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            relationships: vec![],
            related_issues: vec![],
            files: vec![],
            cycles: None,
            milestones: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            created: created.into(),
            type_: None,
            updated: "2026-01-01".into(),
            filename: format!("2026-01-01-{number}.md"),
            body: String::new(),
            history: crate::model::History::new(),
            has_retired_links_key: false,
            parent: None,
            extra_frontmatter: std::collections::BTreeMap::new(),
            archived: false,
            entered_at: None,
            source: None,
        };
        let corpus = Corpus {
            issues: vec![
                to_issue(1, "old", "2026-01-01"),
                to_issue(2, "new", "2026-03-01"),
                to_issue(3, "mid", "2026-02-01"),
            ],
            texts: vec!["old".into(), "new".into(), "mid".into()],
        };
        let config = crate::config::Config::default();
        let (_, resolution) = crate::workflow::active_resolution(&config);
        let board = BoardState::build_filtered(
            config.default_config(),
            &config,
            &corpus,
            "",
            &StructuredFilter::default(),
            &resolution,
        );
        let titles: Vec<&str> = board
            .column_cards(0)
            .iter()
            .map(|c| c.title.as_str())
            .collect();
        assert_eq!(
            titles,
            ["new", "mid", "old"],
            "default desc applies to filtered results too"
        );
    }

    /// A card for the tree-ordering tests: only the fields the ordering and the
    /// renderer read are spelled out.
    fn tree_card(number: u32, parent: Option<u32>) -> Card {
        Card {
            number,
            title: format!("Issue {number}"),
            priority: Priority::Medium,
            labels: vec![],
            assignee: None,
            filename: format!("{number}.md"),
            commit: None,
            created: "2026-01-01".into(),
            due_date: None,
            status: "todo".into(),
            category: None,
            category_color: None,
            done: false,
            cycle: None,
            milestone: None,
            blocked: None,
            children: None,
            parent,
            depth: 0,
            archived: false,
            related: 0,
        }
    }

    #[test]
    fn nest_children_places_a_child_after_its_parent() {
        let mut cards = vec![
            tree_card(2, Some(1)),
            tree_card(1, None),
            tree_card(3, None),
        ];
        nest_children(&mut cards);
        let shape: Vec<(u32, u8)> = cards.iter().map(|c| (c.number, c.depth)).collect();
        assert_eq!(
            shape,
            vec![(1, 0), (2, 1), (3, 0)],
            "the child moves up under its parent and is marked depth 1"
        );
    }

    #[test]
    fn nest_children_keeps_adopted_siblings_in_their_existing_order() {
        let mut cards = vec![
            tree_card(1, None),
            tree_card(3, Some(1)),
            tree_card(2, Some(1)),
        ];
        nest_children(&mut cards);
        let shape: Vec<(u32, u8)> = cards.iter().map(|c| (c.number, c.depth)).collect();
        assert_eq!(shape, vec![(1, 0), (3, 1), (2, 1)]);
    }

    #[test]
    fn nest_children_does_not_nest_a_grandchild() {
        // #2 is a child of #1; #3 is a child of #2. Only one level is shown, so #3
        // stays top level instead of stacking under the child.
        let mut cards = vec![
            tree_card(1, None),
            tree_card(2, Some(1)),
            tree_card(3, Some(2)),
        ];
        nest_children(&mut cards);
        let shape: Vec<(u32, u8)> = cards.iter().map(|c| (c.number, c.depth)).collect();
        assert_eq!(shape, vec![(1, 0), (2, 1), (3, 0)]);
    }

    #[test]
    fn nest_children_leaves_a_child_whose_parent_is_in_another_column() {
        // #1 is not in this column, so #2 keeps its position and `depth`.
        let mut cards = vec![tree_card(2, Some(1)), tree_card(5, None)];
        nest_children(&mut cards);
        let shape: Vec<(u32, u8)> = cards.iter().map(|c| (c.number, c.depth)).collect();
        assert_eq!(shape, vec![(2, 0), (5, 0)]);
    }

    #[test]
    fn nest_children_keeps_every_card_exactly_once() {
        let mut cards = vec![
            tree_card(4, None),
            tree_card(3, Some(1)),
            tree_card(1, None),
            tree_card(2, Some(1)),
        ];
        nest_children(&mut cards);
        let mut numbers: Vec<u32> = cards.iter().map(|c| c.number).collect();
        numbers.sort_unstable();
        assert_eq!(
            numbers,
            vec![1, 2, 3, 4],
            "no card is duplicated or dropped"
        );
    }

    #[test]
    fn render_indents_a_sub_issue_without_changing_its_line_count() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let width = 80u16;
        let height = 30u16;
        let mut child = tree_card(2, Some(1));
        child.title = "a sub-issue whose deliberately long title wraps across more \
                       than a single rendered row inside the column"
            .into();
        child.depth = 1;
        let parent = tree_card(1, None);

        let mut flat_child = child.clone();
        flat_child.depth = 0;
        assert_eq!(
            widgets::card_line_count(&child, width as usize, true, 3),
            widgets::card_line_count(&flat_child, width as usize, true, 3),
            "the indent must not change the card's rendered line count"
        );

        let board = BoardState {
            columns: vec![BoardColumn {
                name: "todo".into(),
                cards: vec![parent, child],
            }],
            hidden: vec![],
            mismatch: BoardColumn {
                name: "Mismatched".into(),
                cards: vec![],
            },
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
            show_mismatch: false,
        };
        let display = BoardDisplay {
            wrap_titles: true,
            title_lines: 3,
        };
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| {
                render(&board, f, f.area(), &None, None, display);
            })
            .unwrap();
        let buffer = terminal.backend().buffer();
        let row = |y: u16| -> String { (0..width).map(|x| buffer[(x, y)].symbol()).collect() };

        assert!(
            row(1).contains("#1"),
            "the parent draws first: {:?}",
            row(1)
        );
        assert!(!row(1).contains('â””'), "a top-level card is not indented");
        assert!(
            row(2).contains("â”” #2"),
            "the sub-issue draws indented with a tree marker: {:?}",
            row(2)
        );

        // Hit-testing resolves the rows the renderer drew to the same card
        // indices: row 1 is card 0 (the parent), row 2 is card 1 (the child).
        let area = Rect::new(0, 0, width, height);
        assert_eq!(
            board.hit_test(area, display, false, 3, 1),
            Some(HitTarget::Card { col: 0, row: 0 })
        );
        assert_eq!(
            board.hit_test(area, display, false, 3, 2),
            Some(HitTarget::Card { col: 0, row: 1 })
        );
    }

    /// Write an issue with an optional `parent:` frontmatter line, for the
    /// build-time tree tests.
    fn write_issue_with_parent_md(
        dir: &std::path::Path,
        name: &str,
        number: u32,
        title: &str,
        status: &str,
        created: &str,
        parent: Option<u32>,
    ) {
        let parent_line = parent.map(|p| format!("parent: {p}\n")).unwrap_or_default();
        let contents = format!(
            "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"{status}\"\nlabels: []\npriority: \"medium\"\ncreated: \"{created}\"\nupdated: \"{created}\"\n{parent_line}---\n\nBody text."
        );
        std::fs::write(dir.join(name), contents).unwrap();
    }

    #[test]
    fn build_with_show_children_nests_a_sub_issue_below_its_parent() {
        use crate::config::Config;
        use std::path::PathBuf;

        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        std::fs::create_dir_all(&dir).unwrap();
        write_issue_with_parent_md(
            &dir,
            "2026-01-01-parent.md",
            1,
            "parent",
            "todo",
            "2026-01-01",
            None,
        );
        write_issue_with_parent_md(
            &dir,
            "2026-01-02-child.md",
            2,
            "child",
            "todo",
            "2026-01-02",
            Some(1),
        );
        let config = Config {
            issues_dir: PathBuf::from(&dir),
            ..Config::default()
        };
        let store = crate::storage::Store::open(&config).unwrap();
        let board_cfg = config.default_config().clone();

        // The default order puts the newer child before the older parent, so the
        // toggle has to reorder them.
        let flat = BoardState::build(&store, &board_cfg);
        let flat_shape: Vec<(u32, u8)> = flat
            .column_cards(0)
            .iter()
            .map(|c| (c.number, c.depth))
            .collect();
        assert_eq!(flat_shape, vec![(2, 0), (1, 0)]);

        let tree = BoardState::build_with(&store, &board_cfg, false, true);
        let tree_shape: Vec<(u32, u8)> = tree
            .column_cards(0)
            .iter()
            .map(|c| (c.number, c.depth))
            .collect();
        assert_eq!(
            tree_shape,
            vec![(1, 0), (2, 1)],
            "the sub-issue follows its parent, one level deep"
        );
        assert_eq!(tree.column_cards(0)[1].parent, Some(1));
    }

    /// `build_from_issues` is the single build path: for the same store it must
    /// produce exactly the board `build_with` produces (issue #10 follow-up).
    #[test]
    fn build_from_issues_matches_build_with() {
        use crate::config::Config;

        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        std::fs::create_dir_all(&dir).unwrap();
        write_issue_with_parent_md(
            &dir,
            "2026-01-01-parent.md",
            1,
            "parent",
            "todo",
            "2026-01-01",
            None,
        );
        write_issue_with_parent_md(
            &dir,
            "2026-01-02-child.md",
            2,
            "child",
            "todo",
            "2026-01-02",
            Some(1),
        );
        write_issue_md(
            &dir,
            "2026-01-03-other.md",
            3,
            "other",
            "in progress",
            "2026-01-03",
        );
        let config = Config {
            issues_dir: dir.clone(),
            ..Config::default()
        };
        let store = crate::storage::Store::open(&config).unwrap();
        let board_cfg = config.default_config().clone();

        let shape = |state: &BoardState| -> Vec<(String, Vec<(String, u8)>)> {
            state
                .columns
                .iter()
                .chain(state.hidden.iter())
                .chain(std::iter::once(&state.mismatch))
                .map(|col| {
                    (
                        col.name.clone(),
                        col.cards
                            .iter()
                            .map(|c| (c.filename.clone(), c.depth))
                            .collect(),
                    )
                })
                .collect()
        };

        for show_children in [false, true] {
            let from_store = BoardState::build_with(&store, &board_cfg, false, show_children);
            let issues = store.list().unwrap();
            let resolution = BoardState::resolution_for(&store, &board_cfg);
            let from_issues = BoardState::build_from_issues(
                &issues,
                &board_cfg,
                &config,
                &resolution,
                show_children,
            );
            assert_eq!(
                shape(&from_issues),
                shape(&from_store),
                "show_children={show_children}"
            );
        }
    }
}