mirador 1.22.2

An opinionated personal dashboard for your terminal: world clocks, a calendar, weather, tasks, notes, a market watchlist, and live CPU and network graphs.
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
//! The to-do panel: a full create/read/update/delete task list.
//!
//! Every mutation is written straight through to disk, so the task file on disk
//! and the list on screen never disagree. Save failures surface in the panel's
//! status line rather than being swallowed.

use jiff::civil::Date;
use ratatui::Frame;
use ratatui::crossterm::event::{
    KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use ratatui::layout::{Constraint, Layout, Position, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, BorderType, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap,
};

use crate::config::TodoConfig;
use crate::dateinput::parse_due;
use crate::frame::{Binding, centred};
use crate::grid::{Column, Grid, WrapSource, fitted_rows};
use crate::keymap::{KeysConfig, Meta, PanelKeymap};
use crate::panel::{KeyOutcome, Panel, RenderContext};
use crate::task::{DueState, Priority, SortMode, Task, TaskStore};
use crate::textfield::TextField;
use crate::theme::Theme;

/// The three tallies the header and the frame counter show.
///
/// Cached rather than recomputed, because they were four separate full scans of
/// the store — three here and one in `counter()` — with `jiff` date arithmetic
/// per task, and they run on **every frame**. `title()` and `counter()` are
/// called by the shell's render loop outside `render()`, so no early-out
/// protects them and a narrow or hidden panel paid the same price as a visible
/// one. They also grew without bound: the store never drops completed tasks.
///
/// Now one pass, recomputed only where the answer can change — a store
/// mutation, or the date rolling over at midnight, both of which already go
/// through `refresh_view`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct Counts {
    open: usize,
    overdue: usize,
    today: usize,
}

impl Counts {
    fn of(tasks: &[Task], today: Date) -> Self {
        let mut counts = Self::default();
        for task in tasks.iter().filter(|t| !t.done) {
            counts.open += 1;
            match task.due_state(today) {
                DueState::Overdue(_) => counts.overdue += 1,
                DueState::Today => counts.today += 1,
                _ => {}
            }
        }
        counts
    }
}

/// What the list's keys do. The form, the filter and the delete question
/// keep their own keys: they capture input, and a key moved there could
/// never be typed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TodoAction {
    Add,
    Edit,
    Done,
    Delete,
    Up,
    Down,
    First,
    Last,
    PageUp,
    PageDown,
    PriorityNext,
    PriorityPrevious,
    Sort,
    Completed,
    Filter,
    ShowPath,
}

const NONE: KeyModifiers = KeyModifiers::NONE;

/// Every key the list responds to, under `[todo.keys]`.
///
/// The hints — help overlay, status bar and border at once — are derived
/// from this, so a key the list reads is a key it advertises. The primary
/// entries come first and are what fits in the frame hint, so they are
/// ordered by how often they are used, not alphabetically.
pub const ACTIONS: &[Meta<TodoAction>] = &[
    Meta {
        action: TodoAction::Add,
        name: "add",
        defaults: &[(KeyCode::Char('a'), NONE), (KeyCode::Char('n'), NONE)],
        label: "add",
        primary: true,
        joins: false,
        about: "add a task",
    },
    Meta {
        action: TodoAction::Edit,
        name: "edit",
        defaults: &[(KeyCode::Enter, NONE), (KeyCode::Char('e'), NONE)],
        label: "edit",
        primary: true,
        joins: false,
        about: "edit the selected task",
    },
    Meta {
        action: TodoAction::Done,
        name: "done",
        defaults: &[(KeyCode::Char(' '), NONE)],
        label: "done",
        primary: true,
        joins: false,
        about: "mark the selected task done, or not",
    },
    Meta {
        action: TodoAction::Delete,
        name: "delete",
        defaults: &[(KeyCode::Char('d'), NONE)],
        label: "delete",
        primary: true,
        joins: false,
        about: "delete the selected task, after asking",
    },
    Meta {
        action: TodoAction::Up,
        name: "up",
        defaults: &[(KeyCode::Up, NONE), (KeyCode::Char('k'), NONE)],
        label: "move selection",
        primary: false,
        joins: false,
        about: "select the task above",
    },
    Meta {
        action: TodoAction::Down,
        name: "down",
        defaults: &[(KeyCode::Down, NONE), (KeyCode::Char('j'), NONE)],
        label: "move selection",
        primary: false,
        joins: true,
        about: "select the task below",
    },
    Meta {
        action: TodoAction::First,
        name: "first",
        defaults: &[(KeyCode::Char('g'), NONE), (KeyCode::Home, NONE)],
        label: "first",
        primary: false,
        joins: false,
        about: "select the first task",
    },
    Meta {
        action: TodoAction::Last,
        name: "last",
        defaults: &[(KeyCode::Char('G'), NONE), (KeyCode::End, NONE)],
        label: "last",
        primary: false,
        joins: true,
        about: "select the last task",
    },
    Meta {
        action: TodoAction::PageUp,
        name: "page_up",
        defaults: &[(KeyCode::PageUp, NONE)],
        label: "move ten rows",
        primary: false,
        joins: false,
        about: "select ten tasks up",
    },
    Meta {
        action: TodoAction::PageDown,
        name: "page_down",
        defaults: &[(KeyCode::PageDown, NONE)],
        label: "move ten rows",
        primary: false,
        joins: true,
        about: "select ten tasks down",
    },
    Meta {
        action: TodoAction::PriorityNext,
        name: "priority_next",
        defaults: &[(KeyCode::Char('p'), NONE)],
        label: "cycle priority",
        primary: false,
        joins: false,
        about: "lower the task's priority, wrapping to high",
    },
    Meta {
        action: TodoAction::PriorityPrevious,
        name: "priority_previous",
        defaults: &[(KeyCode::Char('P'), NONE)],
        label: "cycle priority",
        primary: false,
        joins: true,
        about: "raise the task's priority, wrapping to none",
    },
    Meta {
        action: TodoAction::Sort,
        name: "sort",
        defaults: &[(KeyCode::Char('s'), NONE)],
        label: "cycle sort",
        primary: false,
        joins: false,
        about: "sort by the next order",
    },
    Meta {
        action: TodoAction::Completed,
        name: "completed",
        defaults: &[(KeyCode::Char('c'), NONE)],
        label: "show completed",
        primary: false,
        joins: false,
        about: "show or hide completed tasks",
    },
    Meta {
        action: TodoAction::Filter,
        name: "filter",
        defaults: &[(KeyCode::Char('/'), NONE)],
        label: "filter",
        primary: false,
        joins: false,
        about: "filter the list by text",
    },
    Meta {
        action: TodoAction::ShowPath,
        name: "show_path",
        defaults: &[(KeyCode::Char('o'), NONE)],
        label: "show file path",
        primary: false,
        joins: false,
        about: "show where the tasks are saved",
    },
];

/// Hints for the list's keys that no table moves.
const FIXED: &[Binding] = &[Binding::extra("Esc", "clear filter")];

/// `[todo.keys]` laid over [`ACTIONS`], or why it cannot be.
pub fn keymap(keys: &KeysConfig) -> Result<PanelKeymap<TodoAction>, String> {
    PanelKeymap::new("todo", ACTIONS, keys).map(|map| map.with_fixed(FIXED))
}

/// What the panel builds itself with; see [`PanelKeymap::or_defaults`].
fn list_keys(keys: &KeysConfig) -> PanelKeymap<TodoAction> {
    PanelKeymap::or_defaults("todo", ACTIONS, keys).with_fixed(FIXED)
}

/// Columns of the task list.
///
/// `done` and `pri` are glyph columns, but they still carry names: without a
/// header the three-cell gauge is a guess.
pub(crate) const COLUMNS: &[Column] = &[
    Column::fixed("done", 4),
    Column::fixed("pri", 3),
    Column::flex("task", 1),
    Column::fixed("tags", 16).drops_below(58),
    Column::fixed("due", 12).right().drops_below(40),
];

/// Fields in the edit form, in Tab order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Field {
    Title,
    Notes,
    Due,
    Priority,
    Tags,
}

impl Field {
    const ORDER: [Self; 5] = [
        Self::Title,
        Self::Notes,
        Self::Due,
        Self::Priority,
        Self::Tags,
    ];

    fn next(self) -> Self {
        let i = Self::ORDER.iter().position(|f| *f == self).unwrap_or(0);
        Self::ORDER[(i + 1) % Self::ORDER.len()]
    }

    fn prev(self) -> Self {
        let i = Self::ORDER.iter().position(|f| *f == self).unwrap_or(0);
        Self::ORDER[(i + Self::ORDER.len() - 1) % Self::ORDER.len()]
    }

    fn label(self) -> &'static str {
        match self {
            Self::Title => "Title",
            Self::Notes => "Notes",
            Self::Due => "Due",
            Self::Priority => "Priority",
            Self::Tags => "Tags",
        }
    }
}

/// State of the add/edit form.
#[derive(Debug)]
struct EditForm {
    /// `None` when creating a new task.
    id: Option<u64>,
    field: Field,
    title: TextField,
    notes: TextField,
    due: TextField,
    tags: TextField,
    priority: Priority,
    /// Validation failure from the last save attempt.
    error: Option<String>,
}

impl EditForm {
    /// A blank form for a new task.
    fn blank() -> Self {
        Self {
            id: None,
            field: Field::Title,
            title: TextField::new(),
            notes: TextField::new(),
            due: TextField::new(),
            tags: TextField::new(),
            priority: Priority::default(),
            error: None,
        }
    }

    /// A form pre-filled from an existing task.
    fn from_task(task: &Task) -> Self {
        Self {
            id: Some(task.id),
            field: Field::Title,
            title: TextField::with_value(&task.title),
            notes: TextField::with_value(task.notes.clone().unwrap_or_default()),
            due: TextField::with_value(task.due.map(|d| d.to_string()).unwrap_or_default()),
            tags: TextField::with_value(task.tags.join(", ")),
            priority: task.priority,
            error: None,
        }
    }

    fn active_text_field(&mut self) -> Option<&mut TextField> {
        match self.field {
            Field::Title => Some(&mut self.title),
            Field::Notes => Some(&mut self.notes),
            Field::Due => Some(&mut self.due),
            Field::Tags => Some(&mut self.tags),
            Field::Priority => None,
        }
    }

    fn text_field(&self, field: Field) -> Option<&TextField> {
        match field {
            Field::Title => Some(&self.title),
            Field::Notes => Some(&self.notes),
            Field::Due => Some(&self.due),
            Field::Tags => Some(&self.tags),
            Field::Priority => None,
        }
    }
}

/// What the panel is currently doing.
#[derive(Debug)]
enum Mode {
    /// Browsing the list.
    List,
    /// Typing into the filter box, with the tags it offers while the box is
    /// blank — gathered once on the way in, since nothing can add a tag while
    /// a filter is being typed, rather than from every task on every frame.
    Filter(TextField, Vec<String>),
    /// Adding or editing a task.
    Edit(Box<EditForm>),
    /// Confirming a deletion.
    ConfirmDelete { id: u64, title: String },
}

/// The to-do panel.
#[derive(Debug)]
pub struct TodoPanel {
    store: TaskStore,
    config: TodoConfig,
    /// `[todo.keys]` over the defaults, for the list.
    keys: PanelKeymap<TodoAction>,
    sort: SortMode,
    show_completed: bool,
    filter: String,
    mode: Mode,
    /// Task ids in display order, recomputed whenever the list changes.
    view: Vec<u64>,
    /// The header and counter tallies, recomputed alongside `view`.
    counts: Counts,
    /// Tasks the completed toggle would show but the horizon hides, so the
    /// summary can reconcile the border's count with the rows and an empty
    /// list can say why it is empty. Always 0 while a filter is active, since
    /// a filter searches past the horizon.
    beyond: usize,
    list_state: ListState,
    /// Transient message with a severity flag.
    status: Option<(String, bool)>,
    today: Date,
    /// Rectangle the task rows were last drawn into, so a click can be turned
    /// back into the row it landed on. `None` until the first draw, and while
    /// the list is empty — there is no row to hit in either case.
    list_area: Option<Rect>,
    /// Events waiting to be drained by the watch log.
    pending: Vec<crate::watch::Event>,
}

impl TodoPanel {
    /// Build the panel, loading tasks from `path`.
    pub fn new(config: TodoConfig, path: std::path::PathBuf) -> anyhow::Result<Self> {
        let today = jiff::Zoned::now().date();
        let store = TaskStore::load_or_seed(path, today)?;
        let sort = config.sort.parse().unwrap_or_default();
        let show_completed = config.show_completed;

        let mut panel = Self {
            store,
            keys: list_keys(&config.keys),
            config,
            sort,
            show_completed,
            filter: String::new(),
            mode: Mode::List,
            view: Vec::new(),
            counts: Counts::default(),
            list_state: ListState::default(),
            status: None,
            beyond: 0,
            today,
            list_area: None,
            pending: Vec::new(),
        };
        panel.refresh_view();
        Ok(panel)
    }

    /// Recompute the ordered id list, keeping the selection on the same task
    /// where possible so that toggling a filter does not move the cursor.
    ///
    /// An active filter searches past the horizon. It is how a task is looked
    /// up by name, so a task saved with a due date further out than meant has
    /// to be findable, and then editable and deletable, before the day it
    /// would come into range on its own.
    fn refresh_view(&mut self) {
        let previously_selected = self.selected_id();
        let horizon = if self.filter.is_empty() {
            self.config.horizon_days
        } else {
            0
        };
        self.view = self.store.view(
            self.sort,
            self.show_completed,
            &self.filter,
            horizon,
            self.today,
        );
        self.counts = Counts::of(self.store.tasks(), self.today);
        self.beyond = if horizon == 0 {
            0
        } else {
            self.store
                .view(self.sort, self.show_completed, &self.filter, 0, self.today)
                .len()
                .saturating_sub(self.view.len())
        };

        let index = previously_selected
            .and_then(|id| self.view.iter().position(|v| *v == id))
            .unwrap_or_else(|| {
                self.list_state
                    .selected()
                    .unwrap_or(0)
                    .min(self.view.len().saturating_sub(1))
            });

        if self.view.is_empty() {
            self.list_state.select(None);
        } else {
            self.list_state.select(Some(index.min(self.view.len() - 1)));
        }
    }

    /// The id of the highlighted task, if any.
    fn selected_id(&self) -> Option<u64> {
        self.list_state
            .selected()
            .and_then(|i| self.view.get(i))
            .copied()
    }

    /// Move the selection `n` rows down, stopping at the last task.
    fn select_down(&mut self, n: usize) {
        crate::selection::down(&mut self.list_state, n, self.view.len());
    }

    /// Move the selection `n` rows up, stopping at the first task.
    fn select_up(&mut self, n: usize) {
        crate::selection::up(&mut self.list_state, n, self.view.len());
    }

    /// Persist and report the outcome in the status line.
    fn persist(&mut self) {
        self.store.save_reporting();
        if let Some(err) = self.store.last_error.clone() {
            self.status = Some((format!("save failed: {err}"), true));
        }
    }

    fn set_status(&mut self, message: impl Into<String>) {
        self.status = Some((message.into(), false));
    }

    /// Turn form contents into a task, or explain why it cannot be.
    fn commit_form(&mut self) -> Result<(), String> {
        let Mode::Edit(form) = &mut self.mode else {
            return Ok(());
        };

        if form.title.is_blank() {
            return Err("a task needs a title".into());
        }

        let due = parse_due(form.due.value(), self.today).map_err(|e| e.to_string())?;
        // A task saved past the horizon leaves the unfiltered list at once;
        // saying so is the difference between "it is hidden" and "it was lost".
        let hidden = if crate::task::beyond_horizon(due, self.today, self.config.horizon_days) {
            format!(", due beyond the {}-day horizon", self.config.horizon_days)
        } else {
            String::new()
        };

        let notes = {
            let n = form.notes.trimmed();
            if n.is_empty() {
                None
            } else {
                Some(n.to_string())
            }
        };

        let tags: Vec<String> = form
            .tags
            .value()
            .split([',', ' '])
            .map(|t| t.trim().trim_start_matches('#'))
            .filter(|t| !t.is_empty())
            .map(str::to_string)
            .collect();

        let title = form.title.trimmed().to_string();
        let priority = form.priority;
        let id = form.id;

        if let Some(id) = id {
            let Some(existing) = self.store.get(id) else {
                return Err("that task no longer exists".into());
            };
            let mut updated = existing.clone();
            updated.title = title;
            updated.notes = notes;
            updated.due = due;
            updated.priority = priority;
            updated.tags = tags;
            self.store.update(updated);
            self.set_status(format!("task updated{hidden}"));
        } else {
            let mut task = Task::new(0, title, self.today);
            task.notes = notes;
            task.due = due;
            task.priority = priority;
            task.tags = tags;
            let new_id = self.store.add(task);
            self.set_status(format!("task added{hidden}"));
            self.mode = Mode::List;
            self.refresh_view();
            if let Some(pos) = self.view.iter().position(|v| *v == new_id) {
                self.list_state.select(Some(pos));
            }
            self.persist();
            return Ok(());
        }

        self.mode = Mode::List;
        self.refresh_view();
        self.persist();
        Ok(())
    }

    /// Keys handled while browsing the list.
    fn handle_list_key(&mut self, key: KeyEvent) -> KeyOutcome {
        // Esc is not in the map: it always backs out, here of a filter.
        if key.code == KeyCode::Esc {
            if self.filter.is_empty() {
                return KeyOutcome::Ignored;
            }
            self.filter.clear();
            self.set_status("filter cleared");
            self.refresh_view();
            return KeyOutcome::Consumed;
        }
        let Some(action) = self.keys.action(key) else {
            return KeyOutcome::Ignored;
        };
        match action {
            TodoAction::Down => self.select_down(1),
            TodoAction::Up => self.select_up(1),
            TodoAction::First => self.select_up(usize::MAX),
            TodoAction::Last => self.select_down(usize::MAX),
            TodoAction::PageDown => self.select_down(10),
            TodoAction::PageUp => self.select_up(10),

            TodoAction::Done => {
                let Some(id) = self.selected_id() else {
                    return KeyOutcome::Consumed;
                };
                let today = self.today;
                self.store.with_task(id, |t| t.toggle_done(today));
                let now_done = self.store.get(id).is_some_and(|t| t.done);
                self.set_status(if now_done { "completed" } else { "reopened" });
                self.refresh_view();
                self.persist();
            }

            TodoAction::Add => {
                self.mode = Mode::Edit(Box::new(EditForm::blank()));
            }

            // Enter means "go inside", as it does everywhere else: it opens the
            // task for editing. It used to toggle done, which made the most
            // reflexive key in the list a destructive-looking state change on
            // the wrong row. Toggling is `space`, which reads as a checkbox.
            TodoAction::Edit => {
                if let Some(task) = self.selected_id().and_then(|id| self.store.get(id)) {
                    self.mode = Mode::Edit(Box::new(EditForm::from_task(task)));
                }
            }

            TodoAction::Delete => {
                if let Some(task) = self.selected_id().and_then(|id| self.store.get(id)) {
                    self.mode = Mode::ConfirmDelete {
                        id: task.id,
                        title: task.title.clone(),
                    };
                }
            }

            // One walks priority down, the other back up.
            TodoAction::PriorityNext | TodoAction::PriorityPrevious => {
                let Some(id) = self.selected_id() else {
                    return KeyOutcome::Consumed;
                };
                self.store.with_task(id, |t| {
                    t.priority = if action == TodoAction::PriorityPrevious {
                        t.priority.prev()
                    } else {
                        t.priority.next()
                    };
                });
                let label = self
                    .store
                    .get(id)
                    .map_or(String::new(), |t| t.priority.to_string());
                self.set_status(format!("priority: {label}"));
                self.refresh_view();
                self.persist();
            }

            TodoAction::Sort => {
                self.sort = self.sort.next();
                self.set_status(format!("sort: {}", self.sort.label()));
                self.refresh_view();
            }

            TodoAction::Completed => {
                self.show_completed = !self.show_completed;
                self.set_status(if self.show_completed {
                    "showing completed"
                } else {
                    "hiding completed"
                });
                self.refresh_view();
            }

            TodoAction::Filter => {
                let mut tags = self.store.all_tags();
                tags.truncate(6);
                self.mode = Mode::Filter(TextField::with_value(self.filter.clone()), tags);
            }

            TodoAction::ShowPath => {
                let path = self.store.path().display().to_string();
                self.set_status(path);
            }
        }
        KeyOutcome::Consumed
    }

    /// Keys handled while the edit form is open.
    fn handle_edit_key(&mut self, key: KeyEvent) -> KeyOutcome {
        let shift = key.modifiers.contains(KeyModifiers::SHIFT);
        let Mode::Edit(form) = &mut self.mode else {
            return KeyOutcome::Ignored;
        };

        match key.code {
            KeyCode::Esc => {
                self.mode = Mode::List;
                self.set_status("cancelled");
                return KeyOutcome::Consumed;
            }
            KeyCode::Enter => {
                if let Err(message) = self.commit_form()
                    && let Mode::Edit(form) = &mut self.mode
                {
                    form.error = Some(message);
                }
                return KeyOutcome::Consumed;
            }
            KeyCode::Tab | KeyCode::Down => form.field = form.field.next(),
            KeyCode::BackTab | KeyCode::Up => form.field = form.field.prev(),

            KeyCode::Left | KeyCode::Right if form.field == Field::Priority => {
                form.priority = if key.code == KeyCode::Right {
                    form.priority.next()
                } else {
                    form.priority.prev()
                };
            }
            KeyCode::Char(' ') if form.field == Field::Priority => {
                form.priority = if shift {
                    form.priority.prev()
                } else {
                    form.priority.next()
                };
            }

            _ => {
                let used = form
                    .active_text_field()
                    .is_some_and(|field| field.handle_key(key));
                if used {
                    form.error = None;
                }
                return KeyOutcome::Consumed;
            }
        }
        KeyOutcome::Consumed
    }

    /// Keys handled while typing a filter.
    fn handle_filter_key(&mut self, key: KeyEvent) -> KeyOutcome {
        let Mode::Filter(field, _) = &mut self.mode else {
            return KeyOutcome::Ignored;
        };
        match key.code {
            // Esc abandons filtering entirely rather than leaving a
            // half-typed filter applied behind a closed input.
            KeyCode::Esc => {
                field.clear();
                self.filter.clear();
                self.mode = Mode::List;
                self.refresh_view();
            }
            KeyCode::Enter => {
                self.filter = field.trimmed().to_string();
                self.mode = Mode::List;
                self.refresh_view();
            }
            _ => {
                if field.handle_key(key) {
                    let live = field.trimmed().to_string();
                    self.filter = live;
                    self.refresh_view();
                }
            }
        }
        KeyOutcome::Consumed
    }

    /// Keys handled at the delete confirmation.
    fn handle_confirm_key(&mut self, key: KeyEvent) -> KeyOutcome {
        let Mode::ConfirmDelete { id, .. } = self.mode else {
            return KeyOutcome::Ignored;
        };
        match key.code {
            // `y` alone. Enter used to delete here while the prompt said "any
            // other key cancel" — the most reflexive key at a confirmation,
            // promised safe, wired to the one action with no undo.
            KeyCode::Char('y' | 'Y') => {
                self.store.remove(id);
                self.mode = Mode::List;
                self.set_status("task deleted");
                self.refresh_view();
                self.persist();
            }
            _ => {
                self.mode = Mode::List;
            }
        }
        KeyOutcome::Consumed
    }

    /// Build one task row against the shared column grid.
    ///
    /// Ragged rows are why a task list reads as noise: if the due date floats
    /// to wherever the title happens to end, the eye cannot scan down it. The
    /// grid guarantees every row agrees on where each column starts.
    fn task_line<'a>(&self, task: &'a Task, theme: &Theme, grid: &Grid) -> Line<'a> {
        let (filled, priority_colour) = match task.priority {
            Priority::High => (3, theme.error),
            Priority::Medium => (2, theme.warning),
            Priority::Low => (1, theme.muted),
            Priority::None => (0, theme.muted),
        };

        let (due_label, due_colour) = self
            .due_badge(task, theme)
            .unwrap_or_else(|| (String::new(), theme.muted));

        let tags = task
            .tags
            .iter()
            .map(|t| format!("#{t}"))
            .collect::<Vec<_>>()
            .join(" ");

        let title_style = if task.done {
            Style::default()
                .fg(theme.muted)
                .add_modifier(Modifier::CROSSED_OUT)
        } else {
            Style::default().fg(theme.text)
        };

        grid.row(&[
            Span::styled(
                if task.done { "[x]" } else { "[ ]" },
                Style::default().fg(if task.done {
                    theme.success
                } else {
                    theme.muted
                }),
            ),
            // A filled gauge reads as a level without needing colour, which
            // matters when a terminal theme flattens the palette.
            Span::styled(
                "\u{25ae}".repeat(filled),
                Style::default().fg(priority_colour),
            ),
            Span::styled(task.title.as_str(), title_style),
            Span::styled(tags, Style::default().fg(theme.label)),
            Span::styled(due_label, Style::default().fg(due_colour)),
        ])
    }

    /// The due-date badge text and colour, if the task has a due date.
    fn due_badge(&self, task: &Task, theme: &Theme) -> Option<(String, ratatui::style::Color)> {
        let due = task.due?;
        if task.done {
            return Some((
                due.strftime(&self.config.date_format).to_string(),
                theme.muted,
            ));
        }
        let badge = match task.due_state(self.today) {
            DueState::Overdue(1) => ("1 day late".to_string(), theme.error),
            DueState::Overdue(n) => (format!("{n} days late"), theme.error),
            DueState::Today => ("today".to_string(), theme.warning),
            DueState::Soon(1) => ("tomorrow".to_string(), theme.warning),
            DueState::Soon(n) => (format!("in {n} days"), theme.text),
            DueState::Later(_) => (
                due.strftime(&self.config.date_format).to_string(),
                theme.muted,
            ),
            DueState::None => return None,
        };
        Some(badge)
    }

    /// The summary line: what is wrong, and how the list is sorted.
    ///
    /// Assembled in priority order and cut at whole items, so a narrow panel
    /// loses the sort mode before the overdue count and never shows `4 op`.
    ///
    /// It does *not* carry the open count, which the border already shows two
    /// rows above — see the note beside the one case that puts it back.
    fn header(&self, theme: &Theme, width: u16) -> Line<'static> {
        let Counts {
            open,
            overdue,
            today,
        } = self.counts;

        // Lead with whatever is actually wrong. On a calm day this line is
        // short and grey, which is the point: you should be able to tell at a
        // glance that there is nothing to deal with. That ordering is also the
        // order things are given up in when the panel is narrow, which is the
        // same judgement read from the other end.
        let mut items: Vec<(String, Style)> = Vec::new();
        if overdue > 0 {
            items.push((
                format!("{overdue} overdue"),
                Style::default()
                    .fg(theme.error)
                    .add_modifier(Modifier::BOLD),
            ));
        }
        if today > 0 {
            items.push((
                format!("{today} due today"),
                Style::default().fg(theme.warning),
            ));
        }
        // The border already says `N open`, and said it two rows above this
        // one — so this line was printing the same fact twice, and under a
        // narrow panel it printed the *duplicate* while dropping the sort mode,
        // which appears nowhere else. It is kept only for the one case where
        // the border is saying something more urgent instead: a failed save
        // replaces the counter with `unsaved!`, and the count would otherwise
        // vanish from the panel exactly when the reader is being told their
        // work is not reaching the disk.
        if self.store.last_error.is_some() {
            items.push((format!("{open} open"), Style::default().fg(theme.muted)));
        }
        // The border counts the tasks the horizon hides too, so a thinned list
        // says how many it is not showing. Not over an emptied one: the list's
        // own message says it there.
        if self.beyond > 0 && !self.view.is_empty() {
            items.push((
                format!("{} later", self.beyond),
                Style::default().fg(theme.muted),
            ));
        }
        items.push((
            format!("by {}", self.sort.label()),
            Style::default().fg(theme.muted),
        ));
        if self.show_completed {
            items.push(("+done".to_string(), Style::default().fg(theme.muted)));
        }
        if !self.filter.is_empty() {
            items.push((
                format!("/{}", self.filter),
                Style::default().fg(theme.accent),
            ));
        }

        // The gap belongs to the item it introduces, so dropping the item
        // takes its gap with it and the line never ends in trailing space.
        let parts = items
            .into_iter()
            .enumerate()
            .map(|(index, (text, style))| {
                let text = if index == 0 {
                    text
                } else {
                    format!("   {text}")
                };
                vec![Span::styled(text, style)]
            })
            .collect();

        crate::grid::assemble(parts, width)
    }

    /// Draw the add/edit form as a centred modal.
    #[allow(clippy::too_many_lines)] // A form with five fields; splitting it
    // further would scatter the layout across helpers without making it clearer.
    fn render_form(frame: &mut Frame, area: Rect, theme: &Theme, form: &EditForm) {
        let width = area.width.clamp(24, 66);
        let height = 13u16.min(area.height);
        let popup = centred(area, width, height);

        frame.render_widget(Clear, popup);
        let title = if form.id.is_some() {
            " Edit task "
        } else {
            " New task "
        };
        let block = Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.accent))
            .title(Span::styled(title, Style::default().fg(theme.title).bold()));
        let inner = block.inner(popup);
        frame.render_widget(block, popup);

        let rows = Layout::vertical([
            Constraint::Length(1), // title
            Constraint::Length(1), // notes
            Constraint::Length(1), // due
            Constraint::Length(1), // priority
            Constraint::Length(1), // tags
            Constraint::Length(1), // spacer
            Constraint::Min(1),    // hint / error, and the rows to wrap it
            Constraint::Length(1), // key help
        ])
        .split(inner);

        let label_width = 9u16;
        for (i, field) in Field::ORDER.iter().enumerate() {
            let row = rows[i];
            let active = form.field == *field;
            let label_style = if active {
                Style::default().fg(theme.accent).bold()
            } else {
                Style::default().fg(theme.muted)
            };

            let columns = Layout::horizontal([Constraint::Length(label_width), Constraint::Min(1)])
                .split(row);

            frame.render_widget(
                Paragraph::new(Span::styled(field.label(), label_style)),
                columns[0],
            );

            let value_area = columns[1];
            if *field == Field::Priority {
                let marker = if active { "‹ " } else { "  " };
                let marker_end = if active { " ›" } else { "" };
                let colour = match form.priority {
                    Priority::High => theme.error,
                    Priority::Medium => theme.warning,
                    _ => theme.text,
                };
                frame.render_widget(
                    Paragraph::new(Line::from(vec![
                        Span::styled(marker, Style::default().fg(theme.muted)),
                        Span::styled(form.priority.to_string(), Style::default().fg(colour)),
                        Span::styled(marker_end, Style::default().fg(theme.muted)),
                    ])),
                    value_area,
                );
            } else if let Some(text) = form.text_field(*field) {
                let (visible, cursor_col) = text.visible(value_area.width as usize);
                let style = if active {
                    Style::default().fg(theme.text)
                } else {
                    Style::default().fg(theme.muted)
                };
                // Cut to the field with its `…` (invariant 19). It was drawn at
                // its natural width, and a form narrower than about 27
                // columns let the terminal cut it: `what needs d`, which
                // reads as a word nobody wrote.
                let display = if visible.is_empty() && !active {
                    truncate(placeholder(*field), usize::from(value_area.width))
                } else {
                    visible
                };
                let display_style = if text.value().is_empty() && !active {
                    Style::default().fg(theme.muted).italic()
                } else {
                    style
                };
                frame.render_widget(
                    Paragraph::new(Span::styled(display, display_style)),
                    value_area,
                );
                if active {
                    frame.set_cursor_position((value_area.x + cursor_col as u16, value_area.y));
                }
            }
        }

        // Hint or validation error, in the rows left over above the key help.
        // Wrapped by `grid` rather than by ratatui — a save error carries text
        // from the operating system, and ratatui's wrapper panics on text
        // mirador did not write. See `grid::wrapped`. It used to have one row
        // and be handed every wrapped row anyway, so the Due hint and a bad
        // date's error both lost their second half in silence; where the form
        // is too short for the whole message, the last row says it was cut.
        let (message, style) = match &form.error {
            Some(err) => (err.as_str(), Style::default().fg(theme.error)),
            None => (hint_for(form.field), Style::default().fg(theme.muted)),
        };
        frame.render_widget(
            Paragraph::new(fitted_rows(message, rows[6], false)).style(style),
            rows[6],
        );

        // The key help is the form's only word on how to leave it, and at the
        // shipped 120x40 dashboard it had 36 cells for 38: the terminal cut
        // it to `Esc can`. Its parts drop whole, `Esc cancel` last, as a
        // prompt's help does.
        let keys = ["Tab/↑↓ field", "Enter save", "Esc cancel"]
            .map(str::to_string)
            .to_vec();
        frame.render_widget(
            Paragraph::new(crate::grid::assemble(
                crate::prompt::way_out_last(
                    keys,
                    " · ",
                    rows[7].width,
                    Style::default().fg(theme.muted),
                ),
                rows[7].width,
            )),
            rows[7],
        );
    }

    /// Draw the delete confirmation.
    fn render_confirm(frame: &mut Frame, area: Rect, theme: &Theme, title: &str) {
        let width = area.width.clamp(20, 54);
        let popup = centred(area, width, 5.min(area.height));
        frame.render_widget(Clear, popup);

        let block = Block::default()
            .borders(Borders::ALL)
            .border_type(BorderType::Rounded)
            .border_style(Style::default().fg(theme.error))
            .title(Span::styled(
                " Delete task ",
                Style::default().fg(theme.error).bold(),
            ));
        let inner = block.inner(popup);
        frame.render_widget(block, popup);

        let text = vec![
            Line::from(Span::styled(
                truncate(title, inner.width as usize),
                Style::default().fg(theme.text),
            )),
            Line::from(Span::styled(
                "y delete · any other key cancel",
                Style::default().fg(theme.muted),
            )),
        ];
        frame.render_widget(Paragraph::new(text).wrap(Wrap { trim: true }), inner);
    }
}

impl Panel for TodoPanel {
    fn title(&self) -> String {
        "Tasks".to_string()
    }

    fn counter(&self) -> Option<String> {
        // A failed save outranks the count. The status line is transient — it
        // clears on the next keypress — which is the right lifetime for "added
        // a task" and the wrong one for "nothing you do is reaching the disk".
        // Left to the status line alone, the panel went on reporting a tally it
        // could not persist, and said nothing at all on the way out.
        if self.store.last_error.is_some() {
            return Some("unsaved!".into());
        }
        Some(format!("{} open", self.counts.open))
    }

    fn refresh_interval(&self) -> std::time::Duration {
        // Only needed so that due-date colouring rolls over at midnight.
        std::time::Duration::from_mins(1)
    }

    fn tick(&mut self) -> bool {
        // This already compared; the answer was simply thrown away, so the
        // dashboard repainted every second to learn that the date had not
        // changed.
        let today = jiff::Zoned::now().date();
        if today == self.today {
            return false;
        }

        // A task that went overdue because the day turned is the clearest
        // example of something that happened *to* the reader: nobody did it,
        // and it is true whether or not they were looking at this panel.
        //
        // Deliberately only on the rollover. Editing a due date into the past
        // also makes a task overdue, and that is the reader's own doing — they
        // were there, and telling them about it would be the log repeating
        // their own keystrokes back at them.
        for task in self.store.tasks() {
            if task.done {
                continue;
            }
            let was = matches!(
                task.due_state(self.today),
                crate::task::DueState::Overdue(_)
            );
            let now = matches!(task.due_state(today), crate::task::DueState::Overdue(_));
            if !was && now {
                self.pending.push(crate::watch::Event::new(
                    "tasks",
                    format!("{} went overdue", task.title),
                ));
            }
        }

        self.today = today;
        // Overdue rows are coloured by date, so a day boundary restyles the
        // list even when no task moved.
        self.refresh_view();
        true
    }

    fn alert(&self) -> Option<crate::panel::Alert> {
        // A save that is failing is the clearest case there is: the work is on
        // screen and not on disk, and every further edit widens the gap.
        self.store
            .last_error
            .as_ref()
            .map(|why| crate::panel::Alert::failing(format!("Tasks could not be saved — {why}")))
    }

    fn events(&mut self) -> Vec<crate::watch::Event> {
        std::mem::take(&mut self.pending)
    }

    fn remember(&self, state: &mut crate::state::UiState) {
        state.todo_sort = Some(self.sort.label().to_string());
        state.todo_show_completed = Some(self.show_completed);
    }

    fn captures_input(&self) -> bool {
        !matches!(self.mode, Mode::List)
    }

    fn handle_key(&mut self, key: KeyEvent) -> KeyOutcome {
        // Any keypress clears a stale status message.
        self.status = None;
        match &self.mode {
            Mode::List => self.handle_list_key(key),
            Mode::Edit(_) => self.handle_edit_key(key),
            Mode::Filter(..) => self.handle_filter_key(key),
            Mode::ConfirmDelete { .. } => self.handle_confirm_key(key),
        }
    }

    /// Claimed and dropped at the delete confirmation. A paste nobody claims
    /// is typed in key by key, and one beginning with `y` would answer the
    /// question and delete the task. Everywhere else the shell's typing is
    /// what the form wants.
    fn handle_paste(&mut self, _text: &str) -> KeyOutcome {
        if matches!(self.mode, Mode::ConfirmDelete { .. }) {
            KeyOutcome::Consumed
        } else {
            KeyOutcome::Ignored
        }
    }

    fn handle_mouse(&mut self, event: MouseEvent, _area: Rect) -> KeyOutcome {
        // A form owns the panel while it is open; a click landing behind it
        // must not quietly move the selection out from under the editor.
        if !matches!(self.mode, Mode::List) {
            return KeyOutcome::Ignored;
        }

        match event.kind {
            MouseEventKind::ScrollDown => {
                self.select_down(1);
                KeyOutcome::Consumed
            }
            MouseEventKind::ScrollUp => {
                self.select_up(1);
                KeyOutcome::Consumed
            }
            MouseEventKind::Down(MouseButton::Left) => {
                let Some(area) = self.list_area else {
                    return KeyOutcome::Ignored;
                };
                let at = Position::new(event.column, event.row);
                let Some(index) =
                    crate::selection::row_at(&self.list_state, area, at, self.view.len())
                else {
                    return KeyOutcome::Ignored;
                };
                self.status = None;
                self.list_state.select(Some(index));
                KeyOutcome::Consumed
            }
            _ => KeyOutcome::Ignored,
        }
    }

    fn bindings(&self) -> &[Binding] {
        self.keys.bindings()
    }

    fn set_keys(&mut self, config: &crate::config::Config) {
        self.keys = list_keys(&config.todo.keys);
    }

    #[allow(clippy::too_many_lines)] // Four stacked regions plus two modal
    // overlays; the sub-renderers are already factored out.
    fn render(&mut self, frame: &mut Frame, area: Rect, ctx: RenderContext<'_>) {
        let theme = ctx.theme;
        if area.height == 0 || area.width == 0 {
            return;
        }

        let show_notes = self
            .selected_id()
            .and_then(|id| self.store.get(id))
            .and_then(|t| t.notes.as_ref())
            .is_some()
            && area.height > 6;

        // The column header only earns its row once there are rows to label
        // and vertical space to spare.
        let show_columns = !self.view.is_empty() && area.height >= 5;

        // Over an empty list with no filter and no failed save, the summary
        // has only the sort order of nothing to say, and the list's message
        // says the rest — so the message gets its row. `by smart` over `No
        // tasks yet. Press…` cut the key it names to keep a sort mode.
        let show_summary =
            !(self.view.is_empty() && self.filter.is_empty() && self.store.last_error.is_none());

        let rows = Layout::vertical([
            Constraint::Length(u16::from(show_summary)),   // summary
            Constraint::Length(u16::from(show_columns)),   // column header
            Constraint::Min(1),                            // list
            Constraint::Length(u16::from(show_notes) * 2), // notes preview
            Constraint::Length(1),                         // status / filter
        ])
        .split(area);

        if show_summary {
            frame.render_widget(Paragraph::new(self.header(theme, rows[0].width)), rows[0]);
        }

        // Recorded every pass so a click maps to the rows actually on screen,
        // and cleared when there are none rather than left pointing at a stale
        // rectangle.
        self.list_area = (!self.view.is_empty()).then_some(rows[2]);

        if self.view.is_empty() {
            // "No tasks yet" over a list the horizon emptied would be false
            // while the border still counted them open.
            let message = if !self.filter.is_empty() {
                "Nothing matches this filter. Esc to clear.".to_string()
            } else if self.beyond > 0 {
                let days = match self.config.horizon_days {
                    1 => "day".to_string(),
                    n => format!("{n} days"),
                };
                format!("Nothing due in the next {days}; {} later.", self.beyond)
            } else if let Some(key) = self.keys.keys(TodoAction::Add).first() {
                // The key `[todo.keys]` gave `add`, and no offer when it
                // gave none.
                format!("No tasks yet. Press `{key}` to add one.")
            } else {
                "No tasks yet.".to_string()
            };
            // Prose in a list of several rows, so wrapped into them, and the
            // last row says so if they run out (invariant 19). Cut to one
            // row, it lost the key it names at 20 cells over blank rows.
            frame.render_widget(
                Paragraph::new(fitted_rows(&message, rows[2], false))
                    .style(Style::default().fg(theme.muted)),
                rows[2],
            );
        } else {
            // Only the rows the pane can show are built. Every task in the
            // view used to become a `ListItem` — a gauge, a tag string, a due
            // label and a line of spans each — for a `List` that then drew
            // the twenty that fit, so a frame cost as many allocations as
            // there were open tasks rather than rows on screen. The window
            // is the one `List` would have scrolled to; it is worked out
            // first, and the list is handed only what is in it.
            let (shown, selected) = crate::selection::window(
                self.list_state.selected(),
                self.list_state.offset(),
                self.view.len(),
                usize::from(rows[2].height),
            );
            let visible =
                crate::selection::in_order(self.store.tasks(), &self.view[shown.clone()], |task| {
                    task.id
                });

            // The list is indented by the selection marker, so the grid gets
            // what is left and the header is indented to match.
            let marker = 2u16;
            let grid = Grid::new(COLUMNS, rows[2].width.saturating_sub(marker));

            let items: Vec<ListItem> = visible
                .iter()
                .map(|task| ListItem::new(self.task_line(task, theme, &grid)))
                .collect();

            // Dim the selection when the panel is not focused, so it is
            // obvious which panel the keyboard is talking to.
            let list = List::new(items)
                .highlight_symbol(if ctx.focused { "▸ " } else { "  " })
                .highlight_style(if ctx.focused {
                    Style::default()
                        .fg(theme.accent)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(theme.muted)
                });
            if show_columns && rows[1].height > 0 {
                // Indent the header past the selection marker so it lines up
                // with the columns it names.
                let header_area = Rect::new(
                    rows[1].x + marker,
                    rows[1].y,
                    rows[1].width.saturating_sub(marker),
                    1,
                );
                frame.render_widget(Paragraph::new(grid.header(theme)), header_area);
            }

            // A list with no room draws nothing and, as `List` itself does,
            // leaves the scroll where it was.
            if !rows[2].is_empty() {
                let mut drawn =
                    ListState::default().with_selected(selected.map(|at| at - shown.start));
                frame.render_stateful_widget(list, rows[2], &mut drawn);
                // Kept as `List` would have kept it, so the next frame scrolls
                // from here and a click maps through the rows on screen.
                self.list_state.select(selected);
                *self.list_state.offset_mut() = shown.start;
            }
        }

        if show_notes
            && let Some(notes) = self
                .selected_id()
                .and_then(|id| self.store.get(id))
                .and_then(|t| t.notes.as_deref())
        {
            // Only as much text as the preview can possibly show is wrapped.
            // Wrapping the whole field cost 62ms a frame for a 2MB note — the
            // same defect the reader in `notes` had (#178), and the same rule
            // broken: a panel may allocate in proportion to what is on screen,
            // never to how much it holds. For the same reason the field is
            // borrowed: it was cloned whole every frame before the few rows
            // the preview shows were taken from the copy.
            //
            // No cache is needed here because this preview does not scroll, so
            // the first few rows are the only rows. A wrapped row holds at most
            // `width` characters of its own, and a break after it takes a run
            // of whitespace that draws nothing. Spent from the budget whole,
            // padding would use it up and cut a word after it to `R…` with a
            // row to spare, so a run is kept only as far as the wrap needs and
            // each row is allowed that too (see `WrapSource`).
            // `height` rows of it is always enough to fill the pane — an
            // over-estimate, which is what makes it safe. What is left out is
            // still read, so the read stops at sixteen characters for each the
            // budget allows, and a note of nothing but spaces cannot make every
            // frame walk the whole of it.
            let width = usize::from(rows[3].width);
            let budget = usize::from(rows[3].height).saturating_mul(WrapSource::row_cells(width));
            let mut source = WrapSource::new(width);
            let (mut enough, mut kept, mut cut) = (String::new(), 0usize, false);
            for (read, c) in notes.chars().enumerate() {
                if read == budget.saturating_mul(16) {
                    cut = true;
                    break;
                }
                if !source.needs(c) {
                    continue;
                }
                if kept == budget {
                    cut = true;
                    break;
                }
                enough.push(c);
                kept += 1;
            }
            // A note longer than the pane keeps the rows that fit and says it
            // was cut on the last of them (invariant 19). Handing every row to
            // the `Paragraph` let it drop the rest in silence, so the seeded
            // overdue task's preview ended a sentence early and looked whole.
            // A note cut by the budget above is abridged too, even when its
            // rows happen to fill the pane exactly.
            frame.render_widget(
                Paragraph::new(fitted_rows(&enough, rows[3], cut))
                    .style(Style::default().fg(theme.muted)),
                rows[3],
            );
        }

        // Bottom line: filter input takes priority, then status, then hints.
        let bottom = rows[4];
        if let Mode::Filter(field, tags) = &self.mode {
            let (visible, cursor) = field.visible(bottom.width.saturating_sub(2) as usize);
            let mut parts = vec![vec![
                Span::styled("/", Style::default().fg(theme.accent)),
                Span::styled(visible, Style::default().fg(theme.text)),
            ]];
            // With nothing typed yet, offer the tags actually in use rather
            // than leaving the user to guess what will match. Each is a part
            // of its own, so a narrow bar drops whole tags: it used to append
            // them at their natural width and end in `#mira`, a tag that
            // does not exist.
            if field.is_blank() {
                parts.extend(tags.iter().enumerate().map(|(index, tag)| {
                    let gap = if index == 0 { "   " } else { " " };
                    vec![Span::styled(
                        format!("{gap}#{tag}"),
                        Style::default().fg(theme.muted),
                    )]
                }));
            }
            frame.render_widget(
                Paragraph::new(crate::grid::assemble(parts, bottom.width)),
                bottom,
            );
            frame.set_cursor_position((bottom.x + 1 + cursor as u16, bottom.y));
        } else {
            let line = match &self.status {
                Some((message, is_error)) => Span::styled(
                    truncate(message, bottom.width as usize),
                    Style::default().fg(if *is_error { theme.error } else { theme.muted }),
                ),
                // The frame carries the key hints, so an idle status line
                // stays blank rather than repeating them.
                None => Span::raw(""),
            };
            frame.render_widget(Paragraph::new(line), bottom);
        }

        // Modals draw last so they sit on top.
        match &self.mode {
            Mode::Edit(form) => Self::render_form(frame, area, theme, form),
            Mode::ConfirmDelete { title, .. } => Self::render_confirm(frame, area, theme, title),
            _ => {}
        }
    }

    fn shutdown(&mut self) {
        self.store.save_reporting();
    }
}

/// Placeholder text for an empty, unfocused field.
fn placeholder(field: Field) -> &'static str {
    match field {
        Field::Title => "what needs doing",
        Field::Notes => "optional detail",
        Field::Due => "empty for none",
        Field::Tags => "comma separated",
        Field::Priority => "",
    }
}

/// Contextual hint for the focused field.
fn hint_for(field: Field) -> &'static str {
    match field {
        Field::Title => "A one-line summary. Required.",
        Field::Notes => "Longer detail, shown under the list.",
        Field::Due => "2026-07-28, today, tomorrow, fri, +3d, 2w — or empty.",
        Field::Priority => "←/→ or space to change.",
        Field::Tags => "Comma or space separated, e.g. rust, mirador.",
    }
}

// Truncation is `grid::truncate`, which measures display cells. This module
// had its own copy that counted `chars()`, and both callers pass a cell count
// — `inner.width` and `bottom.width` — so a CJK title overflowed the panel by
// one cell per character.
use crate::grid::truncate;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::testing::TempDir;

    #[test]
    fn field_order_cycles_both_ways() {
        assert_eq!(Field::Title.next(), Field::Notes);
        assert_eq!(Field::Tags.next(), Field::Title);
        assert_eq!(Field::Title.prev(), Field::Tags);
        for f in Field::ORDER {
            assert_eq!(f.next().prev(), f);
        }
    }

    #[test]
    fn a_truncated_title_never_outgrows_its_budget_in_cells() {
        assert_eq!(truncate("hello", 10), "hello");
        assert_eq!(truncate("hello", 3), "he…");
        assert_eq!(truncate("hello", 0), "");

        // This used to assert `"日本…"` — five cells for a three-cell budget,
        // which is how a task title got to overwrite the panel's own border.
        // The test pinned the bug rather than catching it.
        assert_eq!(truncate("日本語テスト", 3), "日…");

        for width in 0..12 {
            for text in ["hello", "日本語テスト", "a日b本c", "☀ 21°C"] {
                assert!(
                    crate::grid::display_width(&truncate(text, width)) <= width,
                    "truncate({text:?}, {width}) overflows its budget"
                );
            }
        }
    }

    #[test]
    fn centred_never_exceeds_its_container() {
        let area = Rect::new(0, 0, 20, 10);
        let r = centred(area, 100, 100);
        assert!(r.width <= area.width && r.height <= area.height);
        assert!(r.x >= area.x && r.y >= area.y);
        assert!(r.x + r.width <= area.x + area.width);
        assert!(r.y + r.height <= area.y + area.height);
    }

    #[test]
    fn centred_is_actually_centred() {
        let r = centred(Rect::new(0, 0, 20, 10), 10, 4);
        assert_eq!((r.x, r.y, r.width, r.height), (5, 3, 10, 4));
    }

    // ---------------------------------------------------------------------
    // Panel behaviour, driven through the same key events the terminal sends.
    // ---------------------------------------------------------------------

    /// A panel backed by a fresh, empty task file.
    fn panel(name: &str) -> (TodoPanel, TempDir) {
        let dir = TempDir::new(&format!("todo-{name}"));
        let path = dir.join("todos.toml");
        // An empty file rather than no file: the panel seeds examples when the
        // file is absent, and these tests are about the panel, not the seed.
        // Writing it first exercises the same branch a second run takes.
        std::fs::write(&path, "").unwrap();
        let panel = TodoPanel::new(TodoConfig::default(), path).unwrap();
        (panel, dir)
    }

    /// `[todo].horizon_days` shipped in the first commit, documented in every
    /// first-run config as "hide tasks due further out than this", and was
    /// read by nothing: a reader who set it to a week still saw the whole year.
    #[test]
    fn a_horizon_hides_only_the_tasks_due_beyond_it() {
        let dir = TempDir::new("todo-horizon");
        let path = dir.join("todos.toml");
        std::fs::write(&path, "").unwrap();
        let config = TodoConfig {
            horizon_days: 7,
            ..TodoConfig::default()
        };
        let mut panel = TodoPanel::new(config, path).unwrap();

        let today = panel.today;
        let in_days = |n: i32| today.checked_add(jiff::Span::new().days(n)).unwrap();
        let mut add = |title: &str, due: Option<Date>| {
            let mut task = Task::new(0, title, today);
            task.due = due;
            panel.store.add(task)
        };
        let late = add("late", Some(in_days(-3)));
        let edge = add("a week out", Some(in_days(7)));
        let past_edge = add("a day further", Some(in_days(8)));
        let far = add("next month", Some(in_days(30)));
        let undated = add("whenever", None);
        panel.refresh_view();

        for id in [late, edge, undated] {
            assert!(
                panel.view.contains(&id),
                "a task that is late, due within the horizon or undated stays: {:?}",
                panel.store.get(id)
            );
        }
        for id in [past_edge, far] {
            assert!(
                !panel.view.contains(&id),
                "a task due beyond the horizon is hidden: {:?}",
                panel.store.get(id)
            );
        }

        // Measured from the panel's today, which `tick` moves on at midnight,
        // so a hidden task comes into view on the day it comes into range.
        panel.today = in_days(23);
        panel.refresh_view();
        assert!(
            panel.view.contains(&far),
            "the horizon must move with the day"
        );

        // 0 is the documented "show all", and a horizon past the end of the
        // calendar shows all too rather than taking the dashboard down: one
        // that a span can hold and a date cannot, and one a span cannot hold.
        for horizon in [0, 7_000_000, u32::MAX] {
            panel.config.horizon_days = horizon;
            panel.refresh_view();
            assert_eq!(panel.view.len(), 5, "horizon {horizon} hides nothing");
        }
    }

    /// A task saved past the horizon disappears from the list at once, so the
    /// panel says where it went, and an empty list says the horizon emptied it
    /// rather than claiming there are no tasks.
    #[test]
    fn a_task_beyond_the_horizon_is_accounted_for() {
        let (mut panel, _guard) = panel("horizon-said");
        panel.config.horizon_days = 7;
        panel.refresh_view();

        press(&mut panel, KeyCode::Char('a'));
        type_str(&mut panel, "Renew the passport");
        press(&mut panel, KeyCode::Tab);
        press(&mut panel, KeyCode::Tab);
        type_str(&mut panel, "+30d");
        press(&mut panel, KeyCode::Enter);

        let said = panel.status.as_ref().map(|(text, _)| text.clone());
        assert_eq!(
            said.as_deref(),
            Some("task added, due beyond the 7-day horizon")
        );
        let screen = screen_of(&mut panel, 60, 12);
        assert!(!screen.contains("No tasks yet"), "{screen}");
        assert!(screen.contains("1 later"), "{screen}");
        assert_eq!(
            screen.matches("later").count(),
            1,
            "the empty list says it, so the summary does not say it again: {screen}"
        );

        // A one-day horizon is "the next day", not "the next 1 days".
        panel.config.horizon_days = 1;
        panel.refresh_view();
        let screen = screen_of(&mut panel, 60, 12);
        assert!(
            screen.contains("Nothing due in the next day; 1 later."),
            "{screen}"
        );
    }

    /// The filter is how a task is looked up by name, so it looks past the
    /// horizon. Otherwise a task saved with `+300d` for `+3d` is out of reach
    /// of `/`, `e` and `d` until the day it comes into range, and "Nothing
    /// matches this filter" is said over a task that does.
    #[test]
    fn a_filter_searches_past_the_horizon() {
        let (mut panel, _guard) = panel("horizon-filter");
        panel.config.horizon_days = 7;
        let mut task = Task::new(0, "Renew the passport", panel.today);
        task.due = panel.today.checked_add(jiff::Span::new().days(30)).ok();
        let id = panel.store.add(task);
        panel.refresh_view();
        assert!(panel.view.is_empty(), "unfiltered, the horizon hides it");

        press(&mut panel, KeyCode::Char('/'));
        type_str(&mut panel, "passport");
        assert_eq!(panel.view, vec![id], "a filter finds it however far out");
        press(&mut panel, KeyCode::Enter);
        assert_eq!(panel.selected_id(), Some(id), "so `e` and `d` reach it");
        let screen = screen_of(&mut panel, 60, 12);
        assert!(screen.contains("Renew the passport"), "{screen}");
        assert!(
            !screen.contains("later"),
            "a filter hides nothing: {screen}"
        );

        // Both empty states stay true either side of it.
        panel.filter = "visa".to_string();
        panel.refresh_view();
        let screen = screen_of(&mut panel, 60, 12);
        assert!(screen.contains("Nothing matches this filter"), "{screen}");
        press(&mut panel, KeyCode::Esc);
        let screen = screen_of(&mut panel, 60, 12);
        assert!(
            screen.contains("Nothing due in the next 7 days; 1 later."),
            "{screen}"
        );
    }

    /// The border counts every open task, the ones the horizon hides as well,
    /// so a list it has thinned says how many it is not showing. Otherwise
    /// `4 open` sits over two rows with nothing to reconcile them.
    #[test]
    fn the_summary_says_how_many_the_horizon_hides() {
        let (mut panel, _guard) = panel("horizon-summary");
        panel.config.horizon_days = 7;
        for (title, days) in [
            ("Pay the rent", 2),
            ("Call the bank", 5),
            ("Book the dentist", 30),
            ("Renew the lease", 40),
        ] {
            let mut task = Task::new(0, title, panel.today);
            task.due = panel.today.checked_add(jiff::Span::new().days(days)).ok();
            panel.store.add(task);
        }
        panel.refresh_view();
        assert_eq!(panel.view.len(), 2);
        assert_eq!(panel.counter().as_deref(), Some("4 open"));
        let screen = screen_of(&mut panel, 60, 12);
        assert!(screen.contains("2 later"), "{screen}");
        assert_eq!(screen.matches("later").count(), 1, "{screen}");
    }

    /// The border and this line were both saying `4 open`, and the drop order
    /// made it worse rather than harmless: at 80 columns the summary kept the
    /// duplicate and dropped the sort mode, which is written down nowhere else.
    ///
    /// The count comes back for the one case where the border stops carrying
    /// it. A failed save takes the counter for `unsaved!`, and that is the
    /// worst possible moment for the panel to also stop saying how much is on
    /// the list.
    #[test]
    fn the_open_count_is_shown_once_and_by_the_border() {
        let dir = TempDir::new("todo-count");
        // Seeded rather than empty: the examples are what a first run shows,
        // and one of them is overdue, so the summary has something to lead with
        // besides the count under test.
        let mut panel = TodoPanel::new(TodoConfig::default(), dir.join("todos.toml")).unwrap();

        let theme = Theme::default();
        let text = |panel: &TodoPanel| -> String {
            panel
                .header(&theme, 120)
                .spans
                .iter()
                .map(|span| span.content.to_string())
                .collect()
        };

        let counter = panel.counter().expect("the border carries a counter");
        assert!(
            counter.contains("open"),
            "the border is where the count lives: {counter}"
        );
        assert!(
            !text(&panel).contains("open"),
            "and so the summary line must not repeat it: {}",
            text(&panel)
        );
        assert!(
            text(&panel).contains("by "),
            "the sort mode is what the line keeps instead: {}",
            text(&panel)
        );

        panel.store.last_error = Some("read-only file system".to_string());
        assert_eq!(
            panel.counter().as_deref(),
            Some("unsaved!"),
            "a failed save outranks the count in the border"
        );
        assert!(
            text(&panel).contains("open"),
            "so the summary line takes it back: {}",
            text(&panel)
        );
    }

    /// The panel as drawn at `width`x`height`, joined into one string.
    fn screen_of(panel: &mut TodoPanel, width: u16, height: u16) -> String {
        crate::widgets::testing::rows(&crate::widgets::testing::rendered(panel, width, height))
            .join("\n")
    }

    /// The form and the delete prompt had key-handling tests and no drawing
    /// tests: `render_form` and `render_confirm` were never executed. What the
    /// reader sees is the contract — every field labelled, the active one
    /// marked, and a title too long for the box abridged with `…` rather than
    /// cut by the terminal.
    #[test]
    fn the_task_form_and_the_delete_prompt_draw_what_they_say() {
        let (mut panel, _guard) = panel("form-draw");
        add_task(&mut panel, "Renew the domain");

        press(&mut panel, KeyCode::Char('a'));
        let form = screen_of(&mut panel, 80, 24);
        for label in ["New task", "Title", "Notes", "Due", "Priority", "Tags"] {
            assert!(form.contains(label), "the form shows `{label}`:\n{form}");
        }
        for _ in 0..3 {
            press(&mut panel, KeyCode::Tab);
        }
        let on_priority = screen_of(&mut panel, 80, 24);
        assert!(
            on_priority.contains("‹ low ›"),
            "the active priority field shows its arrows:\n{on_priority}"
        );
        press(&mut panel, KeyCode::Esc);

        press(&mut panel, KeyCode::Enter);
        assert!(
            screen_of(&mut panel, 80, 24).contains("Edit task"),
            "editing an existing task says so"
        );
        press(&mut panel, KeyCode::Esc);

        let long = "A".repeat(70);
        add_task(&mut panel, &long);
        press(&mut panel, KeyCode::Char('G'));
        press(&mut panel, KeyCode::Char('d'));
        let confirm = screen_of(&mut panel, 40, 12);
        assert!(
            confirm.contains("Delete task"),
            "the prompt names itself:\n{confirm}"
        );
        assert!(confirm.contains("y delete"), "and its keys:\n{confirm}");
        assert!(
            confirm.contains('…'),
            "a title wider than the box is abridged, not cut:\n{confirm}"
        );
        assert!(
            !confirm.contains(&long),
            "the whole title cannot fit and does not:\n{confirm}"
        );
    }

    /// The form's message row was one row high and handed the message
    /// *wrapped*, so it drew the first line and dropped the rest in silence:
    /// at the shipped width the Due hint lost `or empty.` and a bad date lost
    /// the forms it would take. A full-height form has the rows to draw both
    /// whole; a short one draws what fits and ends it in `…`.
    #[test]
    fn the_forms_hint_and_error_are_whole_or_say_they_were_cut() {
        let (mut panel, _guard) = panel("form-message");
        press(&mut panel, KeyCode::Char('a'));
        type_str(&mut panel, "Renew the domain");
        press(&mut panel, KeyCode::Tab);
        press(&mut panel, KeyCode::Tab);
        let hint = screen_of(&mut panel, 41, 32);
        assert!(hint.contains("or empty."), "the whole Due hint:\n{hint}");

        type_str(&mut panel, "someday");
        press(&mut panel, KeyCode::Enter);
        let error = screen_of(&mut panel, 41, 32);
        assert!(error.contains("or 2w."), "the whole error:\n{error}");

        // Ten rows leave the message one row: what fits, marked as cut.
        let short = screen_of(&mut panel, 41, 10);
        let row = short
            .lines()
            .find(|row| row.contains("is not a date") || row.contains("`someday`"))
            .unwrap_or_else(|| panic!("the error is drawn:\n{short}"));
        let inside = row.trim_end().trim_end_matches('│').trim_end();
        assert!(inside.ends_with('…'), "cut, and says so: {row:?}\n{short}");
    }

    /// The form's key help is the one place it says how to leave, and at the
    /// shipped 120x40 dashboard the panel is 38 wide, so the row has 36 cells
    /// for 38: the terminal cut it to `Esc can`. Its parts drop whole, as a
    /// prompt's do, and `Esc cancel` is the last to go.
    #[test]
    fn the_forms_key_help_keeps_the_way_out_at_every_width() {
        let (mut panel, _guard) = panel("form-keys");
        press(&mut panel, KeyCode::Char('a'));
        let whole = [
            "Tab/↑↓ field · Enter save · Esc cancel",
            "Tab/↑↓ field · Esc cancel",
            "Esc cancel",
        ];
        let mut dropped = 0;
        for width in 24..=80u16 {
            let screen = screen_of(&mut panel, width, 20);
            let rows: Vec<&str> = screen.lines().collect();
            let bottom = rows
                .iter()
                .position(|row| row.contains('╰'))
                .unwrap_or_else(|| panic!("{width}: the form is drawn:\n{screen}"));
            let keys = rows[bottom - 1]
                .trim()
                .trim_start_matches('│')
                .trim_end_matches('│')
                .trim();
            assert!(whole.contains(&keys), "{width}: {keys:?}\n{screen}");
            if keys != whole[0] {
                dropped += 1;
            }
        }
        assert!(dropped > 0, "the sweep reached a width that drops a part");
    }

    /// With nothing typed, the filter bar offers the tags in use. They were
    /// appended at their natural width, so a narrow bar ended in `#mira`.
    /// Each tag is now a part that drops whole.
    #[test]
    fn the_filter_bars_tags_are_whole_or_absent() {
        let (mut panel, _guard) = panel("filter-tags");
        press(&mut panel, KeyCode::Char('a'));
        type_str(&mut panel, "Renew the domain");
        for _ in 0..4 {
            press(&mut panel, KeyCode::Tab);
        }
        type_str(&mut panel, "errands garden home mirador rust");
        press(&mut panel, KeyCode::Enter);
        let tags = ["#errands", "#garden", "#home", "#mirador", "#rust"];

        press(&mut panel, KeyCode::Char('/'));
        let mut offered = 0;
        for width in 2..=60u16 {
            let screen = screen_of(&mut panel, width, 12);
            let bar = screen.lines().last().expect("a bottom row");
            let mut words = bar.split_whitespace();
            assert_eq!(words.next(), Some("/"), "{width}: {bar:?}");
            for word in words {
                assert!(tags.contains(&word), "{width}: {word:?} in {bar:?}");
                offered += 1;
            }
        }
        assert!(offered > 0, "the sweep saw the tags offered at all");
    }

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

    /// Every key in the map works, and every one is advertised. The hints
    /// are derived from the map, so the second half holds by construction —
    /// this checks the first, that `handle_list_key` answers every action
    /// the map can send it, at every default key.
    #[test]
    fn every_key_in_the_map_works_and_is_advertised() {
        let map = keymap(&KeysConfig::default()).expect("valid");
        let advertised: Vec<String> = map
            .bindings()
            .iter()
            .flat_map(|b| b.key.split(" / ").map(str::to_string).collect::<Vec<_>>())
            .collect();
        for meta in ACTIONS {
            for key in meta.default_keys() {
                assert!(
                    advertised.contains(&key.to_string()),
                    "`{key}` ({}) is handled but not advertised: {advertised:?}",
                    meta.name
                );
                let (mut p, _guard) = panel("keymap");
                add_task(&mut p, "a task");
                assert!(matches!(p.mode, Mode::List));
                let (code, modifiers) = meta
                    .defaults
                    .iter()
                    .copied()
                    .find(|&(code, modifiers)| crate::keymap::Key::new(code, modifiers) == key)
                    .expect("a default");
                assert_eq!(
                    p.handle_key(KeyEvent::new(code, modifiers)),
                    KeyOutcome::Consumed,
                    "`{key}` ({}) is in the map but the list ignores it",
                    meta.name
                );
            }
        }
    }

    /// A moved key takes the action with it: the new key works, the old one
    /// is free, and the border says the new one.
    #[test]
    fn a_moved_list_key_works_and_the_old_one_does_not() {
        let (mut p, _guard) = panel("moved");
        add_task(&mut p, "a task");
        p.keys = keymap(&toml::from_str("delete = \"x\"").expect("a table")).expect("valid");
        assert_eq!(
            press_outcome(&mut p, KeyCode::Char('d')),
            KeyOutcome::Ignored
        );
        assert_eq!(
            press_outcome(&mut p, KeyCode::Char('x')),
            KeyOutcome::Consumed
        );
        assert!(
            matches!(p.mode, Mode::ConfirmDelete { .. }),
            "x asks to delete"
        );
        press(&mut p, KeyCode::Char('n'));
        assert!(
            p.bindings()
                .iter()
                .any(|b| b.primary && b.key == "x" && b.action == "delete")
        );
        // Esc is not in the map and still clears a filter.
        p.filter = "task".into();
        assert_eq!(press_outcome(&mut p, KeyCode::Esc), KeyOutcome::Consumed);
        assert!(p.filter.is_empty(), "{:?}", p.filter);
    }

    fn press_outcome(panel: &mut TodoPanel, code: KeyCode) -> KeyOutcome {
        panel.handle_key(KeyEvent::new(code, KeyModifiers::NONE))
    }

    /// The hints read as they did before the keys could move: paired keys
    /// share a line, and nothing the help overlay listed has gone.
    #[test]
    fn the_default_hints_are_the_ones_the_list_always_drew() {
        let map = keymap(&KeysConfig::default()).expect("valid");
        let drawn: Vec<(String, String, bool)> = map
            .bindings()
            .iter()
            .map(|b| (b.key.to_string(), b.action.to_string(), b.primary))
            .collect();
        let expected = [
            ("a", "add", true),
            ("↵", "edit", true),
            ("space", "done", true),
            ("d", "delete", true),
            ("↑ / ↓", "move selection", false),
            ("g / G", "first / last", false),
            ("PgUp / PgDn", "move ten rows", false),
            ("p / P", "cycle priority", false),
            ("s", "cycle sort", false),
            ("c", "show completed", false),
            ("/", "filter", false),
            ("o", "show file path", false),
            ("n", "add", false),
            ("e", "edit", false),
            ("k / j", "move selection", false),
            ("Home / End", "first / last", false),
            ("Esc", "clear filter", false),
        ];
        let expected: Vec<(String, String, bool)> = expected
            .iter()
            .map(|(k, a, p)| ((*k).to_string(), (*a).to_string(), *p))
            .collect();
        assert_eq!(drawn, expected);
    }

    #[test]
    fn enter_opens_the_task_for_editing_rather_than_completing_it() {
        let (mut p, _guard) = panel("enter-edits");
        add_task(&mut p, "buy milk");
        let id = p.selected_id().unwrap();

        press(&mut p, KeyCode::Enter);
        assert!(
            matches!(p.mode, Mode::Edit(_)),
            "Enter must go inside the task"
        );
        assert!(
            !p.store.get(id).is_some_and(|t| t.done),
            "Enter must not complete the task"
        );
    }

    #[test]
    fn space_still_toggles_done() {
        let (mut p, _guard) = panel("space-toggles");
        // `c` first: with completed tasks hidden, finishing one drops it out of
        // the view, and there is then nothing selected to reopen.
        press(&mut p, KeyCode::Char('c'));
        add_task(&mut p, "buy milk");
        let id = p.selected_id().unwrap();

        press(&mut p, KeyCode::Char(' '));
        assert!(p.store.get(id).is_some_and(|t| t.done), "space completes");
        press(&mut p, KeyCode::Char(' '));
        assert!(
            !p.store.get(id).is_some_and(|t| t.done),
            "and reopens again"
        );
    }

    #[test]
    fn completing_a_task_hides_it_while_completed_tasks_are_hidden() {
        let (mut p, _guard) = panel("done-hides");
        add_task(&mut p, "buy milk");
        assert_eq!(p.view.len(), 1);

        press(&mut p, KeyCode::Char(' '));
        assert!(
            p.view.is_empty(),
            "a finished task leaves the list until `c` shows it again"
        );
        press(&mut p, KeyCode::Char('c'));
        assert_eq!(p.view.len(), 1, "`c` brings it back");
    }

    fn type_str(panel: &mut TodoPanel, text: &str) {
        for c in text.chars() {
            press(panel, KeyCode::Char(c));
        }
    }

    /// Add a task through the form: `a`, title, then any extra field edits.
    fn add_task(panel: &mut TodoPanel, title: &str) {
        press(panel, KeyCode::Char('a'));
        type_str(panel, title);
        press(panel, KeyCode::Enter);
    }

    /// The preview's character budget is always enough to fill its pane.
    ///
    /// The preview wraps only `height * width` characters instead of the whole
    /// field, because wrapping a 2MB note for two rows of output cost 62ms a
    /// frame — the same defect as #178 in the notes reader. The over-estimate
    /// is what makes that safe: a wrapped row consumes at most `width`
    /// characters, so `height * width` of them always spans at least `height`
    /// rows. Wide glyphs only help, since they make a row hold fewer
    /// characters and so produce more rows.
    ///
    /// The first version of this test compared a huge note's render against a
    /// merely long one's and asserted they matched. It could not fail: both
    /// exceed any budget, so both were truncated identically and drew the same
    /// thing. It passed with the budget cut to twenty characters.
    #[test]
    fn the_preview_budget_always_fills_its_pane() {
        for source in [
            "lorem ipsum dolor sit amet ".repeat(500),
            "\u{65e5}\u{672c}\u{8a9e}".repeat(500),
            "no-spaces-at-all-".repeat(500),
        ] {
            for width in 1..=48u16 {
                for height in 1..=4u16 {
                    let budget = usize::from(height).saturating_mul(usize::from(width));
                    let cut: String = source.chars().take(budget).collect();
                    let rows = crate::grid::wrap(&cut, usize::from(width));
                    assert!(
                        rows.len() >= usize::from(height),
                        "{height}x{width} needs {height} rows, {} chars gave {}",
                        budget,
                        rows.len()
                    );
                }
            }
        }
    }

    /// A note longer than its preview says it was cut (invariant 19).
    ///
    /// Found on a first-run dashboard at 200x50: the seeded overdue task's
    /// preview stopped after "This one is here to show that;" and the closing
    /// sentence was gone with nothing to say so, because the `Paragraph` was
    /// handed every wrapped row and dropped the ones below its two in silence.
    ///
    /// `no_panel_cuts_a_value_silently_at_any_width` could not see it: it
    /// varies the width and differences adjacent renders, and a row that is
    /// never drawn at all leaves nothing to difference. So this sweeps width
    /// with the preview's height fixed, and asserts both halves — a note that
    /// fits carries no `…` — so an ellipsis stuck on unconditionally fails too.
    #[test]
    fn a_note_longer_than_its_preview_ends_in_an_ellipsis() {
        const NOTE: &str = "A task past its due date reads in red, and the counter in the \
                            border frames it as overdue. This one is here to show that; \
                            delete it with d once you have seen it.";
        const HEIGHT: u16 = 12;
        let (mut p, _dir) = panel("preview-cut");
        let mut task = Task::new(0, "This one is overdue", p.today);
        task.notes = Some(NOTE.to_string());
        p.store.add(task);
        p.refresh_view();

        let (mut cut, mut whole) = (0, 0);
        for width in 8..=200u16 {
            let screen = screen_of(&mut p, width, HEIGHT);
            let rows: Vec<&str> = screen.lines().collect();
            // The preview's two rows sit directly above the status line.
            let first = rows[usize::from(HEIGHT) - 3].trim_end();
            let last = rows[usize::from(HEIGHT) - 2].trim_end();
            let wrapped = crate::grid::wrap(NOTE, usize::from(width));
            assert_eq!(first, wrapped[0].trim_end(), "at width {width}");
            if wrapped.len() > 2 {
                cut += 1;
                assert!(
                    last.ends_with('…'),
                    "a note needing {} rows was cut to 2 without saying so at width {width}:\n{screen}",
                    wrapped.len()
                );
            } else {
                whole += 1;
                assert!(
                    !screen.contains('…'),
                    "a note that fits must not claim to be cut at width {width}:\n{screen}"
                );
            }
        }
        assert!(
            cut > 0 && whole > 0,
            "the sweep must reach both a cut and a whole note: cut {cut}, whole {whole}"
        );
    }

    /// The preview reads only as much of a note as its rows can show. A run of
    /// spaces at a break draws nothing, since the break takes it, so a budget
    /// that counted every space as something a row draws would be used up by
    /// padding and cut the words after it short with a row to spare: at 20
    /// cells `Call Bob.`, thirty spaces and `Re: invoice` would draw `R…`
    /// where the whole note fits.
    #[test]
    fn a_note_padded_with_spaces_still_shows_what_follows() {
        const HEIGHT: u16 = 12;
        let (mut p, _dir) = panel("preview-padding");
        let mut task = Task::new(0, "Call Bob", p.today);
        task.id = p.store.add(task.clone());
        p.refresh_view();

        let (mut cut, mut whole) = (0, 0);
        for padding in [30, 100, 300] {
            let note = format!("Call Bob.{}Re: invoice", " ".repeat(padding));
            task.notes = Some(note.clone());
            assert!(p.store.update(task.clone()));
            for width in 8..=60u16 {
                let screen = screen_of(&mut p, width, HEIGHT);
                let rows: Vec<&str> = screen.lines().collect();
                let preview = [
                    rows[usize::from(HEIGHT) - 3].trim_end(),
                    rows[usize::from(HEIGHT) - 2].trim_end(),
                ];
                let wrapped = crate::grid::wrap(&note, usize::from(width));
                assert_eq!(preview[0], wrapped[0].trim_end(), "{padding} at {width}");
                if wrapped.len() > 2 {
                    cut += 1;
                    assert!(preview[1].ends_with('…'), "{padding} at {width}:\n{screen}");
                } else {
                    whole += 1;
                    let second = wrapped.get(1).map_or("", |row| row.trim_end());
                    assert_eq!(preview[1], second, "{padding} at {width}:\n{screen}");
                }
            }
        }
        assert!(
            cut > 0 && whole > 0,
            "the sweep must reach both a cut and a whole note: cut {cut}, whole {whole}"
        );
    }

    #[test]
    fn adding_a_task_through_the_form_persists_it() {
        let (mut p, _dir) = panel("add");
        add_task(&mut p, "Publish placeholder");

        assert_eq!(p.store.tasks().len(), 1);
        assert_eq!(p.store.tasks()[0].title, "Publish placeholder");
        assert_eq!(p.view.len(), 1, "the new task must be visible");
        assert!(matches!(p.mode, Mode::List), "the form must close on save");

        // And it reached disk, not just memory.
        let reloaded = TaskStore::load(p.store.path()).unwrap();
        assert_eq!(reloaded.tasks().len(), 1);
    }

    #[test]
    fn the_form_captures_input_so_typing_q_cannot_quit() {
        let (mut p, _dir) = panel("capture");
        assert!(!p.captures_input(), "the list must not swallow global keys");

        press(&mut p, KeyCode::Char('a'));
        assert!(p.captures_input(), "an open form must swallow global keys");

        type_str(&mut p, "quit? q!");
        press(&mut p, KeyCode::Enter);
        assert_eq!(p.store.tasks()[0].title, "quit? q!");
    }

    #[test]
    fn a_blank_title_is_rejected_and_the_form_stays_open() {
        let (mut p, _dir) = panel("blank");
        press(&mut p, KeyCode::Char('a'));
        press(&mut p, KeyCode::Enter);

        assert!(p.store.tasks().is_empty(), "nothing should be created");
        match &p.mode {
            Mode::Edit(form) => {
                assert!(form.error.is_some(), "the failure must be explained");
            }
            _ => panic!("the form must stay open after a rejected save"),
        }
    }

    #[test]
    fn escape_cancels_without_creating_anything() {
        let (mut p, _dir) = panel("cancel");
        press(&mut p, KeyCode::Char('a'));
        type_str(&mut p, "never saved");
        press(&mut p, KeyCode::Esc);

        assert!(p.store.tasks().is_empty());
        assert!(matches!(p.mode, Mode::List));
    }

    #[test]
    fn a_bad_due_date_is_rejected_without_losing_the_typed_title() {
        let (mut p, _dir) = panel("baddate");
        press(&mut p, KeyCode::Char('a'));
        type_str(&mut p, "Ship it");
        press(&mut p, KeyCode::Tab); // Notes
        press(&mut p, KeyCode::Tab); // Due
        type_str(&mut p, "someday");
        press(&mut p, KeyCode::Enter);

        assert!(p.store.tasks().is_empty());
        match &p.mode {
            Mode::Edit(form) => {
                assert!(form.error.is_some());
                assert_eq!(form.title.value(), "Ship it", "typed input must survive");
            }
            _ => panic!("the form must stay open"),
        }
    }

    #[test]
    fn the_form_round_trips_every_field() {
        let (mut p, _dir) = panel("fields");
        press(&mut p, KeyCode::Char('a'));
        type_str(&mut p, "Full task");
        press(&mut p, KeyCode::Tab);
        type_str(&mut p, "some detail");
        press(&mut p, KeyCode::Tab);
        type_str(&mut p, "tomorrow");
        press(&mut p, KeyCode::Tab); // Priority
        press(&mut p, KeyCode::Right); // Low -> None
        press(&mut p, KeyCode::Tab);
        type_str(&mut p, "rust, mirador");
        press(&mut p, KeyCode::Enter);

        let task = &p.store.tasks()[0];
        assert_eq!(task.title, "Full task");
        assert_eq!(task.notes.as_deref(), Some("some detail"));
        let tomorrow = p.today.checked_add(jiff::Span::new().days(1)).unwrap();
        assert_eq!(task.due, Some(tomorrow));
        assert_eq!(task.priority, Priority::None);
        assert_eq!(task.tags, vec!["rust".to_string(), "mirador".to_string()]);
    }

    #[test]
    fn tags_accept_a_leading_hash_and_either_separator() {
        let (mut p, _dir) = panel("tags");
        press(&mut p, KeyCode::Char('a'));
        type_str(&mut p, "Tagged");
        for _ in 0..4 {
            press(&mut p, KeyCode::Tab);
        }
        type_str(&mut p, "#one  two,,#three");
        press(&mut p, KeyCode::Enter);

        assert_eq!(
            p.store.tasks()[0].tags,
            vec!["one".to_string(), "two".to_string(), "three".to_string()]
        );
    }

    #[test]
    fn space_toggles_completion_and_hides_the_task() {
        let (mut p, _dir) = panel("toggle");
        add_task(&mut p, "Do the thing");
        assert_eq!(p.view.len(), 1);

        press(&mut p, KeyCode::Char(' '));
        assert!(p.store.tasks()[0].done);
        assert!(p.store.tasks()[0].completed.is_some());
        assert!(p.view.is_empty(), "completed tasks hide by default");

        // Reveal completed tasks, then reopen it.
        press(&mut p, KeyCode::Char('c'));
        assert_eq!(p.view.len(), 1);
        press(&mut p, KeyCode::Char(' '));
        assert!(!p.store.tasks()[0].done);
        assert!(p.store.tasks()[0].completed.is_none());
    }

    #[test]
    fn editing_updates_in_place_rather_than_creating_a_duplicate() {
        let (mut p, _dir) = panel("edit");
        add_task(&mut p, "Original");
        let id = p.store.tasks()[0].id;

        press(&mut p, KeyCode::Char('e'));
        // Clear the pre-filled title, then retype.
        for _ in 0.."Original".len() {
            press(&mut p, KeyCode::Backspace);
        }
        type_str(&mut p, "Revised");
        press(&mut p, KeyCode::Enter);

        assert_eq!(p.store.tasks().len(), 1, "editing must not duplicate");
        assert_eq!(p.store.tasks()[0].id, id, "the id must be stable");
        assert_eq!(p.store.tasks()[0].title, "Revised");
    }

    #[test]
    fn delete_requires_confirmation() {
        let (mut p, _dir) = panel("delete");
        add_task(&mut p, "Doomed");

        press(&mut p, KeyCode::Char('d'));
        assert!(matches!(p.mode, Mode::ConfirmDelete { .. }));

        // Anything other than y backs out.
        press(&mut p, KeyCode::Char('n'));
        assert_eq!(p.store.tasks().len(), 1, "n must not delete");

        // Enter above all: it is the most reflexive key at a confirmation, the
        // prompt promises "any other key cancel", and deleting has no undo.
        press(&mut p, KeyCode::Char('d'));
        press(&mut p, KeyCode::Enter);
        assert_eq!(
            p.store.tasks().len(),
            1,
            "Enter must cancel, exactly as the prompt says it does"
        );

        press(&mut p, KeyCode::Char('d'));
        press(&mut p, KeyCode::Char('y'));
        assert!(p.store.tasks().is_empty());
        assert!(p.view.is_empty(), "{:?}", p.view);
    }

    #[test]
    fn priority_cycles_from_the_list() {
        let (mut p, _dir) = panel("priority");
        add_task(&mut p, "Rank me");
        assert_eq!(p.store.tasks()[0].priority, Priority::Low);

        press(&mut p, KeyCode::Char('p'));
        assert_eq!(p.store.tasks()[0].priority, Priority::None);
        press(&mut p, KeyCode::Char('p'));
        assert_eq!(p.store.tasks()[0].priority, Priority::High);
    }

    #[test]
    fn navigation_clamps_at_both_ends() {
        let (mut p, _dir) = panel("nav");
        for i in 0..3 {
            add_task(&mut p, &format!("task {i}"));
        }
        assert_eq!(p.view.len(), 3);

        press(&mut p, KeyCode::Char('g'));
        assert_eq!(p.list_state.selected(), Some(0));
        for _ in 0..10 {
            press(&mut p, KeyCode::Char('k'));
        }
        assert_eq!(p.list_state.selected(), Some(0), "must not go negative");

        press(&mut p, KeyCode::Char('G'));
        assert_eq!(p.list_state.selected(), Some(2));
        for _ in 0..10 {
            press(&mut p, KeyCode::Char('j'));
        }
        assert_eq!(
            p.list_state.selected(),
            Some(2),
            "must not run past the end"
        );
    }

    #[test]
    fn navigation_on_an_empty_list_is_harmless() {
        let (mut p, _dir) = panel("empty-nav");
        for code in [
            KeyCode::Char('j'),
            KeyCode::Char('k'),
            KeyCode::Char('g'),
            KeyCode::Char('G'),
            KeyCode::Char(' '),
            KeyCode::Char('p'),
            KeyCode::Char('e'),
            KeyCode::Char('d'),
        ] {
            press(&mut p, code);
        }
        assert!(p.store.tasks().is_empty());
        assert_eq!(p.list_state.selected(), None);
    }

    #[test]
    fn filtering_narrows_the_view_and_escape_restores_it() {
        let (mut p, _dir) = panel("filter");
        add_task(&mut p, "Buy milk");
        add_task(&mut p, "Write docs");

        press(&mut p, KeyCode::Char('/'));
        type_str(&mut p, "milk");
        assert_eq!(p.view.len(), 1, "the filter applies as you type");
        press(&mut p, KeyCode::Enter);
        assert_eq!(p.filter, "milk");

        press(&mut p, KeyCode::Char('/'));
        press(&mut p, KeyCode::Esc);
        assert!(p.filter.is_empty(), "Esc must clear the filter");
        assert_eq!(p.view.len(), 2);
    }

    #[test]
    fn the_selection_stays_on_the_same_task_when_the_view_changes() {
        let (mut p, _dir) = panel("selection");
        add_task(&mut p, "alpha");
        add_task(&mut p, "beta");
        add_task(&mut p, "gamma");

        press(&mut p, KeyCode::Char('G'));
        let selected = p.selected_id().unwrap();

        // Changing sort reorders the list; the cursor should follow the task.
        press(&mut p, KeyCode::Char('s'));
        assert_eq!(p.selected_id(), Some(selected));
    }

    #[test]
    fn unhandled_keys_fall_through_to_the_application() {
        let (mut p, _dir) = panel("fallthrough");
        let outcome = p.handle_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE));
        assert_eq!(
            outcome,
            KeyOutcome::Ignored,
            "Tab must reach the app so focus can move"
        );
    }

    /// Building only the rows on screen means `List` is handed a window and
    /// never sees the scroll, so the panel keeps it. Walk a list three
    /// screens long down and back: the marked row is always the selected
    /// task, and a click always lands on the task under it — a scroll left
    /// at the top maps a click on the last screen to the first. Which task
    /// is under the row is read off the screen *before* the click: drawn
    /// after it, the frame scrolls to whatever was selected, and any task at
    /// all would look like the one clicked.
    #[test]
    fn a_long_list_scrolls_and_clicks_as_it_always_did() {
        let (mut p, _guard) = panel("window");
        for i in 0..30 {
            add_task(&mut p, &format!("Task {i:02}"));
        }
        press(&mut p, KeyCode::Char('g'));

        let selected_title = |p: &TodoPanel| {
            let id = p.selected_id().expect("a selection");
            p.store.get(id).expect("the task").title.clone()
        };
        let keys = std::iter::repeat_n(KeyCode::Char('j'), 29)
            .chain(std::iter::repeat_n(KeyCode::Char('k'), 29));
        for (step, code) in keys.enumerate() {
            press(&mut p, code);
            let screen = screen_of(&mut p, 40, 12);
            let title = selected_title(&p);
            let marked = screen
                .lines()
                .find(|row| row.contains('▸'))
                .unwrap_or_else(|| panic!("{step}: a row is marked:\n{screen}"));
            assert!(marked.contains(&title), "{step}: {title}:\n{screen}");
        }

        press(&mut p, KeyCode::Char('G'));
        let before = screen_of(&mut p, 40, 12);
        let area = p.list_area.expect("the list was drawn");
        let first_on_screen = p.list_state.offset();
        assert!(first_on_screen > 0, "the last screen is scrolled");
        // Below the top row, so a click that forgets where the list starts on
        // screen misses as surely as one that forgets the scroll.
        let row = area.y + 2;
        let under = before
            .lines()
            .nth(usize::from(row))
            .and_then(|line| line.find("Task ").map(|at| line[at..at + 7].to_owned()))
            .unwrap_or_else(|| panic!("a task is drawn on row {row}:\n{before}"));
        assert_ne!(selected_title(&p), under, "the click has somewhere to go");
        let click = MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: area.x + 4,
            row,
            modifiers: KeyModifiers::NONE,
        };
        p.handle_mouse(click, area);
        assert_eq!(selected_title(&p), under, "clicked row {row} of:\n{before}");
    }

    /// The form's placeholders were drawn at their natural width, so a form
    /// narrower than about 27 columns let the terminal cut them: `what needs
    /// d`, a word nobody wrote. Whole, or cut with `…`, at every width.
    #[test]
    fn the_forms_placeholders_are_whole_or_say_they_were_cut() {
        let (mut panel, _guard) = panel("form-placeholders");
        press(&mut panel, KeyCode::Char('a'));
        // On priority, every text field is empty and unfocused.
        for _ in 0..3 {
            press(&mut panel, KeyCode::Tab);
        }
        let fields = [
            ("Title", "what needs doing"),
            ("Notes", "optional detail"),
            ("Due", "empty for none"),
            ("Tags", "comma separated"),
        ];
        let mut cut = 0;
        for width in 12..=40u16 {
            let screen = screen_of(&mut panel, width, 20);
            for (label, placeholder) in fields {
                let row = screen
                    .lines()
                    .find(|row| row.contains(&format!("│{label} ")))
                    .unwrap_or_else(|| panic!("{width}: `{label}` is drawn:\n{screen}"));
                let shown = row
                    .split_once(label)
                    .map_or("", |(_, rest)| rest)
                    .trim_end()
                    .trim_end_matches('│')
                    .trim();
                if shown == placeholder {
                    continue;
                }
                let kept = shown.strip_suffix('…').unwrap_or_else(|| {
                    panic!("{width}: `{placeholder}` cut silently to {shown:?}:\n{screen}")
                });
                assert!(placeholder.starts_with(kept), "{width}: {shown:?}");
                cut += 1;
            }
        }
        assert!(cut > 0, "the sweep reached a width that cuts a placeholder");
    }

    /// An empty list says how to add the first task, with the key
    /// `[todo.keys]` gave `add` — it said `a` whatever the table said — and
    /// without the offer when `add` is unbound.
    #[test]
    fn an_empty_list_names_the_add_key_it_has() {
        let text = |keys: &str| {
            let (mut panel, _g) = panel("empty-keys");
            let config: crate::config::Config =
                toml::from_str(&format!("[todo.keys]\n{keys}")).expect("a config");
            panel.set_keys(&config);
            screen_of(&mut panel, 60, 12)
        };
        let moved = text("add = \"z\"");
        assert!(moved.contains("Press `z` to add one."), "{moved}");
        assert!(!moved.contains("`a`"), "{moved}");

        let unbound = text("add = []");
        assert!(unbound.contains("No tasks yet."), "{unbound}");
        assert!(!unbound.contains("Press"), "{unbound}");

        assert!(text("").contains("No tasks yet. Press `a` to add one."));
    }

    /// Invariant 19 for the empty list: its message arrives whole wherever
    /// the list has the rows for it, and otherwise its last row ends in `…`.
    /// It was cut to one row with an `…` in a list several rows tall, so at
    /// 20 cells it read `No tasks yet. Press…` over blank rows and the key it
    /// names was gone. Swept over height as well as width, since a cut along
    /// the height is the one a width sweep cannot see. The room starts at
    /// row 0: a sweep that started under it approved `by smart` over `No
    /// tasks yet. Press…` at 20x3.
    #[test]
    fn an_empty_lists_message_is_whole_where_it_has_the_rows() {
        let whole = "No tasks yet. Press `a` to add one.";
        // The longest word; narrower, a word is broken and the rows cannot
        // be joined back into the sentence.
        let longest = 5;
        let (mut panel, _g) = panel("empty-cut");
        let (mut cut, mut wrapped) = (0, 0);
        for height in 2..=10u16 {
            for width in 4..=48u16 {
                let screen = screen_of(&mut panel, width, height);
                let rows: Vec<&str> = screen.lines().map(str::trim_end).collect();
                // The status is the last row, and the list, with no column
                // header over an empty view, is every row above it. Row 0
                // included: a summary there said `by smart`, the sort order
                // of nothing, and took a row the key needed.
                let room = usize::from(height - 1);
                let lines: Vec<&str> = rows[..room]
                    .iter()
                    .copied()
                    .take_while(|row| !row.is_empty())
                    .collect();
                assert!(!lines.is_empty(), "at {width}x{height}: {rows:#?}");
                let said = lines.join(" ");
                let needed = usize::from(crate::grid::wrapped_height(whole, width));
                if needed > room {
                    cut += 1;
                    assert!(said.ends_with('…'), "at {width}x{height}: {rows:#?}");
                    assert_eq!(lines.len(), room, "at {width}x{height}: {rows:#?}");
                } else if width >= longest {
                    assert_eq!(said, whole, "at {width}x{height}: {rows:#?}");
                    wrapped += usize::from(needed > 1);
                }
            }
        }
        assert!(cut > 0, "the sweep reached a size that cuts the message");
        assert!(wrapped > 0, "the sweep reached a size that wraps it");
    }
}