mach-tui 0.3.2

A terminal-first task manager for people who live in the shell and work with agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
//! All drawing: a Categories panel on the left, a Tasks panel on the
//! right, and a status line along the bottom. Each panel is a rounded
//! block whose border lights up when it holds focus.

use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Margin, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::Text;
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, BorderType, Cell, Clear, Gauge, List, ListItem, Padding, Paragraph, Row, Scrollbar,
    ScrollbarOrientation, ScrollbarState, Table,
};
use ratatui_image::{Resize, StatefulImage};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;

use crate::app::{App, Focus, MessageKind, Mode, SETTINGS_ITEMS, UpdateActivity};
use crate::banner;
use crate::due;
use crate::form::Field;
use crate::theme::Theme;

/// Outer width of the sidebar, borders and padding included.
pub const SIDEBAR_WIDTH: u16 = 26;
/// `[ ]` / `[✓]` in the task list and body subtasks.
pub const DONE_MARK_WIDTH: u16 = 3;
/// Right column shorter than this → no bottom preview (list only).
const PREVIEW_SPLIT_MIN: u16 = 16;
/// Minimum height of the list half when the preview is below.
const LIST_MIN: u16 = 6;
/// Minimum height of the preview / docked editor half (bottom layout).
const PREVIEW_MIN: u16 = 8;
/// Minimum list width when the preview sits to the right.
const LIST_WIDTH_MIN: u16 = 24;
/// Minimum preview width when docked on the right.
const PREVIEW_WIDTH_MIN: u16 = 28;
/// Whole right column narrower than this → no side preview.
const PREVIEW_SIDE_MIN: u16 = LIST_WIDTH_MIN + PREVIEW_WIDTH_MIN + 1;
pub const MIN_TERMINAL_WIDTH: u16 = 60;
pub const MIN_TERMINAL_HEIGHT: u16 = 16;

pub fn draw(f: &mut Frame, app: &mut App) {
    let area = f.area();
    // Every frame owns its hit targets. Hidden overlays and undersized
    // terminals must never retain clickable geometry from an older frame.
    app.areas = crate::app::Areas::default();
    if let Some(form) = &mut app.form {
        form.areas = crate::form::FieldAreas::default();
        form.body_menu_area = None;
        form.image_hits.clear();
        if let Some(picker) = &mut form.picker {
            picker.layout = crate::duepicker::PickerLayout::default();
        }
    }
    if let Some(form) = &mut app.category_form {
        form.name_area = Rect::ZERO;
        form.description_area = Rect::ZERO;
    }

    if area.width < MIN_TERMINAL_WIDTH || area.height < MIN_TERMINAL_HEIGHT {
        let p = Paragraph::new(format!(
            "too small · need {MIN_TERMINAL_WIDTH}×{MIN_TERMINAL_HEIGHT}"
        ))
        .centered();
        f.render_widget(p, area);
        return;
    }

    let theme = app.theme();
    let [content, status] =
        Layout::vertical([Constraint::Min(3), Constraint::Length(3)]).areas(area);
    // The panels sit against each other: two borders is already a
    // divider, a gap on top of that is just slack.
    // A column of air between the panels keeps each one's focus colour
    // unambiguous.
    let [sidebar, right] =
        Layout::horizontal([Constraint::Length(SIDEBAR_WIDTH), Constraint::Min(20)])
            .spacing(1)
            .areas(content);

    let mut modal_task_form = false;
    draw_sidebar(f, app, &theme, sidebar);
    if let Some((list, preview_rect)) =
        split_tasks_and_preview(right, &app.settings.preview_position)
    {
        app.areas.preview = preview_rect;
        draw_tasks(f, app, &theme, list);
        match app.mode {
            Mode::TaskForm => match docked_task_form_layout(preview_rect) {
                Some(layout) => draw_task_form(f, app, &theme, preview_rect, layout),
                None => {
                    draw_task_preview(f, app, &theme, preview_rect);
                    modal_task_form = true;
                }
            },
            _ => draw_task_preview(f, app, &theme, preview_rect),
        }
    } else {
        app.areas.preview = Rect::ZERO;
        draw_tasks(f, app, &theme, right);
        if app.mode == Mode::TaskForm {
            modal_task_form = true;
        }
    }
    draw_status(f, app, &theme, status);
    // Palette floats above the status bar.
    if app.mode == Mode::Slash {
        draw_slash_palette(f, app, &theme, status);
    }

    match app.mode {
        Mode::Help => draw_help(f, app, &theme, area),
        Mode::Settings => draw_settings(f, app, &theme, area),
        Mode::Welcome => draw_welcome(f, &theme, area),
        Mode::WhatsNew => draw_whats_new(f, &theme, area),
        Mode::CategoryForm => draw_category_form(f, app, &theme, area),
        Mode::TaskForm if modal_task_form => {
            // Draw the fallback last, over the intact panels and task preview.
            draw_task_form(f, app, &theme, area, TaskFormLayout::Modal);
        }
        Mode::TaskForm => {} // Already drawn in the task preview pane.
        _ => {}
    }
}

/// Split the right column into task list + preview when there is room.
/// `position` is `"bottom"` (default) or `"right"`. Falls back to bottom
/// when a side-by-side split will not fit, then to no preview.
fn split_tasks_and_preview(right: Rect, position: &str) -> Option<(Rect, Rect)> {
    if position == "right"
        && let Some(pair) = split_preview_right(right)
    {
        return Some(pair);
    }
    split_preview_bottom(right)
}

fn split_preview_bottom(right: Rect) -> Option<(Rect, Rect)> {
    if right.height < PREVIEW_SPLIT_MIN {
        return None;
    }
    let [list, preview] = Layout::vertical([
        Constraint::Min(LIST_MIN),
        Constraint::Length((right.height / 2).max(PREVIEW_MIN)),
    ])
    .spacing(0)
    .areas(right);
    if list.height < LIST_MIN || preview.height < PREVIEW_MIN {
        return None;
    }
    Some((list, preview))
}

fn split_preview_right(right: Rect) -> Option<(Rect, Rect)> {
    if right.width < PREVIEW_SIDE_MIN || right.height < PREVIEW_MIN {
        return None;
    }
    let preview_w = (right.width / 2).max(PREVIEW_WIDTH_MIN);
    let [list, preview] = Layout::horizontal([
        Constraint::Min(LIST_WIDTH_MIN),
        Constraint::Length(preview_w),
    ])
    .spacing(1)
    .areas(right);
    if list.width < LIST_WIDTH_MIN || preview.width < PREVIEW_WIDTH_MIN {
        return None;
    }
    Some((list, preview))
}

// --------------------------------------------------------- task dialog

const TASK_FORM_WIDE_CHROME: u16 = 9;
const TASK_FORM_COMPACT_CHROME: u16 = 15;
const TASK_FORM_MIN_BODY_HEIGHT: u16 = 3;
const TASK_FORM_WIDE_MIN_WIDTH: u16 = 56;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TaskFormLayout {
    DockedWide,
    DockedCompact,
    Modal,
}

impl TaskFormLayout {
    fn is_docked(self) -> bool {
        !matches!(self, Self::Modal)
    }

    fn is_compact(self) -> bool {
        matches!(self, Self::DockedCompact)
    }
}

fn docked_task_form_layout(area: Rect) -> Option<TaskFormLayout> {
    if area.width >= TASK_FORM_WIDE_MIN_WIDTH
        && area.height >= TASK_FORM_WIDE_CHROME + TASK_FORM_MIN_BODY_HEIGHT
    {
        Some(TaskFormLayout::DockedWide)
    } else if area.width >= PREVIEW_WIDTH_MIN
        && area.height >= TASK_FORM_COMPACT_CHROME + TASK_FORM_MIN_BODY_HEIGHT
    {
        Some(TaskFormLayout::DockedCompact)
    } else {
        None
    }
}

/// Title, category/due/flags metadata, then the body: a free stack of prose,
/// to-dos and pictures with a `/` menu for making new ones.
///
/// Docked layouts fill the permanent task preview pane. The modal layout is
/// centered over `area` when that pane cannot expose every field honestly.
fn draw_task_form(f: &mut Frame, app: &mut App, theme: &Theme, area: Rect, layout: TaskFormLayout) {
    // Disjoint borrows: the form owns the fields, the store owns the
    // decoded images.
    let App {
        form,
        images: store,
        ..
    } = app;
    let Some(form) = form.as_mut() else { return };

    let rect = if layout.is_docked() {
        area
    } else {
        let width = 92.min(area.width.saturating_sub(4));
        let body_height = area
            .height
            .saturating_sub(TASK_FORM_WIDE_CHROME)
            .clamp(TASK_FORM_MIN_BODY_HEIGHT, 22);
        centered(
            area,
            width,
            (TASK_FORM_WIDE_CHROME + body_height).min(area.height),
        )
    };
    let h_pad = if layout.is_docked() { 1 } else { 2 };
    let block = Block::bordered()
        .border_type(BorderType::Thick)
        .border_style(theme.accent_text())
        .title(Span::styled(
            format!(" {} ", form.title_text()),
            theme.accent_text().bold(),
        ))
        .padding(Padding::new(h_pad, h_pad, 0, 0));
    let inner = block.inner(rect);
    f.render_widget(Clear, rect);
    f.render_widget(block, rect);

    let (title_box, category_box, due_box, importance_box, body_box, hint) = if layout.is_compact()
    {
        let [title, category, due, importance, body, hint] = Layout::vertical([
            Constraint::Length(3),
            Constraint::Length(3),
            Constraint::Length(3),
            Constraint::Length(3),
            Constraint::Min(TASK_FORM_MIN_BODY_HEIGHT),
            Constraint::Length(1),
        ])
        .areas(inner);
        (title, category, due, importance, body, hint)
    } else {
        let [title, metadata, body, hint] = Layout::vertical([
            Constraint::Length(3),
            Constraint::Length(3),
            Constraint::Min(TASK_FORM_MIN_BODY_HEIGHT),
            Constraint::Length(1),
        ])
        .areas(inner);
        // Category takes the rest; Due fits a formatted date+time;
        // Flags fits ⚑⚑⚑.
        let [category, due, importance] = Layout::horizontal([
            Constraint::Fill(1),
            Constraint::Length(20),
            Constraint::Length(9),
        ])
        .spacing(1)
        .areas(metadata);
        (title, category, due, importance, body, hint)
    };

    // --- title ----------------------------------------------------------
    let focused = form.field == Field::Title;
    let box_inner = render_field_box(f, field_block("Title", focused, None, theme), title_box);
    form.areas.title = box_inner;
    let view = form.title.visible(box_inner.width as usize);
    if view.text.is_empty() {
        render_or_placeholder(f, box_inner, "", "what needs doing?", theme);
    } else {
        f.render_widget(
            Paragraph::new(line_with_selection(
                &view.text,
                view.sel_cols,
                Style::new(),
                theme,
            )),
            box_inner,
        );
    }
    if focused {
        f.set_cursor_position((box_inner.x.saturating_add(view.cursor_col), box_inner.y));
    }

    // --- category -------------------------------------------------------
    let focused = form.field == Field::Category;
    let box_inner = render_field_box(
        f,
        field_block("Category", focused, None, theme),
        category_box,
    );
    form.areas.category = box_inner;
    let category = format!("{}", form.category_label());
    f.render_widget(
        Paragraph::new(truncate(&category, box_inner.width as usize)),
        box_inner,
    );

    // --- due -------------------------------------------------------------
    // Picker-only: show the value, no text cursor (Enter / click opens UI).
    // Store the outer box so the calendar left-aligns with the Due border.
    let focused = form.field == Field::Due;
    let box_inner = render_field_box(f, field_block("Due", focused, None, theme), due_box);
    form.areas.due = due_box;
    let view = form.due.visible(box_inner.width as usize);
    render_or_placeholder(f, box_inner, &view.text, "↵ Enter", theme);

    // --- importance ---------------------------------------------------------
    let focused = form.field == Field::Importance;
    let box_inner = render_field_box(
        f,
        field_block("Flags", focused, None, theme),
        importance_box,
    );
    form.areas.importance = box_inner;
    let marks = crate::model::importance_marks(form.importance);
    if marks.is_empty() {
        render_or_placeholder(f, box_inner, "", "", theme);
    } else {
        f.render_widget(
            Paragraph::new(Line::styled(marks, Style::new().fg(theme.error_color()))),
            box_inner,
        );
    }

    // --- body --------------------------------------------------------------
    let focused = form.field == Field::Body;
    let (done, total) = form.body.progress();
    let progress = (total > 0).then(|| format!("{done}/{total}"));
    let box_inner = render_field_box(f, field_block("Body", focused, progress, theme), body_box);
    form.areas.body = box_inner;
    draw_body(f, form, store, theme, box_inner, focused);
    scrollbar(
        f,
        theme,
        body_box,
        form.body.content_height(),
        box_inner.height as usize,
        form.body.scroll(),
        focused,
    );

    // --- error or key hints ---------------------------------------------
    let footer = match &form.error {
        Some(error) => Line::styled(
            truncate(error, hint.width as usize),
            Style::new()
                .fg(theme.error_color())
                .add_modifier(Modifier::BOLD),
        ),
        None => Line::styled(
            match layout {
                TaskFormLayout::DockedWide => "/ commands · Ctrl+Z undo · Ctrl+S save · Esc list",
                TaskFormLayout::DockedCompact => "/ · Ctrl+S save · Esc list",
                TaskFormLayout::Modal => "/ commands · Ctrl+Z undo · Ctrl+S save · Esc cancel",
            },
            Style::new().fg(theme.muted_color()),
        ),
    };
    f.render_widget(Paragraph::new(footer), hint);

    // Drawn last so it sits over the body box below it.
    // Picker/image lightbox use the full frame so they are not clipped.
    let overlay = f.area();
    if let Some(picker) = form.picker.as_mut() {
        draw_due_picker(f, theme, picker, form.areas.due, overlay);
    }

    // Preview the picture the cursor is on, or the first one otherwise.
    if form.preview
        && let Some(path) = form
            .body
            .selected_image()
            .or_else(|| form.body.images().first().cloned())
    {
        draw_image_preview(f, store, form, theme, &path, overlay);
    }
}

/// Read-only view of the selected task in the permanent preview pane.
fn draw_task_preview(f: &mut Frame, app: &mut App, theme: &Theme, area: Rect) {
    let focused = false;
    let block = panel("Task preview", focused, theme);
    let inner = block.inner(area);
    f.render_widget(block, area);
    if inner.height == 0 || inner.width == 0 {
        return;
    }

    let Some(task) = app.selected_task().cloned() else {
        app.invalidate_preview();
        let style = Style::new().fg(theme.muted_color());
        draw_box(f, inner, "Select a task · Enter to edit", style);
        return;
    };

    // One owned snapshot avoids a second selection lookup and lets the image
    // cache and preview editor be borrowed independently below.
    let image_paths: Vec<_> = task
        .body
        .iter()
        .filter_map(|block| match block {
            crate::model::Block::Image { attachment_id } => Some(app.images.resolve(attachment_id)),
            _ => None,
        })
        .collect();
    let todo = crate::model::todo_progress(&task);
    let title = task.title;
    let done = task.done;
    let due_s = due::display(&task.due, &app.settings.date_format);
    let importance = task.importance;
    let body_empty = task.body.is_empty();

    // Prefetch body pictures so they appear on the next frames.
    app.images.prefetch(image_paths);

    let flags = crate::model::importance_marks(importance);
    let mut meta = String::new();
    if !due_s.is_empty() {
        meta.push_str(&due_s);
    }
    if !flags.is_empty() {
        if !meta.is_empty() {
            meta.push_str("  ");
        }
        meta.push_str(&flags);
    }
    if let Some((d, t)) = todo {
        if !meta.is_empty() {
            meta.push_str("  ");
        }
        meta.push_str(&format!("{d}/{t}"));
    }

    let title_style = if done {
        Style::new()
            .fg(theme.muted_color())
            .add_modifier(Modifier::CROSSED_OUT | Modifier::BOLD)
    } else {
        Style::new().add_modifier(Modifier::BOLD)
    };

    let (title_row, meta_row, body_area) = if meta.is_empty() {
        let [t, b] = Layout::vertical([Constraint::Length(1), Constraint::Min(1)]).areas(inner);
        (t, None, b)
    } else {
        let [t, m, b] = Layout::vertical([
            Constraint::Length(1),
            Constraint::Length(1),
            Constraint::Min(1),
        ])
        .areas(inner);
        (t, Some(m), b)
    };

    f.render_widget(
        Paragraph::new(Line::styled(
            truncate(&title, title_row.width as usize),
            title_style,
        )),
        title_row,
    );
    if let Some(meta_row) = meta_row {
        f.render_widget(
            Paragraph::new(Line::styled(
                truncate(&meta, meta_row.width as usize),
                Style::new().fg(theme.muted_color()),
            )),
            meta_row,
        );
    }

    if body_area.height == 0 {
        return;
    }
    if body_empty {
        f.render_widget(
            Paragraph::new(Line::styled(
                "Enter to edit",
                Style::new().fg(theme.muted_color()),
            )),
            body_area,
        );
        return;
    }

    app.ensure_preview();
    let App {
        images: store,
        preview_form,
        ..
    } = app;
    if let Some(paint) = preview_form.as_mut() {
        draw_body(f, paint, store, theme, body_area, false);
        if paint.body.content_height() > usize::from(body_area.height) && body_area.height > 0 {
            let indicator = Rect {
                y: body_area.bottom() - 1,
                height: 1,
                ..body_area
            };
            f.render_widget(
                Paragraph::new(Line::styled(
                    "↓ more · Enter to edit",
                    Style::new()
                        .fg(theme.muted_color())
                        .add_modifier(Modifier::BOLD),
                )),
                indicator,
            );
        }
    }
}

/// One field of a dialog: a rounded box with its name on the border.
fn field_block<'a>(
    label: &'a str,
    focused: bool,
    note: Option<String>,
    theme: &Theme,
) -> Block<'a> {
    // Thick glyphs (┃/━) — terminal bold barely changes box lines.
    let (border, label_style) = if focused {
        (theme.accent_text(), theme.accent_text().bold())
    } else {
        (
            Style::new().fg(theme.muted_color()),
            Style::new()
                .fg(theme.muted_color())
                .add_modifier(Modifier::BOLD),
        )
    };
    let mut block = Block::bordered()
        .border_type(BorderType::Thick)
        .border_style(border)
        .title(Span::styled(format!(" {label} "), label_style))
        .padding(Padding::horizontal(1));
    if let Some(note) = note {
        block = block.title_top(
            Line::styled(format!(" {note} "), Style::new().fg(theme.muted_color())).right_aligned(),
        );
    }
    block
}

/// The category dialog: the same shape as a task's, with a name and a
/// note about what the category is for.
fn draw_category_form(f: &mut Frame, app: &mut App, theme: &Theme, area: Rect) {
    let Some(form) = &mut app.category_form else {
        return;
    };
    // Borders (2), name box (3), hint (1).
    const CHROME: u16 = 6;
    let text_height = area.height.saturating_sub(CHROME).clamp(3, 12);
    let width = 72.min(area.width.saturating_sub(4));
    let rect = centered(area, width, (CHROME + text_height).min(area.height));

    let block = Block::bordered()
        .border_type(BorderType::Thick)
        .border_style(theme.accent_text())
        .title(Span::styled(
            format!(" {} ", form.title_text()),
            theme.accent_text().bold(),
        ))
        .padding(Padding::horizontal(1));
    let inner = block.inner(rect);
    f.render_widget(Clear, rect);
    f.render_widget(block, rect);

    let [name_box, text_box, hint] = Layout::vertical([
        Constraint::Length(3),
        Constraint::Length(text_height),
        Constraint::Length(1),
    ])
    .areas(inner);

    let focused = !form.on_description;
    let box_inner = render_field_box(f, field_block("Name", focused, None, theme), name_box);
    form.name_area = box_inner;
    let view = form.name.visible(box_inner.width as usize);
    if view.text.is_empty() {
        render_or_placeholder(f, box_inner, "", "What to call it", theme);
    } else {
        f.render_widget(
            Paragraph::new(line_with_selection(
                &view.text,
                view.sel_cols,
                Style::new(),
                theme,
            )),
            box_inner,
        );
    }
    if focused {
        f.set_cursor_position((box_inner.x.saturating_add(view.cursor_col), box_inner.y));
    }

    let focused = form.on_description;
    let box_inner = render_field_box(
        f,
        field_block("Description", focused, None, theme),
        text_box,
    );
    form.description_area = box_inner;
    let (lines, cursor) = form
        .description
        .layout(box_inner.width as usize, box_inner.height);
    if form.description.is_empty() && form.description.menu.is_none() {
        render_or_placeholder(f, box_inner, "", "Press / for commands", theme);
    }
    for placed in lines {
        if matches!(placed.block, crate::body::Painted::Text { .. }) {
            draw_placed_text(f, theme, box_inner, &placed);
        }
    }
    if let (true, Some((row, col))) = (focused, cursor) {
        f.set_cursor_position((
            box_inner.x.saturating_add(col),
            box_inner.y.saturating_add(row),
        ));
    }
    if focused {
        draw_slash_menu(f, &form.description, theme, box_inner, cursor);
    }
    scrollbar(
        f,
        theme,
        text_box,
        form.description.content_height(),
        box_inner.height as usize,
        form.description.scroll(),
        focused,
    );

    let footer = match &form.error {
        Some(error) => Line::styled(
            truncate(error, hint.width as usize),
            Style::new()
                .fg(theme.error_color())
                .add_modifier(Modifier::BOLD),
        ),
        None => Line::styled(
            "/ commands · Ctrl+Z undo · Ctrl+S save · Esc cancel",
            Style::new().fg(theme.muted_color()),
        ),
    };
    f.render_widget(Paragraph::new(footer), hint);
}

/// The stack of blocks, plus the `/` menu when it is open.
fn draw_body(
    f: &mut Frame,
    form: &mut crate::form::TaskForm,
    store: &mut crate::image::ImageStore,
    theme: &Theme,
    area: Rect,
    focused: bool,
) {
    let menu_open = form.body.menu.is_some();
    if form.body.is_empty() && form.body.menu.is_none() {
        render_or_placeholder(f, area, "", "Press / for commands", theme);
    }
    let (blocks, cursor) = form.body.layout(area.width as usize, area.height);
    let scroll = form.body.scroll();
    // Graphics protocols ignore cell Clear. Drop placements when the `/`
    // menu closes or the body scrolls (pictures shrink/move) so the next
    // get re-emits cleanly. Pixels stay in RAM — encode only.
    if (form.menu_was_open && !menu_open) || form.body_scroll != scroll {
        store.clear_cache();
        f.render_widget(Clear, area);
    }
    form.menu_was_open = menu_open;
    form.body_scroll = scroll;
    // Only hide images the dropdown actually covers. Graphics protocols
    // cannot be "punched" cleanly, so an overlapping image becomes a
    // compact marker; anything the menu does not touch stays real.
    let menu_rect = slash_menu_rect(&form.body, area, cursor);
    form.body_menu_area = menu_rect;
    form.image_hits.clear();
    for placed in blocks {
        match &placed.block {
            crate::body::Painted::Image(path) => {
                let row = Rect {
                    y: area.y.saturating_add(placed.y),
                    height: placed.rows,
                    ..area
                };
                let covered = menu_rect.is_some_and(|m| rects_overlap(m, row));
                // Frame + type label only while the body field owns focus
                // and the cursor is on this picture — not when the dialog
                // opens on Title with the cursor still sitting on line 0.
                let show_frame = focused && placed.selected;
                if covered {
                    f.render_widget(Clear, row);
                    let hit = letterbox_rect(row, 4, 3);
                    draw_image_placeholder(f, theme, hit, show_frame);
                    form.image_hits.push((placed.line, hit));
                } else if let Some(hit) = draw_image(f, store, theme, path, row, show_frame) {
                    form.image_hits.push((placed.line, hit));
                }
            }
            crate::body::Painted::Text { .. } => {
                draw_placed_text(f, theme, area, &placed);
            }
        }
    }
    if focused && let Some((row, col)) = cursor {
        f.set_cursor_position((area.x.saturating_add(col), area.y.saturating_add(row)));
    }

    draw_slash_menu(f, &form.body, theme, area, cursor);
}

fn rects_overlap(a: Rect, b: Rect) -> bool {
    a.x < b.right() && b.x < a.right() && a.y < b.bottom() && b.y < a.bottom()
}

/// Screen rect of the open `/` dropdown, if any.
fn slash_menu_rect(
    body: &crate::body::BodyEditor,
    area: Rect,
    cursor: Option<(u16, u16)>,
) -> Option<Rect> {
    body.menu.as_ref()?;
    let commands = body.menu_commands();
    if commands.is_empty() {
        return None;
    }
    let width = 48.min(area.width);
    let height = u16::try_from(commands.len())
        .unwrap_or(u16::MAX)
        .saturating_add(2);
    let cursor_row = cursor.map(|(row, _)| row).unwrap_or(0);
    let below = area.y.saturating_add(cursor_row).saturating_add(1);
    let y = if area.bottom().saturating_sub(below) >= height {
        below
    } else {
        area.y.saturating_add(cursor_row).saturating_sub(height)
    };
    Some(Rect {
        x: area.x.saturating_add(
            cursor
                .map(|(_, col)| col)
                .unwrap_or(0)
                .min(area.width.saturating_sub(width)),
        ),
        y,
        width,
        height,
    })
}

/// Soft-wrapped text / list / link block (body and category description).
fn draw_placed_text(f: &mut Frame, theme: &Theme, area: Rect, placed: &crate::body::Placed) {
    let crate::body::Painted::Text { rows, kind } = &placed.block else {
        return;
    };
    let indent = kind.indent();
    let max_rows = placed.rows as usize;
    for (i, wr) in rows.iter().enumerate().take(max_rows) {
        let y = area
            .y
            .saturating_add(placed.y)
            .saturating_add(u16::try_from(i).unwrap_or(u16::MAX));
        if y >= area.bottom() {
            break;
        }
        let row = Rect {
            x: area.x,
            y,
            width: area.width,
            height: 1,
        };
        let base = match kind {
            crate::body::TextKind::Link => Style::new()
                .fg(theme.accent)
                .add_modifier(Modifier::UNDERLINED),
            crate::body::TextKind::Todo { done: true } => Style::new()
                .fg(theme.muted_color())
                .add_modifier(Modifier::CROSSED_OUT),
            _ => Style::new(),
        };
        let body = line_with_selection(&wr.text, wr.sel, base, theme);
        let line = if i == 0 {
            match kind {
                crate::body::TextKind::Todo { done: true } => Line::from(
                    [
                        vec![Span::styled("[✓] ", Style::new().fg(theme.success_color()))],
                        body.spans,
                    ]
                    .concat(),
                ),
                crate::body::TextKind::Todo { done: false } => Line::from(
                    [
                        vec![Span::styled("[ ] ", Style::new().fg(theme.muted_color()))],
                        body.spans,
                    ]
                    .concat(),
                ),
                crate::body::TextKind::Bullet => Line::from(
                    [
                        vec![Span::styled("", Style::new().fg(theme.muted_color()))],
                        body.spans,
                    ]
                    .concat(),
                ),
                crate::body::TextKind::Number(n) => Line::from(
                    [
                        vec![Span::styled(
                            format!("{n}. "),
                            Style::new().fg(theme.muted_color()),
                        )],
                        body.spans,
                    ]
                    .concat(),
                ),
                crate::body::TextKind::Link => Line::from(
                    [
                        vec![Span::styled("", Style::new().fg(theme.muted_color()))],
                        body.spans,
                    ]
                    .concat(),
                ),
                crate::body::TextKind::Plain => body,
            }
        } else if indent > 0 {
            // Continuation rows line up under the text, past the prefix.
            Line::from([vec![Span::raw(" ".repeat(indent))], body.spans].concat())
        } else {
            body
        };
        f.render_widget(Paragraph::new(line), row);
    }
}

/// Compact cell stand-in when the `/` menu covers an image slot.
fn draw_image_placeholder(f: &mut Frame, theme: &Theme, area: Rect, selected: bool) {
    if area.width == 0 || area.height == 0 {
        return;
    }
    let rect = Rect { height: 1, ..area };
    let style = if selected {
        theme.accent_text()
    } else {
        Style::new().fg(theme.muted_color())
    };
    f.render_widget(Clear, rect);
    f.render_widget(Paragraph::new(Line::styled(" [image] ", style)), rect);
}

/// Full-size stand-in while a body/preview image is loading or failed.
enum ImageSlotKind<'a> {
    Loading,
    Broken { detail: &'a str },
}

/// Letterbox a content box into `area` (after a 1-cell frame margin),
/// matching how real pictures are laid out. `aspect_w` / `aspect_h` are
/// relative; unknown images use 4×3.
fn letterbox_rect(area: Rect, aspect_w: u16, aspect_h: u16) -> Rect {
    if area.width < 3 || area.height < 3 {
        return area;
    }
    let inner = area.inner(Margin {
        horizontal: 1,
        vertical: 1,
    });
    let aw = u32::from(aspect_w.max(1));
    let ah = u32::from(aspect_h.max(1));
    let iw = u32::from(inner.width);
    let ih = u32::from(inner.height);
    let (pw, ph) = if iw * ah <= ih * aw {
        let pw = iw;
        let ph = (iw * ah / aw).clamp(1, ih);
        (pw as u16, ph as u16)
    } else {
        let ph = ih;
        let pw = (ih * aw / ah).clamp(1, iw);
        (pw as u16, ph as u16)
    };
    centered(inner, pw, ph)
}

/// Outer area used by preview stand-ins (inner content + 1-cell frame).
fn preview_slot_area(inner: Rect) -> Rect {
    Rect {
        x: inner.x.saturating_sub(1),
        y: inner.y.saturating_sub(1),
        width: inner.width.saturating_add(2),
        height: inner.height.saturating_add(2),
    }
}

fn draw_image_slot(
    f: &mut Frame,
    theme: &Theme,
    area: Rect,
    kind: ImageSlotKind<'_>,
    selected: bool,
) {
    if area.width < 3 || area.height < 2 {
        return;
    }
    let border = if selected {
        theme.accent_text()
    } else {
        Style::new().fg(theme.muted_color())
    };
    let (icon, title, title_style, detail) = match kind {
        ImageSlotKind::Loading => ("", "loading", Style::new().fg(theme.muted_color()), None),
        ImageSlotKind::Broken { detail } => (
            "",
            "broken image",
            Style::new().fg(theme.error_color()),
            Some(detail),
        ),
    };
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(border);
    let inner = block.inner(area);
    f.render_widget(Clear, area);
    f.render_widget(block, area);
    if inner.width == 0 || inner.height == 0 {
        return;
    }

    let mut lines: Vec<Line> = Vec::new();
    // Vertical centre: pad, icon, title, optional detail.
    let content_rows: u16 = if detail.is_some() { 3 } else { 2 };
    let pad = inner.height.saturating_sub(content_rows) / 2;
    for _ in 0..pad {
        lines.push(Line::raw(""));
    }
    lines.push(
        Line::from(Span::styled(
            truncate(icon, inner.width as usize),
            title_style,
        ))
        .centered(),
    );
    lines.push(
        Line::from(Span::styled(
            truncate(title, inner.width as usize),
            title_style,
        ))
        .centered(),
    );
    if let Some(d) = detail {
        let d = d.trim();
        if !d.is_empty() {
            lines.push(
                Line::from(Span::styled(
                    truncate(d, inner.width as usize),
                    Style::new().fg(theme.muted_color()),
                ))
                .centered(),
            );
        }
    }
    f.render_widget(Paragraph::new(lines), inner);
}

/// The `/` menu floats under the line being typed on.
fn draw_slash_menu(
    f: &mut Frame,
    body: &crate::body::BodyEditor,
    theme: &Theme,
    area: Rect,
    cursor: Option<(u16, u16)>,
) {
    let Some(menu) = &body.menu else { return };
    let Some(rect) = slash_menu_rect(body, area, cursor) else {
        return;
    };
    let commands = body.menu_commands();
    // Inner width of a bordered block (no horizontal padding).
    let row_width = rect.width.saturating_sub(2) as usize;
    let lines: Vec<Line> = commands
        .iter()
        .enumerate()
        .map(|(i, command)| {
            let selected = i == menu.index.min(commands.len() - 1);
            dropdown_row(
                theme,
                selected,
                &format!("{:<14}", command.label()),
                command.hint(),
                row_width,
            )
        })
        .collect();
    let block = Block::bordered()
        .border_type(BorderType::Thick)
        .border_style(theme.accent_text())
        .title(Span::styled(
            format!(" /{} ", menu.query),
            Style::new().fg(theme.muted_color()),
        ));
    f.render_widget(Clear, rect);
    f.render_widget(Paragraph::new(lines).block(block), rect);
}

/// Calendar + clock, dropped under the due field. Date and time are both
/// set here — the Due field itself is not typed into.
fn draw_due_picker(
    f: &mut Frame,
    theme: &Theme,
    picker: &mut crate::duepicker::DuePicker,
    field: Rect,
    area: Rect,
) {
    use crate::duepicker::{PickerFocus, PickerLayout};

    let Some(day) = crate::duepicker::to_time_date(picker.day) else {
        return;
    };
    let mut events = ratatui::widgets::calendar::CalendarEventStore::today(
        Style::new().fg(theme.success_color()),
    );
    // Underlined rather than filled, to match the task list.
    events.add(day, theme.selection().add_modifier(Modifier::UNDERLINED));

    // Monthly needs 21 columns (` Su Mo …` / 7×3-wide day cells). Borders
    // add 2; keep the panel at least that wide so headers and days line up,
    // even when the Due field itself is narrower.
    const CAL_COLS: u16 = 21;
    let width = (CAL_COLS + 2).max(field.width).min(area.width);
    // Borders (2) + calendar (8) + blank (1) + clock (1) + title_bottom row.
    let height = 13;
    let below = field.bottom(); // flush under Due — field already includes its border
    let rect = Rect {
        // Left-align with the Due field's outer box.
        x: field.x.min(area.right().saturating_sub(width)),
        y: if area.bottom().saturating_sub(below) >= height {
            below
        } else {
            field.y.saturating_sub(height)
        },
        width,
        height,
    };
    let block = Block::bordered()
        .border_type(BorderType::Thick)
        .border_style(theme.accent_text())
        .title_bottom(
            Line::styled(" Tab · clear(x) ", Style::new().fg(theme.muted_color())).left_aligned(),
        );
    f.render_widget(Clear, rect);
    let inner = block.inner(rect);
    f.render_widget(block, rect);

    // Calendar (8) + blank gap (1) + clock (1).
    let [cal_area, _gap, time_area] = Layout::vertical([
        Constraint::Length(8),
        Constraint::Length(1),
        Constraint::Length(1),
    ])
    .areas(inner);
    let cal_area = Rect {
        width: CAL_COLS.min(cal_area.width),
        ..cal_area
    };
    let time_area = Rect {
        width: CAL_COLS.min(time_area.width),
        ..time_area
    };

    // Month header (1) + weekdays (1) + day grid — matches Monthly's layout.
    let days = Rect {
        x: cal_area.x,
        y: cal_area.y.saturating_add(2),
        width: cal_area.width,
        height: cal_area.height.saturating_sub(2),
    };

    let calendar = ratatui::widgets::calendar::Monthly::new(day, events)
        .show_month_header(theme.accent_text().add_modifier(Modifier::BOLD))
        .show_weekdays_header(Style::new().fg(theme.muted_color()))
        .show_surrounding(
            Style::new()
                .fg(theme.muted_color())
                .add_modifier(Modifier::DIM),
        );
    f.render_widget(calendar, cal_area);

    // Clock only — no "Time" label — centered under the calendar.
    let hour = format!("{:02}", picker.hour);
    let minute = format!("{:02}", picker.minute);
    let unit = |label: &str, on: bool| {
        if on {
            Span::styled(
                label.to_string(),
                theme.selection().add_modifier(Modifier::UNDERLINED),
            )
        } else {
            Span::styled(label.to_string(), Style::new())
        }
    };
    let time_line = Line::from(vec![
        unit(&hour, picker.focus == PickerFocus::Hour),
        Span::styled(":", Style::new().fg(theme.muted_color())),
        unit(&minute, picker.focus == PickerFocus::Minute),
    ])
    .centered();
    f.render_widget(Paragraph::new(time_line), time_area);

    // Hit targets for "HH" and "MM" within the centered "HH:MM" (5 cells).
    let clock_w = 5u16;
    let clock_x = time_area
        .x
        .saturating_add(time_area.width.saturating_sub(clock_w) / 2);
    picker.layout = PickerLayout {
        frame: rect,
        days,
        hour: Rect {
            x: clock_x,
            y: time_area.y,
            width: 2,
            height: 1,
        },
        minute: Rect {
            x: clock_x.saturating_add(3),
            y: time_area.y,
            width: 2,
            height: 1,
        },
        time_row: time_area,
    };
}

/// A body image at whatever size the screen allows.
fn draw_image_preview(
    f: &mut Frame,
    store: &mut crate::image::ImageStore,
    form: &mut crate::form::TaskForm,
    theme: &Theme,
    path: &std::path::Path,
    area: Rect,
) {
    let rect = centered(
        area,
        (u32::from(area.width) * 9 / 10) as u16,
        (u32::from(area.height) * 9 / 10) as u16,
    );
    let title = truncate(
        &path.file_name().unwrap_or_default().to_string_lossy(),
        rect.width.saturating_sub(10) as usize,
    );
    let kind = crate::image::type_label(path);
    let anim_note = form
        .gif
        .as_ref()
        .map(|(_, g)| g)
        .filter(|g| g.is_animated())
        .map(|g| format!(" · {}/{}", g.frame_number(), g.frame_count()))
        .unwrap_or_default();
    let block = Block::bordered()
        .border_type(BorderType::Thick)
        .border_style(theme.accent_text())
        .title(Span::styled(
            format!(" {title} "),
            theme.accent_text().bold(),
        ))
        .title_top(
            Line::styled(
                format!(" {kind}{anim_note} "),
                Style::new().fg(theme.muted_color()),
            )
            .right_aligned(),
        )
        .title_bottom(
            Line::styled(
                match form.gif.as_ref().map(|(_, g)| g) {
                    Some(g) if g.is_animated() && g.is_paused() => {
                        " Esc closes · click/space resume "
                    }
                    Some(g) if g.is_animated() => " Esc closes · click/space pause ",
                    _ => " Esc closes ",
                },
                Style::new().fg(theme.muted_color()),
            )
            .right_aligned(),
        );
    let inner = block.inner(rect);
    f.render_widget(Clear, rect);
    f.render_widget(block, rect);

    // Preview has its own chrome; no selection frame margin.
    if let Some((_, gif)) = form.gif.as_ref() {
        match store.preview_frame(gif) {
            Ok(protocol) => {
                let _ = render_protocol(f, protocol, inner, theme, None);
            }
            Err(err) => {
                let slot = letterbox_rect(preview_slot_area(inner), 4, 3);
                draw_image_slot(
                    f,
                    theme,
                    slot,
                    ImageSlotKind::Broken { detail: &err },
                    false,
                );
            }
        }
    } else {
        match store.get_preview(path) {
            crate::image::ImageReady::Ready(protocol) => {
                let _ = render_protocol(f, protocol, inner, theme, None);
            }
            crate::image::ImageReady::Loading => {
                // Loading means not cached yet — aspect unknown.
                let slot = letterbox_rect(preview_slot_area(inner), 4, 3);
                draw_image_slot(f, theme, slot, ImageSlotKind::Loading, false);
            }
            crate::image::ImageReady::Failed(err) => {
                let slot = letterbox_rect(preview_slot_area(inner), 4, 3);
                draw_image_slot(
                    f,
                    theme,
                    slot,
                    ImageSlotKind::Broken { detail: &err },
                    false,
                );
            }
        }
    }
}

/// Draws a decoded image, or a loading / broken stand-in sized like the
/// picture. Returns the screen rect of the picture (hit target).
fn draw_image(
    f: &mut Frame,
    store: &mut crate::image::ImageStore,
    theme: &Theme,
    path: &std::path::Path,
    area: Rect,
    selected: bool,
) -> Option<Rect> {
    if area.width < 3 || area.height < 3 {
        return None;
    }
    // Room for the frame is always left, so selecting a picture does not
    // change its size.
    let inner = area.inner(Margin {
        horizontal: 1,
        vertical: 1,
    });
    match store.get(path) {
        crate::image::ImageReady::Ready(protocol) => Some(render_protocol(
            f,
            protocol,
            inner,
            theme,
            selected.then_some(path),
        )),
        crate::image::ImageReady::Loading => {
            // Not in cache yet — aspect unknown until decode finishes.
            let slot = letterbox_rect(area, 4, 3);
            draw_image_slot(f, theme, slot, ImageSlotKind::Loading, selected);
            Some(slot)
        }
        crate::image::ImageReady::Failed(err) => {
            let name = path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or(err.as_str());
            let slot = letterbox_rect(area, 4, 3);
            draw_image_slot(
                f,
                theme,
                slot,
                ImageSlotKind::Broken { detail: name },
                selected,
            );
            Some(slot)
        }
    }
}

/// Paints the protocol and returns the interactive rect (frame when
/// selected, otherwise the picture itself).
fn render_protocol(
    f: &mut Frame,
    protocol: &mut ratatui_image::protocol::StatefulProtocol,
    inner: Rect,
    theme: &Theme,
    frame: Option<&std::path::Path>,
) -> Rect {
    // Scale (not Fit): Fit never grows past the source pixel size, so a
    // 1920px image on a large terminal only fills part of the preview.
    // Scale keeps aspect ratio and uses the full cell area.
    let size = protocol.size_for(Resize::Scale(None), inner.as_size());
    let picture = centered(
        inner,
        size.width.min(inner.width),
        size.height.min(inner.height),
    );
    f.render_stateful_widget(
        StatefulImage::default().resize(Resize::Scale(None)),
        picture,
        protocol,
    );
    let hit = if let Some(path) = frame {
        let border = Rect {
            x: picture.x.saturating_sub(1),
            y: picture.y.saturating_sub(1),
            width: picture.width.saturating_add(2),
            height: picture.height.saturating_add(2),
        };
        let kind = crate::image::type_label(path);
        f.render_widget(
            Block::bordered()
                .border_type(BorderType::Thick)
                .border_style(theme.accent_text())
                .title_top(
                    Line::styled(format!(" {kind} "), Style::new().fg(theme.muted_color()))
                        .right_aligned(),
                ),
            border,
        );
        border
    } else {
        picture
    };
    if let Some(Err(err)) = protocol.last_encoding_result() {
        let line = Line::styled(
            truncate(&format!("image: {err}"), inner.width as usize),
            Style::new().fg(theme.error_color()),
        );
        f.render_widget(Paragraph::new(line), inner);
    }
    hit
}

fn render_field_box(f: &mut Frame, block: Block, area: Rect) -> Rect {
    let inner = block.inner(area);
    f.render_widget(block, area);
    inner
}

/// Draws `text`, or a dim hint at what belongs there when it is empty.
/// Split `text` into spans, washing the selection with the theme accent.
fn line_with_selection(
    text: &str,
    sel: Option<(u16, u16)>,
    base: Style,
    theme: &Theme,
) -> Line<'static> {
    let Some((a, b)) = sel else {
        return Line::from(Span::styled(text.to_string(), base));
    };
    let a = a as usize;
    let b = b as usize;
    if a >= b {
        return Line::from(Span::styled(text.to_string(), base));
    }
    let sel_style = theme.selection();
    let mut spans = Vec::new();
    let mut col = 0usize;
    let mut chunk = String::new();
    let mut chunk_in_sel = false;
    let flush = |spans: &mut Vec<Span<'static>>, chunk: &mut String, in_sel: bool| {
        if chunk.is_empty() {
            return;
        }
        let style = if in_sel { sel_style } else { base };
        spans.push(Span::styled(std::mem::take(chunk), style));
    };
    for grapheme in text.graphemes(true) {
        let w = grapheme.width();
        let in_sel = col >= a && col < b;
        if !chunk.is_empty() && in_sel != chunk_in_sel {
            flush(&mut spans, &mut chunk, chunk_in_sel);
        }
        chunk_in_sel = in_sel;
        chunk.push_str(grapheme);
        col += w;
    }
    flush(&mut spans, &mut chunk, chunk_in_sel);
    Line::from(spans)
}

fn render_or_placeholder(f: &mut Frame, area: Rect, text: &str, placeholder: &str, theme: &Theme) {
    let line = if text.is_empty() {
        Line::styled(
            truncate(placeholder, area.width as usize),
            Style::new()
                .fg(theme.muted_color())
                .add_modifier(Modifier::DIM),
        )
    } else {
        Line::raw(text.to_string())
    };
    f.render_widget(Paragraph::new(line), area);
}

/// A panel: thick border glyphs, title in the top-left, accent colour
/// while focused. (Terminal bold barely thickens box-drawing chars.)
fn panel<'a>(title: &'a str, focused: bool, theme: &Theme) -> Block<'a> {
    let (border, title_style) = if focused {
        (theme.accent_text(), theme.accent_text().bold())
    } else {
        (
            Style::new().fg(theme.muted_color()),
            Style::new()
                .fg(theme.muted_color())
                .add_modifier(Modifier::BOLD),
        )
    };
    Block::bordered()
        .border_type(BorderType::Thick)
        .border_style(border)
        .title(Span::styled(format!(" {title} "), title_style))
        .padding(Padding::horizontal(1))
}

/// Panel scrollbar (right border). Accent when focused, grey otherwise.
fn scrollbar(
    f: &mut Frame,
    theme: &Theme,
    area: Rect,
    total: usize,
    visible: usize,
    offset: usize,
    focused: bool,
) {
    paint_scrollbar(f, theme, area, total, visible, offset, focused, 1);
}

#[allow(clippy::too_many_arguments)]
fn paint_scrollbar(
    f: &mut Frame,
    theme: &Theme,
    area: Rect,
    total: usize,
    visible: usize,
    offset: usize,
    focused: bool,
    vertical_margin: u16,
) {
    // Ratatui's thumb hits the end only when `position == content_length - 1`.
    // List/table `offset` runs 0..=(total - visible), so content_length must
    // be that range's size (max_offset + 1), not the raw row count — otherwise
    // the thumb stops short when you are already on the last row.
    let max_offset = total.saturating_sub(visible);
    if max_offset == 0 || area.height <= vertical_margin.saturating_mul(2) {
        return;
    }
    let mut state = ScrollbarState::new(max_offset + 1).position(offset.min(max_offset));
    let style = if focused {
        theme.accent_text()
    } else {
        Style::new().fg(theme.muted_color())
    };
    f.render_stateful_widget(
        Scrollbar::new(ScrollbarOrientation::VerticalRight)
            .symbols(ratatui::symbols::scrollbar::VERTICAL)
            .begin_symbol(None)
            .end_symbol(None)
            .thumb_style(style)
            .track_style(style),
        area.inner(Margin {
            horizontal: 0,
            vertical: vertical_margin,
        }),
        &mut state,
    );
}

// --------------------------------------------------------------- sidebar

fn draw_sidebar(f: &mut Frame, app: &mut App, theme: &Theme, area: Rect) {
    let focused = app.focus == Focus::Sidebar;
    let chrome_focus = focused && !app.mode.command_bar_focused();
    let block = panel("Categories", chrome_focus, theme);
    let inner = block.inner(area);
    app.areas.sidebar = inner;
    if inner.height == 0 || inner.width == 0 {
        f.render_widget(block, area);
        return;
    }

    let width = inner.width as usize;
    // `done/total` per category, right-aligned to the widest score.
    let scores: Vec<String> = app
        .categories
        .iter()
        .map(|cat| {
            let (done, total) = app.category_progress(&cat.id);
            format!("{done}/{total}")
        })
        .collect();
    let count_width = scores.iter().map(|s| s.width()).max().unwrap_or(3).max(3);
    let name_field = width.saturating_sub(count_width + 1);
    let items: Vec<ListItem> = app
        .categories
        .iter()
        .zip(scores.iter())
        .map(|(cat, score)| {
            let count = format!("{score:>count_width$}");
            let name = truncate(&cat.name, name_field);
            let pad = " ".repeat(width.saturating_sub(name.width() + count.width()));
            ListItem::new(Line::from(vec![
                Span::raw(name),
                Span::raw(pad),
                Span::styled(count, Style::new().fg(theme.muted_color())),
            ]))
        })
        .collect();
    let rows = items.len();

    app.cat_state.select(Some(app.cat_index));
    let list = List::new(items).block(block).highlight_style(if focused {
        theme.selection()
    } else {
        theme.selection_unfocused()
    });
    f.render_stateful_widget(list, area, &mut app.cat_state);
    scrollbar(
        f,
        theme,
        area,
        rows,
        inner.height as usize,
        app.cat_state.offset(),
        chrome_focus,
    );
}

// ----------------------------------------------------------------- tasks

fn draw_tasks(f: &mut Frame, app: &mut App, theme: &Theme, area: Rect) {
    let focused = app.focus == Focus::Tasks;
    // While the task editor is open, dim panel chrome (border / scrollbar)
    // but keep the selected-row wash so the edited task stays visible.
    let chrome_focus = focused && app.mode != Mode::TaskForm && !app.mode.command_bar_focused();
    // The sidebar already says which category is showing; only a search
    // needs spelling out up here.
    let mut block = panel("Tasks", chrome_focus, theme);
    // Search spells out what matched; category notes stay in the editor.
    if app.searching {
        let context = format!(" search: {} · {} found ", app.search_query, app.view.len());
        block = block
            .title_top(Line::styled(context, Style::new().fg(theme.muted_color())).right_aligned());
    }
    let inner = block.inner(area);
    app.areas.tasks = inner;
    if inner.height == 0 || inner.width == 0 {
        f.render_widget(block, area);
        return;
    }

    if app.view.is_empty() {
        f.render_widget(block, area);
        let text = if app.searching {
            banner::NO_SEARCH_RESULTS
        } else {
            banner::EMPTY_TASKS
        };
        let style = if chrome_focus {
            theme.accent_text()
        } else {
            Style::new().fg(theme.muted_color())
        };
        draw_box(f, inner, text, style);
        return;
    }

    // Category is shown as a section header row in All Tasks / search, not a
    // per-task suffix. Flags keep a fixed right edge; due dates and body
    // markers live inside each task's content cell so metadata on one task
    // cannot shorten every other title in the list.
    let flags_width = crate::model::MAX_IMPORTANCE as usize;
    let presentations: Vec<_> = app
        .view
        .iter()
        .map(|task_index| TaskPresentation::new(&app.tasks[*task_index], &app.settings.date_format))
        .collect();

    // Preserve a useful title at narrow widths. Flags stay aligned when the
    // panel can afford them; row-local metadata decides independently whether
    // its complete value fits beside that task's title.
    const TITLE_MIN: usize = 8;
    let available = inner.width as usize;
    let flags_visible = DONE_MARK_WIDTH as usize + 1 + TITLE_MIN + 1 + flags_width <= available;
    let mut widths = vec![
        Constraint::Length(DONE_MARK_WIDTH), // [ ] / [✓]
        Constraint::Fill(1),                 // title + this task's metadata
    ];
    if flags_visible {
        widths.push(Constraint::Length(flags_width as u16));
    }
    let column_gaps = widths.len().saturating_sub(1);
    let content_width = available
        .saturating_sub(DONE_MARK_WIDTH as usize)
        .saturating_sub(column_gaps)
        .saturating_sub(if flags_visible { flags_width } else { 0 });
    let mut presentations = presentations.into_iter().enumerate();
    let rows: Vec<Row> = app
        .list_rows
        .iter()
        .map(|row| match row {
            // Placeholder — the full-width rule is painted after the table
            // so column gaps cannot break the line or the title.
            crate::app::TaskListRow::Separator { .. } => {
                Row::new(std::iter::repeat_n(Cell::new(""), widths.len()))
            }
            crate::app::TaskListRow::Task(view_idx) => {
                let (presentation_index, presentation) = presentations
                    .next()
                    .expect("task rows and task presentations must stay aligned");
                debug_assert_eq!(*view_idx, presentation_index);
                task_row(
                    presentation,
                    theme,
                    *view_idx == app.task_index,
                    content_width,
                    flags_visible,
                )
            }
        })
        .collect();
    debug_assert!(presentations.next().is_none());
    // Selected-row wash stays on during edit; bold only when the list has chrome focus.
    let table = Table::new(rows, widths)
        .block(block)
        .column_spacing(1)
        .row_highlight_style(if chrome_focus {
            theme.selection()
        } else {
            theme.selection_unfocused()
        });

    // Remember where the markers ended up, so a click can find them. The
    // flags sit at the right edge, the tick at the left.
    app.areas.done_x = Some(inner.x);
    app.areas.flag_x = flags_visible.then_some(inner.right().saturating_sub(flags_width as u16));

    let vis = app.selected_visual_row();
    app.task_state.select(vis);
    // Table does `start = offset.min(selected)`, so scrolling up to the first
    // task of a group lands on that task and hides the section header above
    // it. Pull offset back onto the header first so the header stays in view.
    if let Some(vis) = vis {
        pin_section_header(app, vis);
    }
    f.render_stateful_widget(table, area, &mut app.task_state);

    // Full-width category rules on top of separator placeholder rows.
    let offset = app.task_state.offset();
    let rule_style = Style::new().fg(theme.muted_color());
    for (vis_i, row) in app.list_rows.iter().enumerate().skip(offset) {
        let y = inner
            .y
            .saturating_add(u16::try_from(vis_i - offset).unwrap_or(u16::MAX));
        if y >= inner.bottom() {
            break;
        }
        let crate::app::TaskListRow::Separator { title } = row else {
            continue;
        };
        // Align the name with task titles (after `[ ]` + column gap).
        let title_x = (DONE_MARK_WIDTH + 1) as usize;
        let line = category_rule(title, inner.width as usize, title_x);
        f.render_widget(
            Paragraph::new(Span::styled(line, rule_style)),
            Rect {
                x: inner.x,
                y,
                width: inner.width,
                height: 1,
            },
        );
    }

    scrollbar(
        f,
        theme,
        area,
        app.list_rows.len(),
        inner.height as usize,
        app.task_state.offset(),
        chrome_focus,
    );
}

/// If `vis` is the first task under a section header, do not let the table
/// scroll that header off the top of the viewport.
fn pin_section_header(app: &mut App, vis: usize) {
    if vis == 0 {
        return;
    }
    let header = vis - 1;
    if !matches!(
        app.list_rows.get(header),
        Some(crate::app::TaskListRow::Separator { .. })
    ) {
        return;
    }
    if app.task_state.offset() > header {
        *app.task_state.offset_mut() = header;
    }
}

/// The markers shown between a task's title and its due date.
fn extras(task: &crate::model::Task) -> String {
    let notes = if crate::model::has_prose_or_image(task) {
        ""
    } else {
        ""
    };
    match crate::model::todo_progress(task) {
        Some((done, total)) => format!("{notes} {done}/{total}").trim_start().to_string(),
        None => notes.to_string(),
    }
}

/// Owned display data derived once for one task during a frame.
struct TaskPresentation {
    title: String,
    extras: String,
    due: String,
    flags: String,
    done: bool,
}

impl TaskPresentation {
    fn new(task: &crate::model::Task, date_format: &str) -> Self {
        Self {
            title: task.title.clone(),
            extras: extras(task),
            due: due::display_compact(&task.due, date_format),
            flags: crate::model::importance_marks(task.importance),
            done: task.done,
        }
    }
}

/// Full-width rule with the category name aligned to the title column:
/// `─── Mach ────────────────` (space before the name, same column as titles).
fn category_rule(title: &str, width: usize, title_x: usize) -> String {
    if width == 0 {
        return String::new();
    }
    // One space before the name so it does not touch the rule; the name
    // still starts at `title_x` like task titles after `[ ] `.
    let label = format!(" {title} ");
    let label_w = label.width();
    let pad = title_x.saturating_sub(1).min(width);
    if pad + label_w >= width {
        let head = "".repeat(pad);
        return truncate(&format!("{head}{label}"), width);
    }
    format!(
        "{}{label}{}",
        "".repeat(pad),
        "".repeat(width - pad - label_w)
    )
}

fn task_row(
    presentation: TaskPresentation,
    theme: &Theme,
    selected: bool,
    content_width: usize,
    flags_visible: bool,
) -> Row<'static> {
    let TaskPresentation {
        title,
        extras,
        due,
        flags,
        done,
    } = presentation;
    // A finished task is muted — but not on the selected row (even when
    // Categories has focus), where the tick and strikethrough say enough.
    // Due colour belongs to the due label rather than tinting the whole title.
    let title_style = if done && !selected {
        Style::new().fg(theme.muted_color())
    } else {
        theme.plain()
    };
    let title_style = if done {
        title_style.add_modifier(Modifier::CROSSED_OUT)
    } else {
        title_style
    };

    let mut cells = Vec::with_capacity(5);
    let (mark, mark_style) = if done {
        ("[✓]", Style::new().fg(theme.success_color()))
    } else {
        ("[ ]", Style::new().fg(theme.muted_color()))
    };
    cells.push(Cell::new(mark).style(mark_style));
    let metadata_style = if done {
        Style::new()
            .fg(theme.muted_color())
            .add_modifier(Modifier::CROSSED_OUT)
    } else {
        Style::new().fg(theme.muted_color())
    };
    let due_style = if done {
        title_style
    } else {
        Style::new().fg(theme.accent)
    };
    cells.push(Cell::new(task_content_line(
        title,
        title_style,
        extras,
        metadata_style,
        due,
        due_style,
        content_width,
    )));
    if flags_visible {
        let flag_style = if done {
            metadata_style
        } else {
            Style::new().fg(theme.error_color())
        };
        cells.push(Cell::new(Text::from(
            Line::from(Span::styled(flags, flag_style)).right_aligned(),
        )));
    }
    Row::new(cells)
}

/// Build one task's content cell with row-local metadata at its right edge.
/// Due is the highest-priority suffix; body/progress markers join it only when
/// both complete values fit while retaining a recognisable title.
fn task_content_line(
    title: String,
    title_style: Style,
    extras: String,
    extras_style: Style,
    due: String,
    due_style: Style,
    width: usize,
) -> Line<'static> {
    const TITLE_MIN: usize = 8;
    const META_GAP: usize = 1;

    let title_floor = title.width().min(TITLE_MIN);
    let mut show_due = false;
    let mut show_extras = false;
    let mut metadata_width = 0;

    if !due.is_empty() && title_floor + META_GAP + due.width() <= width {
        show_due = true;
        metadata_width = due.width();
    }
    if !extras.is_empty() {
        let joined_width = if metadata_width == 0 {
            extras.width()
        } else {
            extras.width() + META_GAP + metadata_width
        };
        if title_floor + META_GAP + joined_width <= width {
            show_extras = true;
            metadata_width = joined_width;
        }
    }

    if metadata_width == 0 {
        return Line::from(Span::styled(truncate(&title, width), title_style));
    }

    let title_width = width.saturating_sub(META_GAP + metadata_width);
    let title = truncate(&title, title_width);
    let padding = width.saturating_sub(title.width() + metadata_width);
    let mut spans = vec![
        Span::styled(title, title_style),
        Span::raw(" ".repeat(padding)),
    ];
    if show_extras {
        spans.push(Span::styled(extras, extras_style));
        if show_due {
            spans.push(Span::raw(" "));
        }
    }
    if show_due {
        spans.push(Span::styled(due, due_style));
    }
    Line::from(spans)
}

// ------------------------------------------------------------ status bar

fn draw_status(f: &mut Frame, app: &mut App, theme: &Theme, area: Rect) {
    // The bar is a panel like the others, minus the name: while a
    // command or a search is being typed it is what has focus.
    let typing = matches!(app.mode, Mode::Slash | Mode::Search);
    let update_activity = (!typing).then(|| app.update_activity()).flatten();
    let downloading = matches!(update_activity, Some(UpdateActivity::Downloading(_)));
    let block = Block::bordered()
        .border_type(BorderType::Thick)
        .border_style(if typing {
            theme.accent_text()
        } else {
            Style::new().fg(theme.muted_color())
        })
        .padding(if downloading {
            Padding::ZERO
        } else {
            Padding::horizontal(1)
        });
    let inner = block.inner(area);
    f.render_widget(block, area);
    let area = inner;

    if let Some(UpdateActivity::Downloading(progress)) = update_activity {
        draw_download_progress(f, progress, theme, area);
        return;
    }

    let right = Line::from(Span::styled(
        due::now_string(&app.settings.date_format),
        Style::new().fg(theme.muted_color()),
    ));
    let right_width = right.width() as u16;
    let [left_area, right_area] = Layout::horizontal([
        Constraint::Min(0),
        Constraint::Length(right_width.min(area.width)),
    ])
    .areas(area);
    // The clock is display-only, but it is still part of the command bar's
    // mouse target. A click there focuses the input and lands at its end.
    app.areas.command_bar = area;
    f.render_widget(Paragraph::new(right), right_area);

    let field = left_area.width.saturating_sub(2) as usize;
    let left = match app.mode {
        Mode::Slash | Mode::Search => {
            let view = app.input.visible(field);
            f.set_cursor_position((
                left_area
                    .x
                    .saturating_add(1)
                    .saturating_add(view.cursor_col),
                left_area.y,
            ));
            let body = line_with_selection(&view.text, view.sel_cols, Style::new(), theme);
            Line::from([vec![Span::styled("/", theme.accent_text())], body.spans].concat())
        }
        _ if update_activity == Some(UpdateActivity::Checking) => {
            Line::from(Span::styled("Checking for updates…", theme.accent_text()))
        }
        _ => match app.status_message() {
            Some((text, kind)) => {
                let style = match kind {
                    MessageKind::Error => Style::new()
                        .fg(theme.error_color())
                        .add_modifier(Modifier::BOLD),
                    MessageKind::Info => theme.accent_text(),
                };
                Line::from(Span::styled(truncate(text, field), style))
            }
            None => {
                let hint = if app.searching {
                    format!("search: {} · Esc clears", app.search_query)
                } else {
                    "/ commands".to_string()
                };
                if (left_area.width as usize) >= hint.width() + 2 {
                    Line::from(Span::styled(hint, Style::new().fg(theme.muted_color())))
                } else {
                    Line::raw("")
                }
            }
        },
    };
    f.render_widget(Paragraph::new(left), left_area);
}

fn draw_download_progress(
    f: &mut Frame,
    progress: crate::update::DownloadProgress,
    theme: &Theme,
    area: Rect,
) {
    let Some(total) = progress.total.filter(|total| *total > 0) else {
        f.render_widget(
            Paragraph::new(Line::from(Span::styled(
                format!(
                    "Downloading update… {}",
                    readable_bytes(progress.downloaded)
                ),
                theme.accent_text(),
            )))
            .centered(),
            area,
        );
        return;
    };
    let ratio = progress.downloaded.min(total) as f64 / total as f64;
    let percent = (ratio * 100.0).round() as u64;
    let label = format!("Downloading update {percent}%");
    f.render_widget(
        Gauge::default()
            .ratio(ratio)
            .label(label)
            .use_unicode(true)
            .style(Style::new().fg(theme.muted_color()))
            .gauge_style(theme.accent_text().add_modifier(Modifier::BOLD)),
        area,
    );
}

fn readable_bytes(bytes: u64) -> String {
    const MIB: u64 = 1024 * 1024;
    const KIB: u64 = 1024;
    if bytes >= MIB {
        format!("{:.1} MiB", bytes as f64 / MIB as f64)
    } else if bytes >= KIB {
        format!("{:.1} KiB", bytes as f64 / KIB as f64)
    } else {
        format!("{bytes} B")
    }
}

/// Dropdown of `/` commands, drawn upward from the status bar.
fn draw_slash_palette(f: &mut Frame, app: &mut App, theme: &Theme, status: Rect) {
    let query = app.input.value();
    let commands = crate::slash::matching(&query);
    if commands.is_empty() {
        return;
    }
    let width = 53.min(status.width.saturating_sub(2)).max(24);
    let height = u16::try_from(commands.len())
        .unwrap_or(u16::MAX)
        .saturating_add(2)
        .min(status.y.max(3));
    let rect = Rect {
        x: status.x,
        y: status.y.saturating_sub(height),
        width,
        height,
    };
    app.areas.slash_menu = rect;
    let row_width = width.saturating_sub(2) as usize;
    let lines: Vec<Line> = commands
        .iter()
        .enumerate()
        .map(|(i, cmd)| {
            let selected = i == app.slash_index.min(commands.len() - 1);
            dropdown_row(
                theme,
                selected,
                &format!("/{:<12}", cmd.id()),
                cmd.hint(),
                row_width,
            )
        })
        .collect();
    let block = Block::bordered()
        .border_type(BorderType::Thick)
        .border_style(theme.accent_text())
        .title(Span::styled(
            format!(" /{} ", query),
            Style::new().fg(theme.muted_color()),
        ));
    f.render_widget(Clear, rect);
    f.render_widget(Paragraph::new(lines).block(block), rect);
}

/// One row of a small dropdown: no leading arrow; selection wash runs
/// the full inner width so the bar reaches the right border.
fn dropdown_row(
    theme: &Theme,
    selected: bool,
    label: &str,
    hint: &str,
    row_width: usize,
) -> Line<'static> {
    let label_part = format!(" {label} ");
    let hint_part = format!("{hint} ");
    let used = label_part.width() + hint_part.width();
    let pad = " ".repeat(row_width.saturating_sub(used));

    let (label_style, hint_style, pad_style) = if selected {
        let selection = theme.selection();
        (selection, selection, selection)
    } else {
        (
            Style::new(),
            Style::new().fg(theme.muted_color()),
            Style::new(),
        )
    };
    Line::from(vec![
        Span::styled(label_part, label_style),
        Span::styled(hint_part, hint_style),
        Span::styled(pad, pad_style),
    ])
}

// -------------------------------------------------------------- overlays

fn draw_help(f: &mut Frame, app: &mut App, theme: &Theme, area: Rect) {
    const COLUMN_WIDTH: usize = 40;
    const WIDE_WIDTH: u16 = COLUMN_WIDTH as u16 * 2 + 7;
    const NARROW_WIDTH: u16 = 58;

    let wide = area.width >= WIDE_WIDTH;
    let width = if wide {
        WIDE_WIDTH
    } else {
        NARROW_WIDTH.min(area.width)
    };
    let mut lines = wordmark_lines(theme, width);
    if !lines.is_empty() {
        lines.push(Line::raw(""));
    }
    let row_style = |heading| {
        if heading {
            theme.accent_text().add_modifier(Modifier::BOLD)
        } else {
            Style::new()
        }
    };
    if wide {
        for banner::HelpRow {
            left,
            right,
            heading,
        } in banner::HELP_COLUMNS
        {
            let style = row_style(heading);
            lines.push(Line::from(vec![
                Span::raw("  "),
                Span::styled(format!("{left:<COLUMN_WIDTH$}"), style),
                Span::styled(right, style),
            ]));
        }
        lines.push(Line::raw(""));
    } else {
        // Stack the paired sections only when two readable columns do not fit.
        for side in 0..2 {
            for banner::HelpRow {
                left,
                right,
                heading,
            } in banner::HELP_COLUMNS
            {
                let text = if side == 0 { left } else { right };
                if text.is_empty() {
                    lines.push(Line::raw(""));
                    continue;
                }
                let prefix = if heading { "" } else { "  " };
                lines.push(Line::styled(format!("{prefix}{text}"), row_style(heading)));
            }
            lines.push(Line::raw(""));
        }
    }
    let store = format!("Data store: {}", app.data_dir().display());
    lines.push(
        Line::styled(
            truncate(&store, width.saturating_sub(4) as usize),
            Style::new().fg(theme.muted_color()),
        )
        .centered(),
    );
    lines.push(Line::styled(banner::HELP_FOOTER, theme.accent_text()).centered());

    let height = u16::try_from(lines.len())
        .unwrap_or(u16::MAX)
        .saturating_add(2)
        .min(area.height);
    let rect = centered(area, width, height);
    let viewport = rect.height.saturating_sub(2) as usize;
    let max_scroll = lines.len().saturating_sub(viewport);
    app.help_scroll = app.help_scroll.min(max_scroll);
    let title = Line::from(vec![
        Span::raw(" mach "),
        Span::styled(
            format!("v{} ", crate::VERSION),
            Style::new().fg(theme.muted_color()),
        ),
    ]);
    let block = Block::bordered()
        .border_type(BorderType::Thick)
        .title(title)
        .border_style(theme.accent_text())
        .padding(ratatui::widgets::Padding::horizontal(1));
    f.render_widget(Clear, rect);
    f.render_widget(
        Paragraph::new(lines)
            .block(block)
            .scroll((app.help_scroll.min(u16::MAX as usize) as u16, 0)),
        rect,
    );
}

fn draw_settings(f: &mut Frame, app: &App, theme: &Theme, area: Rect) {
    let mut lines: Vec<Line> = Vec::new();
    for (i, item) in SETTINGS_ITEMS.iter().enumerate() {
        let selected = i == app.settings_index;
        let value = app.setting_value(i);
        let marker = if selected { "" } else { "  " };
        let name_style = if selected {
            Style::new().add_modifier(Modifier::BOLD)
        } else {
            Style::new()
        };
        lines.push(Line::from(vec![
            Span::styled(marker, theme.accent_text()),
            Span::styled(format!("{item:<14}"), name_style),
            Span::styled(value, theme.accent_text()),
        ]));
    }
    lines.push(Line::raw(""));
    lines.push(Line::styled(
        "↑↓ select · ←→ change · Esc close",
        Style::new().fg(theme.muted_color()),
    ));

    let width = 48.min(area.width);
    let height = u16::try_from(lines.len())
        .unwrap_or(u16::MAX)
        .saturating_add(2)
        .min(area.height);
    let rect = centered(area, width, height);
    let block = Block::bordered()
        .border_type(BorderType::Thick)
        .title(Line::from(" Settings "))
        .border_style(theme.accent_text())
        .padding(ratatui::widgets::Padding::horizontal(2));
    f.render_widget(Clear, rect);
    f.render_widget(Paragraph::new(lines).block(block), rect);
}

fn draw_welcome(f: &mut Frame, theme: &Theme, area: Rect) {
    let mut lines = wordmark_lines(theme, area.width);
    if !lines.is_empty() {
        lines.push(Line::raw(""));
    }
    lines.push(
        Line::styled(
            format!("Welcome to mach v{}", crate::VERSION),
            Style::new().add_modifier(Modifier::BOLD),
        )
        .centered(),
    );
    lines.push(Line::raw(""));
    lines.push(Line::raw("Written in Rust with ratatui.").centered());
    lines.push(Line::raw("Your tasks stay local in ~/.mach.").centered());
    lines.push(Line::raw(""));
    lines.push(
        Line::styled(
            "Press Enter to start · /help for the key list",
            Style::new().fg(theme.muted_color()),
        )
        .centered(),
    );

    let width = 50.min(area.width);
    let height = u16::try_from(lines.len())
        .unwrap_or(u16::MAX)
        .saturating_add(2)
        .min(area.height);
    let rect = centered(area, width, height);
    let block = Block::bordered()
        .border_type(BorderType::Thick)
        .border_style(theme.accent_text());
    f.render_widget(Clear, rect);
    f.render_widget(Paragraph::new(lines).block(block), rect);
}

fn wordmark_lines(theme: &Theme, available_width: u16) -> Vec<Line<'static>> {
    if available_width < banner::BANNER_WIDTH + 8 {
        return Vec::new();
    }
    banner::BANNER
        .iter()
        .map(|row| Line::styled(*row, theme.accent_text()).centered())
        .collect()
}

fn draw_whats_new(f: &mut Frame, theme: &Theme, area: Rect) {
    let mut lines = vec![
        Line::styled(
            format!("What's new in mach v{}", crate::VERSION),
            Style::new().add_modifier(Modifier::BOLD),
        )
        .centered(),
        Line::raw(""),
    ];
    for (index, (title, description)) in banner::WHATS_NEW.into_iter().enumerate() {
        lines.push(Line::from(vec![
            Span::styled("", theme.accent_text()),
            Span::styled(title, Style::new().add_modifier(Modifier::BOLD)),
        ]));
        lines.push(Line::raw(format!("  {description}")));
        if index + 1 < banner::WHATS_NEW.len() {
            lines.push(Line::raw(""));
        }
    }
    lines.push(Line::raw(""));
    lines
        .push(Line::styled("Full release notes:", Style::new().fg(theme.muted_color())).centered());
    lines.push(
        Line::styled(
            format!("github.com/Q1CHENL/mach/releases/tag/v{}", crate::VERSION),
            Style::new().fg(theme.muted_color()),
        )
        .centered(),
    );
    lines.push(
        Line::styled(
            "Press Enter or Esc to continue",
            Style::new().fg(theme.muted_color()),
        )
        .centered(),
    );

    let height = u16::try_from(lines.len())
        .unwrap_or(u16::MAX)
        .saturating_add(2)
        .min(area.height);
    let rect = centered(area, 62.min(area.width), height);
    let block = Block::bordered()
        .border_type(BorderType::Thick)
        .border_style(theme.accent_text())
        .padding(Padding::horizontal(2));
    f.render_widget(Clear, rect);
    f.render_widget(Paragraph::new(lines).block(block), rect);
}

// ----------------------------------------------------------------- utils

fn draw_box(f: &mut Frame, area: Rect, text: &str, style: Style) {
    let width = u16::try_from(text.width())
        .unwrap_or(u16::MAX)
        .saturating_add(8)
        .min(area.width);
    let rect = centered(area, width, 3);
    let block = Block::bordered()
        .border_type(BorderType::Thick)
        .border_style(style);
    f.render_widget(Clear, rect);
    f.render_widget(
        Paragraph::new(Line::styled(text.to_string(), style))
            .centered()
            .block(block),
        rect,
    );
}

pub fn centered(area: Rect, width: u16, height: u16) -> Rect {
    let width = width.min(area.width);
    let height = height.min(area.height);
    Rect {
        x: area.x.saturating_add((area.width - width) / 2),
        y: area.y.saturating_add((area.height - height) / 2),
        width,
        height,
    }
}

/// Cut a string to a display width without splitting a grapheme cluster.
pub fn truncate(s: &str, width: usize) -> String {
    if s.width() <= width {
        return s.to_string();
    }
    let mut out = String::new();
    let mut used = 0;
    for grapheme in s.graphemes(true) {
        let w = grapheme.width();
        if used + w > width {
            break;
        }
        used += w;
        out.push_str(grapheme);
    }
    out
}