sara-tasks 0.8.0

Sara — folder-aware task manager
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
use chrono::{Local, Utc};
use ratatui::{
    Frame,
    layout::{Constraint, Direction, Layout},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph, Wrap},
};

use crate::infrastructure::db;
use crate::infrastructure::model::{Priority, Task, format_duration};

use super::edit::current_value;
use super::handler::{
    GRAPH_NEIGHBOR_CAP, comment_target, depends_on_display, focusables, guide_is_stale,
    notes_of_kind, typed_notes, verification_rows,
};
use super::types::{Detail, EDIT_FIELDS, EditField, EditState, Focusable, GraphNode};

pub(super) fn render(f: &mut Frame, st: &EditState) {
    let area = f.area();
    let d = &st.detail;

    let history_height: u16 = if d.history.is_empty() {
        0
    } else {
        (d.history.len() as u16 + 2).min(6) // border (2) + up to 4 most-recent entries
    };

    let constraints = if st.editing || st.commenting || st.adding_step {
        if history_height > 0 {
            vec![
                Constraint::Min(1),
                Constraint::Length(history_height),
                Constraint::Length(3),
                Constraint::Length(1),
            ]
        } else {
            vec![
                Constraint::Min(1),
                Constraint::Length(3),
                Constraint::Length(1),
            ]
        }
    } else if history_height > 0 {
        vec![
            Constraint::Min(1),
            Constraint::Length(history_height),
            Constraint::Length(1),
        ]
    } else {
        vec![Constraint::Min(1), Constraint::Length(1)]
    };
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints(constraints)
        .split(area);

    let t = &d.task;
    let active = t.is_active();
    let title = format!(
        " Task {}{} ",
        t.id.map(|i| i.to_string()).unwrap_or_else(|| "-".into()),
        if active { "  ● ACTIVE" } else { "" }
    );

    let mut lines: Vec<Line> = vec![];

    // ── Editable fields
    for (i, field) in EDIT_FIELDS.iter().enumerate() {
        let selected = !st.editing && i == st.selected;
        let editing_this = st.editing && i == st.selected;
        let value = if editing_this {
            "…(editing below)".to_string()
        } else if *field == EditField::DependsOn {
            let v = depends_on_display(d);
            if v.is_empty() { "-".to_string() } else { v }
        } else {
            let v = current_value(t, *field);
            if v.is_empty() { "-".to_string() } else { v }
        };
        lines.push(editable_line(field.label(), &value, selected, *field, t));
    }

    // ── Read-only fields
    lines.push(field_line("Status", &t.status.to_string()));

    // Age / deadline counter line
    {
        let age_days = (Utc::now() - t.entry).num_days();
        let age_str = if age_days == 0 {
            "today".to_string()
        } else if age_days == 1 {
            "1 day ago".to_string()
        } else {
            format!("{age_days} days ago")
        };
        let deadline_str = if let Some(due) = t.due {
            let diff = (due - Utc::now()).num_days();
            if diff < 0 {
                format!(
                    "  ·  {} day{} overdue",
                    -diff,
                    if diff == -1 { "" } else { "s" }
                )
            } else if diff == 0 {
                "  ·  due today".to_string()
            } else if diff == 1 {
                "  ·  due tomorrow".to_string()
            } else {
                format!("  ·  due in {diff} days")
            }
        } else {
            String::new()
        };
        let overdue = t.due.map(|d| d < Utc::now()).unwrap_or(false);
        lines.push(Line::from(vec![
            key_span("Age"),
            Span::styled(
                format!("{age_str}{deadline_str}"),
                Style::default().fg(if overdue { Color::Red } else { Color::DarkGray }),
            ),
        ]));
    }

    let time_str = if active {
        format!(
            "{}  (running, this session {})",
            format_duration(t.total_time_spent()),
            format_duration(t.total_time_spent() - t.time_spent)
        )
    } else if t.time_spent > 0 {
        format_duration(t.time_spent)
    } else {
        "-".to_string()
    };
    // Time spent / estimate on the same conceptual row
    {
        let estimate_str = t
            .estimate_mins
            .map(|m| {
                let spent_mins = t.total_time_spent() / 60;
                let pct = if m > 0 {
                    (spent_mins * 100 / m).min(999)
                } else {
                    0
                };
                format!(
                    " / est {} ({pct}%)",
                    if m >= 60 {
                        let h = m / 60;
                        let r = m % 60;
                        if r == 0 {
                            format!("{h}h")
                        } else {
                            format!("{h}h{r}m")
                        }
                    } else {
                        format!("{m}m")
                    }
                )
            })
            .unwrap_or_default();
        lines.push(Line::from(vec![
            key_span("Time spent"),
            Span::styled(
                time_str,
                Style::default().fg(if active { Color::Green } else { Color::Reset }),
            ),
            Span::styled(estimate_str, Style::default().fg(Color::DarkGray)),
        ]));
    }

    // Urgency with breakdown
    {
        let breakdown_str = if let Some(ref bd) = d.urgency_breakdown {
            let mut parts = vec![];
            if bd.priority != 0.0 {
                parts.push(format!("pri {:.1}", bd.priority));
            }
            if bd.due != 0.0 {
                parts.push(format!("due {:.1}", bd.due));
            }
            if bd.blocking != 0.0 {
                parts.push(format!("blocking {:.1}", bd.blocking));
            }
            if bd.blocked != 0.0 {
                parts.push(format!("blocked {:.1}", bd.blocked));
            }
            if bd.active != 0.0 {
                parts.push(format!("active {:.1}", bd.active));
            }
            if bd.age != 0.0 {
                parts.push(format!("age {:.1}", bd.age));
            }
            if bd.tags != 0.0 {
                parts.push(format!("tags {:.1}", bd.tags));
            }
            if bd.project != 0.0 {
                parts.push(format!("proj {:.1}", bd.project));
            }
            if parts.is_empty() {
                String::new()
            } else {
                format!("  ({})", parts.join(" + "))
            }
        } else {
            String::new()
        };
        lines.push(Line::from(vec![
            key_span("Urgency"),
            Span::raw(format!("{:.1}", t.urgency)),
            Span::styled(breakdown_str, Style::default().fg(Color::DarkGray)),
        ]));
    }

    lines.push(field_line(
        "Entered",
        &t.entry
            .with_timezone(&Local)
            .format("%Y-%m-%d %H:%M")
            .to_string(),
    ));
    lines.push(field_line(
        "Modified",
        &t.modified
            .with_timezone(&Local)
            .format("%Y-%m-%d %H:%M")
            .to_string(),
    ));
    lines.push(field_line("UUID", &t.uuid.to_string()));

    // ── Guide: assignment / rationale / freshness banner ────────────
    if let Some(a) = &d.guide.assignment {
        lines.push(Line::from(vec![
            key_span("Assignment"),
            Span::styled(a.clone(), Style::default().fg(Color::DarkGray)),
        ]));
    }
    if let Some(r) = &d.guide.rationale {
        lines.push(Line::from(vec![
            key_span("Rationale"),
            Span::raw(r.clone()),
        ]));
    }
    if guide_is_stale(d) {
        lines.push(Line::from(vec![Span::styled(
            format!(
                "  ⚠ guide may be stale — validated @ {} but HEAD is {} (run `sara validate`)",
                d.guide.validated_commit.as_deref().unwrap_or("-"),
                d.head_commit.as_deref().unwrap_or("-"),
            ),
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        )]));
    } else if let Some(v) = &d.guide.validated_commit {
        lines.push(Line::from(vec![
            key_span("Freshness"),
            Span::styled(
                format!("validated @ {v}"),
                Style::default().fg(Color::Green),
            ),
        ]));
    }

    // Compute selection once here so typed notes, anchors, comments and
    // checklist can all reference it below.
    let items = focusables(d);
    let sel: Option<Focusable> = if st.editing {
        None
    } else {
        items.get(st.selected).cloned()
    };
    let file_selected = |path: &str| sel == Some(Focusable::File(path.to_string()));

    // ── Typed notes (findings, constraints, …) ───────────────────────────────
    // Build a flat note list once so indices match Focusable::Note(i).
    let all_typed = typed_notes(d);
    let mut note_cursor: usize = 0; // tracks position in all_typed across kinds
    for (label, kind) in [
        ("Findings", "finding"),
        ("Constraints", "constraint"),
        ("Assumptions", "assumption"),
        ("Open questions", "open_question"),
        ("Non-goals", "non_goal"),
        ("Decisions", "decision"),
        ("Risks", "risk"),
        ("Patterns", "pattern"),
    ] {
        let notes = notes_of_kind(d, kind);
        if notes.is_empty() {
            continue;
        }
        lines.push(Line::from(""));
        lines.push(section(&format!(
            "{label}  (↑/↓ select · c comment · r reconsider)"
        )));
        for n in &notes {
            let note_idx = note_cursor;
            note_cursor += 1;
            let is_sel = sel == Some(Focusable::Note(note_idx));
            let row_bg = if is_sel { Color::Blue } else { Color::Reset };
            let row_fg = if is_sel { Color::White } else { Color::Reset };

            // Open comments targeting this note.
            let note_id_str = n.id.to_string();
            let note_fb: Vec<&crate::infrastructure::db::Annotation> = d
                .annotations
                .iter()
                .filter(|a| {
                    a.kind == "comment"
                        && a.status == "open"
                        && a.target_kind.as_deref() == Some("note")
                        && a.target_id.as_deref() == Some(note_id_str.as_str())
                })
                .collect();

            let prefix = if is_sel { "" } else { "   " };
            let mut spans = vec![
                Span::styled(
                    prefix.to_string(),
                    Style::default()
                        .fg(if is_sel { Color::White } else { Color::Gray })
                        .bg(row_bg),
                ),
                Span::styled(
                    "".to_string(),
                    Style::default()
                        .fg(if is_sel { Color::White } else { Color::Gray })
                        .bg(row_bg),
                ),
                Span::styled(
                    n.text.clone(),
                    Style::default()
                        .fg(row_fg)
                        .bg(row_bg)
                        .add_modifier(if is_sel {
                            Modifier::BOLD
                        } else {
                            Modifier::empty()
                        }),
                ),
            ];
            if n.author == "ai" {
                spans.push(Span::styled(
                    " (ai)",
                    Style::default()
                        .fg(if is_sel { Color::White } else { Color::Magenta })
                        .bg(row_bg),
                ));
            }
            if !note_fb.is_empty() {
                spans.push(Span::styled(
                    format!("  💬{}", note_fb.len()),
                    Style::default().fg(Color::Cyan).bg(row_bg),
                ));
            }
            if note_fb.iter().any(|a| a.request_revision) {
                spans.push(Span::styled(
                    "",
                    Style::default().fg(Color::Yellow).bg(row_bg),
                ));
            }
            lines.push(Line::from(spans));

            // Thread: show open comments indented beneath this note.
            for a in &note_fb {
                let date = a.entry.with_timezone(&Local).format("%H:%M");
                let flag = if a.request_revision { "" } else { "" };
                lines.push(Line::from(vec![
                    Span::styled("".to_string(), Style::default().fg(Color::DarkGray)),
                    Span::styled(
                        format!("{date}{flag}  "),
                        Style::default().fg(Color::DarkGray),
                    ),
                    Span::styled(a.text.clone(), Style::default().fg(Color::DarkGray)),
                ]));
            }
        }
        // note_cursor already advanced per-note above.
    }
    // Sanity: note_cursor should equal all_typed.len() — unused but kept for
    // clarity; the compiler will optimise it away.
    let _ = all_typed.len();

    if !d.blocked_by.is_empty() {
        lines.push(Line::from(""));
        lines.push(section("Blocked by"));
        for b in &d.blocked_by {
            lines.push(Line::from(format!("  {b}")));
        }
    }
    if !d.blocking.is_empty() {
        lines.push(Line::from(""));
        lines.push(section("Blocking"));
        for b in &d.blocking {
            lines.push(Line::from(format!("  {b}")));
        }
    }
    // (sel / items / file_selected already computed above — before typed notes)

    if !d.links.is_empty() {
        lines.push(Line::from(""));
        lines.push(section("Links  (Enter to open)"));
        for (i, link) in d.links.iter().enumerate() {
            let selected = sel == Some(Focusable::Link(i));
            let (bg, fg) = if selected {
                (Color::Blue, Color::White)
            } else {
                (Color::Reset, Color::Cyan)
            };
            let prefix = if selected { "" } else { "   " };
            let style = Style::default()
                .fg(fg)
                .bg(bg)
                .add_modifier(Modifier::BOLD | Modifier::UNDERLINED);
            let meta_style = Style::default()
                .fg(if selected { Color::White } else { Color::Gray })
                .bg(bg);
            let mut spans = vec![
                Span::styled(prefix.to_string(), meta_style),
                Span::styled(format!("[{}] ", link.id), meta_style),
                Span::styled(link.display(), style),
            ];
            if link.display() != link.url {
                spans.push(Span::styled(
                    format!("  {}", link.url),
                    Style::default().fg(Color::DarkGray).bg(bg),
                ));
            }
            lines.push(Line::from(spans));
        }
    }
    if !d.manual_files.is_empty() {
        lines.push(Line::from(""));
        lines.push(section("Relevant files"));
        for file in &d.manual_files {
            lines.push(nav_line(file, Color::Cyan, false, file_selected(file)));
        }
    }
    // ── Code anchors: each is focusable, shows 💬/⟳ markers + threaded comments ──
    if !d.anchors.is_empty() {
        lines.push(Line::from(""));
        lines.push(section(
            "Possible relevant files  · ↑/↓ select · c comment · r reconsider",
        ));
        for (ai, anchor) in d.anchors.iter().enumerate() {
            let is_sel = sel == Some(Focusable::Anchor(ai));
            let file_text = format!("{}{}", anchor.path, anchor.location());
            let badge = if anchor.source == db::SOURCE_SUGGESTED {
                " (ai)"
            } else {
                ""
            };

            // Threaded comments anchored to this file.
            let anchor_fb: Vec<&crate::infrastructure::db::Annotation> = d
                .annotations
                .iter()
                .filter(|a| {
                    a.kind == "comment"
                        && a.target_kind.as_deref() == Some("anchor")
                        && a.target_id.as_deref() == Some(anchor.path.as_str())
                })
                .collect();
            let open_fb = anchor_fb.iter().filter(|a| a.status == "open").count();
            let needs_reconsider = anchor_fb
                .iter()
                .any(|a| a.request_revision && a.status == "open");

            let row_bg = if is_sel { Color::Blue } else { Color::Reset };
            let row_fg = if is_sel { Color::White } else { Color::Cyan };
            let meta_fg = if is_sel { Color::White } else { Color::Gray };

            let mut spans = vec![
                Span::styled(
                    if is_sel { "" } else { "   " }.to_string(),
                    Style::default().fg(meta_fg).bg(row_bg),
                ),
                Span::styled(
                    file_text,
                    Style::default()
                        .fg(row_fg)
                        .bg(row_bg)
                        .add_modifier(if is_sel {
                            Modifier::BOLD
                        } else {
                            Modifier::empty()
                        }),
                ),
                Span::styled(
                    badge.to_string(),
                    Style::default()
                        .fg(if is_sel { Color::White } else { Color::Magenta })
                        .bg(row_bg),
                ),
            ];
            if let Some(r) = &anchor.reason {
                spans.push(Span::styled(
                    format!("{r}"),
                    Style::default()
                        .fg(if is_sel {
                            Color::White
                        } else {
                            Color::DarkGray
                        })
                        .bg(row_bg),
                ));
            }
            if open_fb > 0 {
                spans.push(Span::styled(
                    format!("  💬{open_fb}"),
                    Style::default().fg(Color::Cyan).bg(row_bg),
                ));
            }
            if needs_reconsider {
                spans.push(Span::styled(
                    "",
                    Style::default().fg(Color::Yellow).bg(row_bg),
                ));
            }
            lines.push(Line::from(spans));

            // Thread: show comments anchored to this file, indented beneath it.
            for a in &anchor_fb {
                let date = a.entry.with_timezone(&Local).format("%H:%M");
                let resolved = a.status == "resolved";
                let text_style = if resolved {
                    Style::default()
                        .fg(Color::DarkGray)
                        .add_modifier(Modifier::CROSSED_OUT)
                } else {
                    Style::default().fg(Color::DarkGray)
                };
                let flag = if a.request_revision && !resolved {
                    ""
                } else {
                    ""
                };
                lines.push(Line::from(vec![
                    Span::styled("".to_string(), Style::default().fg(Color::DarkGray)),
                    Span::styled(
                        format!("{date}{flag}  "),
                        Style::default().fg(Color::DarkGray),
                    ),
                    Span::styled(a.text.clone(), text_style),
                ]));
            }
        }
    }

    // ── Checklist (steps + acceptance criteria with intent + provenance)
    if !d.checklist.is_empty() {
        // At-a-glance progress: steps done / total, acceptance done / total.
        let (mut steps_done, mut steps_total, mut acc_done, mut acc_total) = (0, 0, 0, 0);
        for it in &d.checklist {
            if it.kind == db::STEP_KIND_ACCEPTANCE {
                acc_total += 1;
                acc_done += it.done as i32;
            } else {
                steps_total += 1;
                steps_done += it.done as i32;
            }
        }
        let mut progress = String::new();
        if steps_total > 0 {
            progress.push_str(&format!("{steps_done}/{steps_total} steps"));
        }
        if acc_total > 0 {
            if !progress.is_empty() {
                progress.push_str(" · ");
            }
            progress.push_str(&format!("{acc_done}/{acc_total} acceptance"));
        }
        lines.push(Line::from(""));
        lines.push(section(&format!(
            "Checklist  {progress}  (Space toggle · c comment · r reconsider · x resolve)"
        )));
        for (i, item) in d.checklist.iter().enumerate() {
            let is_sel = sel == Some(Focusable::Checklist(i));
            let row_bg = if is_sel { Color::Blue } else { Color::Reset };

            let (box_str, text_style) = if item.done {
                (
                    "[x]",
                    Style::default()
                        .fg(Color::DarkGray)
                        .bg(row_bg)
                        .add_modifier(Modifier::CROSSED_OUT),
                )
            } else if is_sel {
                (
                    "[ ]",
                    Style::default()
                        .fg(Color::White)
                        .bg(Color::Blue)
                        .add_modifier(Modifier::BOLD),
                )
            } else {
                ("[ ]", Style::default())
            };
            // Feedback markers for this step: comment count + reconsider flag.
            let target_k = if item.kind == db::STEP_KIND_ACCEPTANCE {
                "acceptance"
            } else {
                "step"
            };
            let item_id_str = item.id.to_string();
            let fb: Vec<&crate::infrastructure::db::Annotation> = d
                .annotations
                .iter()
                .filter(|a| {
                    a.kind == "comment"
                        && a.status == "open"
                        && a.target_kind.as_deref() == Some(target_k)
                        && a.target_id.as_deref() == Some(item_id_str.as_str())
                })
                .collect();
            let prefix = if is_sel { "" } else { "   " };
            let box_style = Style::default()
                .fg(if is_sel { Color::White } else { Color::Gray })
                .bg(row_bg);
            let mut spans = vec![
                Span::styled(prefix.to_string(), box_style),
                Span::styled(format!("{box_str} "), box_style),
                Span::styled(item.text.clone(), text_style),
            ];
            if item.kind == db::STEP_KIND_ACCEPTANCE {
                spans.push(Span::styled(" [accept]", Style::default().fg(Color::Blue)));
            }
            if item.source == "ai" {
                spans.push(Span::styled(" (ai)", Style::default().fg(Color::Magenta)));
            }
            if !fb.is_empty() {
                spans.push(Span::styled(
                    format!("  💬{}", fb.len()),
                    Style::default().fg(Color::Cyan),
                ));
            }
            if fb.iter().any(|a| a.request_revision) {
                spans.push(Span::styled("", Style::default().fg(Color::Yellow)));
            }
            lines.push(Line::from(spans));
            if let Some(intent) = &item.intent {
                lines.push(Line::from(Span::styled(
                    format!("         {intent}"),
                    Style::default().fg(Color::DarkGray),
                )));
            }
            // Verify command — how this step/criterion is checked.
            if let Some(v) = &item.verify_cmd {
                lines.push(Line::from(vec![
                    Span::styled(
                        "         verify ".to_string(),
                        Style::default().fg(Color::DarkGray),
                    ),
                    Span::styled(v.clone(), Style::default().fg(Color::Blue)),
                ]));
            }
            // Execution outcome recorded when the step was marked done.
            if let Some(r) = &item.result {
                lines.push(Line::from(vec![
                    Span::styled("".to_string(), Style::default().fg(Color::Green)),
                    Span::styled(r.clone(), Style::default().fg(Color::Green)),
                ]));
            }
            // Completion provenance: which commit / when the step was finished.
            if item.done && (item.done_commit.is_some() || item.done_at.is_some()) {
                let commit = item
                    .done_commit
                    .as_deref()
                    .map(|c| {
                        let short: String = c.chars().take(8).collect();
                        format!("@ {short}")
                    })
                    .unwrap_or_default();
                let when = item
                    .done_at
                    .as_deref()
                    .map(|w| format!("  {w}"))
                    .unwrap_or_default();
                lines.push(Line::from(Span::styled(
                    format!("         done {commit}{when}"),
                    Style::default().fg(Color::DarkGray),
                )));
            }
            // Thread: show comments anchored to this step/acceptance, indented.
            for a in &fb {
                let date = a.entry.with_timezone(&Local).format("%H:%M");
                let flag = if a.request_revision { "" } else { "" };
                lines.push(Line::from(vec![
                    Span::styled(
                        "".to_string(),
                        Style::default().fg(Color::DarkGray),
                    ),
                    Span::styled(
                        format!("{date}{flag}  "),
                        Style::default().fg(Color::DarkGray),
                    ),
                    Span::styled(a.text.clone(), Style::default().fg(Color::DarkGray)),
                ]));
            }
        }
    }

    // ── Verification: how to test/lint/run this task (project + task commands)
    let verif = verification_rows(d);
    if !verif.is_empty() {
        lines.push(Line::from(""));
        lines.push(section("Verification  (run: sara guide <id> --run)"));
        for (scope, label, cmd) in &verif {
            lines.push(Line::from(vec![
                Span::styled(
                    format!("  {label:<7}"),
                    Style::default()
                        .fg(Color::Gray)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled(cmd.clone(), Style::default().fg(Color::Blue)),
                Span::styled(format!("  ({scope})"), Style::default().fg(Color::DarkGray)),
            ]));
        }
    }

    // ── AI activity (provenance footer)
    if !d.ai_runs.is_empty() {
        lines.push(Line::from(""));
        lines.push(section("AI activity"));
        for r in &d.ai_runs {
            let date = r.created_at.with_timezone(&Local).format("%Y-%m-%d %H:%M");
            lines.push(Line::from(Span::styled(
                format!(
                    "  {} via {} [{}] @ {date}",
                    r.kind,
                    r.model.as_deref().unwrap_or("?"),
                    r.provider.as_deref().unwrap_or("?"),
                ),
                Style::default().fg(Color::DarkGray),
            )));
        }
    }
    // ── Similar tasks (shared tags, same project)
    if !d.similar.is_empty() {
        lines.push(Line::from(""));
        lines.push(section("Related tasks (shared tags)"));
        for (id, desc, urg) in &d.similar {
            lines.push(Line::from(vec![
                Span::styled(format!("  #{id:<3} "), Style::default().fg(Color::Gray)),
                Span::raw(desc.clone()),
                Span::styled(
                    format!("  urg {urg:.1}"),
                    Style::default().fg(Color::DarkGray),
                ),
            ]));
        }
    }
    // ── Comments section: task-level + replies only (anchored ones shown inline above) ─
    let all_comments: Vec<&crate::infrastructure::db::Annotation> = d
        .annotations
        .iter()
        .filter(|a| a.kind == "comment")
        .collect();
    let unthreaded: Vec<&crate::infrastructure::db::Annotation> = all_comments
        .iter()
        .copied()
        .filter(|a| a.target_kind.as_deref() != Some("anchor"))
        .collect();
    if !unthreaded.is_empty() {
        lines.push(Line::from(""));
        lines.push(section(
            "Comments  (↑/↓ select · c add · r reconsider · x resolve)",
        ));
        // Build an index: comment-id -> annotation, for resolving note: replies.
        let id_map: std::collections::HashMap<i64, &crate::infrastructure::db::Annotation> =
            all_comments.iter().map(|a| (a.id, *a)).collect();
        // Build an index: checklist-item-id -> text, for resolving step/acceptance replies.
        let checklist_map: std::collections::HashMap<i64, &str> = d
            .checklist
            .iter()
            .map(|it| (it.id, it.text.as_str()))
            .collect();

        for (ci, a) in all_comments.iter().enumerate() {
            if a.target_kind.as_deref() == Some("anchor") {
                continue;
            }
            let is_sel = sel == Some(Focusable::Comment(ci));
            let date = a.entry.with_timezone(&Local).format("%Y-%m-%d %H:%M");

            let target_label = match (a.target_kind.as_deref(), a.target_id.as_deref()) {
                (Some("note"), Some(idv)) => {
                    if let Ok(parent_id) = idv.parse::<i64>()
                        && let Some(parent) = id_map.get(&parent_id)
                    {
                        let snippet: String = parent.text.chars().take(40).collect();
                        format!("\"{snippet}\"  ")
                    } else {
                        String::new()
                    }
                }
                (Some("step"), Some(idv)) => {
                    if let Ok(item_id) = idv.parse::<i64>()
                        && let Some(text) = checklist_map.get(&item_id)
                    {
                        let snippet: String = text.chars().take(40).collect();
                        format!("step: \"{snippet}\"  ")
                    } else {
                        String::new()
                    }
                }
                (Some("acceptance"), Some(idv)) => {
                    if let Ok(item_id) = idv.parse::<i64>()
                        && let Some(text) = checklist_map.get(&item_id)
                    {
                        let snippet: String = text.chars().take(40).collect();
                        format!("accept: \"{snippet}\"  ")
                    } else {
                        String::new()
                    }
                }
                _ => String::new(),
            };

            let resolved = a.status == "resolved";
            let text_style = if resolved {
                Style::default()
                    .fg(Color::DarkGray)
                    .add_modifier(Modifier::CROSSED_OUT)
            } else if is_sel {
                Style::default().fg(Color::White).bg(Color::Blue)
            } else {
                Style::default()
            };
            let meta_style = if is_sel {
                Style::default().fg(Color::White).bg(Color::Blue)
            } else {
                Style::default().fg(Color::Gray)
            };
            let mut spans = vec![
                Span::styled(if is_sel { "" } else { "   " }.to_string(), meta_style),
                Span::styled(format!("{date}  "), meta_style),
            ];
            if !target_label.is_empty() {
                spans.push(Span::styled(
                    target_label,
                    if is_sel {
                        Style::default().fg(Color::White).bg(Color::Blue)
                    } else {
                        Style::default().fg(Color::Cyan)
                    },
                ));
            }
            if a.request_revision && !resolved {
                spans.push(Span::styled("", Style::default().fg(Color::Yellow)));
            }
            spans.push(Span::styled(a.text.clone(), text_style));
            lines.push(Line::from(spans));
        }
    }

    // History is rendered in its own box at the bottom — not in the main lines.

    // Split the main content area horizontally when wide enough for the panel.
    let show_panel = chunks[0].width >= 96;
    let (left_area, panel_area) = if show_panel {
        let cols = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Min(50), Constraint::Length(42)])
            .split(chunks[0]);
        (cols[0], Some(cols[1]))
    } else {
        (chunks[0], None)
    };

    let para = Paragraph::new(lines)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(title)
                .border_style(Style::default().fg(Color::Cyan)),
        )
        .wrap(Wrap { trim: false })
        .scroll((st.scroll, 0));
    f.render_widget(para, left_area);

    // ── Feature chain / dependency graph (top) + Git + stats
    if let Some(panel) = panel_area {
        // 'd' toggles between the linear chain panel (only meaningful when
        // the task is linked to others) and the dependency graph panel.
        // Unlike the chain panel, the graph panel stays visible even with no
        // blockers/dependents (showing "— none —") once toggled on — hiding
        // it silently on an empty task would look like the keypress did
        // nothing.
        let has_chain = d.chain.len() > 1;
        let graph_active = st.show_graph;
        let top_h: u16 = if graph_active {
            graph_panel_height(d, st)
        } else if has_chain {
            // +3 for border (2) and the progress bar row (1).
            ((d.chain.len() as u16) + 3).clamp(5, 14)
        } else {
            0
        };

        // The GitHub-style activity heatmap panel is deprecated for now (kept
        // out of the layout, not deleted — `render_mini_heatmap`/`d.activity`
        // are still populated in case this gets revisited).
        let constraints: Vec<Constraint> = if top_h > 0 {
            vec![
                Constraint::Length(top_h),
                Constraint::Min(4),
                Constraint::Length(14),
            ]
        } else {
            vec![Constraint::Min(4), Constraint::Length(14)]
        };
        let panel_chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints(constraints)
            .split(panel);

        let base = if graph_active {
            render_graph_panel(f, panel_chunks[0], d, st);
            1
        } else if has_chain {
            render_chain_panel(f, panel_chunks[0], d);
            1
        } else {
            0
        };

        let git_lines = git_panel_lines(d);
        let git_para = Paragraph::new(git_lines)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title(" Git ")
                    .border_style(Style::default().fg(Color::DarkGray)),
            )
            .wrap(Wrap { trim: false });
        f.render_widget(git_para, panel_chunks[base]);

        render_project_stats(f, panel_chunks[base + 1], d);
    }

    // ── History box (pinned to bottom, above edit bar and footer)
    if history_height > 0 {
        let hist_chunk = chunks[1]; // always chunk[1] when history is shown
        let hist_lines = history_lines(&d.history);
        let hist_para = Paragraph::new(hist_lines)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title(" History ")
                    .border_style(Style::default().fg(Color::DarkGray)),
            )
            .wrap(Wrap { trim: false });
        f.render_widget(hist_para, hist_chunk);
    }

    // ── Add-step bar ────────────────────────────────────────────────────────
    if st.adding_step {
        let edit_chunk_idx = if history_height > 0 { 2 } else { 1 };
        let block = Block::default()
            .borders(Borders::ALL)
            .title(" Add step  (Enter save · Esc cancel) ".to_string())
            .border_style(Style::default().fg(Color::Green));
        let inner = block.inner(chunks[edit_chunk_idx]);
        f.render_widget(block, chunks[edit_chunk_idx]);
        f.render_widget(&st.editor, inner);
    }

    // ── Comment bar (anchored to the focused element)
    if st.commenting {
        let edit_chunk_idx = if history_height > 0 { 2 } else { 1 };
        let items = focusables(d);
        let focus = items.get(st.selected).cloned();
        let (tk, tid) = comment_target(d, &focus);
        let target = match (tk, tid) {
            (Some(k), Some(i)) => format!("{k}:{i}"),
            _ => "task".to_string(),
        };
        let block = Block::default()
            .borders(Borders::ALL)
            .title(format!(" Comment on {target}  (Enter save · Esc cancel) "))
            .border_style(Style::default().fg(Color::Yellow));
        let inner = block.inner(chunks[edit_chunk_idx]);
        f.render_widget(block, chunks[edit_chunk_idx]);
        f.render_widget(&st.editor, inner);
    }

    // ── Edit bar (chunk index depends on whether history box is present)
    if st.editing {
        let edit_chunk_idx = if history_height > 0 { 2 } else { 1 };
        let field = EDIT_FIELDS
            .get(st.selected)
            .copied()
            .unwrap_or(EditField::Description);
        let (title, border) = if st.due_error {
            (
                format!(" Editing {} — invalid date ", field.label()),
                Color::Red,
            )
        } else if let Some(ref err) = st.dep_error {
            (format!(" Editing {}{} ", field.label(), err), Color::Red)
        } else if field == EditField::DependsOn {
            (
                format!(
                    " Editing {}  (task IDs, space/comma separated · Enter confirm · Esc cancel) ",
                    field.label()
                ),
                Color::Yellow,
            )
        } else {
            (
                format!(" Editing {}  (Enter confirm · Esc cancel) ", field.label()),
                Color::Yellow,
            )
        };
        let block = Block::default()
            .borders(Borders::ALL)
            .title(title)
            .border_style(Style::default().fg(border));
        let inner = block.inner(chunks[edit_chunk_idx]);
        f.render_widget(block, chunks[edit_chunk_idx]);
        f.render_widget(&st.editor, inner);
    }

    let footer = if st.adding_step {
        " type a step  •  Enter/Ctrl+S save  •  Esc cancel ".to_string()
    } else if st.commenting {
        " type a comment  •  Enter/Ctrl+S save  •  Esc cancel ".to_string()
    } else if st.editing {
        " type to edit  •  Enter/Ctrl+S confirm  •  Esc cancel ".to_string()
    } else {
        " ↑/↓ move • ⇧↑/⇧↓ reorder • a add step • Enter edit/open • c comment • Ctrl+E $EDITOR • d graph • ? help • q close "
            .to_string()
    };
    let footer_idx = chunks.len() - 1;
    f.render_widget(
        Paragraph::new(footer).style(Style::default().fg(Color::Gray)),
        chunks[footer_idx],
    );
}

/// Right-hand panel showing the dependency chain (feature) the task belongs to,
/// in blockers-first order: a progress bar plus one row per linked task. Completed
/// tasks are struck through; the task currently being viewed is highlighted.
fn render_chain_panel(f: &mut Frame, area: ratatui::layout::Rect, d: &Detail) {
    let total = d.chain.len();
    let done = d
        .chain
        .iter()
        .filter(|t| t.status == crate::infrastructure::model::Status::Completed)
        .count();
    let all_done = total > 0 && done == total;

    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" Feature chain  {done}/{total} "))
        .border_style(Style::default().fg(if all_done { Color::Green } else { Color::Cyan }));
    let inner = block.inner(area);
    f.render_widget(block, area);
    if inner.width == 0 || inner.height == 0 {
        return;
    }

    let mut lines: Vec<Line> = Vec::new();

    // Progress bar across the panel width.
    let bar_w = inner.width.saturating_sub(2) as usize;
    if bar_w > 0 {
        let filled = (done * bar_w + total / 2).checked_div(total).unwrap_or(0);
        let mut spans = vec![Span::raw(" ")];
        spans.push(Span::styled(
            "".repeat(filled),
            Style::default().fg(if all_done { Color::Green } else { Color::Cyan }),
        ));
        spans.push(Span::styled(
            "".repeat(bar_w - filled),
            Style::default().fg(Color::DarkGray),
        ));
        lines.push(Line::from(spans));
    }

    let current_idx = d.chain.iter().position(|t| t.uuid == d.task.uuid);
    let desc_w = inner.width.saturating_sub(8) as usize;
    for (i, t) in d.chain.iter().enumerate() {
        let completed = t.status == crate::infrastructure::model::Status::Completed;
        let is_current = Some(i) == current_idx;
        let id_str =
            t.id.map(|n| format!("{n:>3}"))
                .unwrap_or_else(|| "  -".to_string());
        let marker = if is_current { "" } else { "  " };
        let glyph = if completed {
            ""
        } else if is_current {
            ""
        } else {
            ""
        };
        let desc = truncate_str(&t.description, desc_w.max(8));

        let (glyph_style, text_style) = if is_current {
            (
                Style::default()
                    .fg(Color::White)
                    .bg(Color::Blue)
                    .add_modifier(Modifier::BOLD),
                Style::default()
                    .fg(Color::White)
                    .bg(Color::Blue)
                    .add_modifier(Modifier::BOLD),
            )
        } else if completed {
            (
                Style::default().fg(Color::Green),
                Style::default()
                    .fg(Color::DarkGray)
                    .add_modifier(Modifier::CROSSED_OUT),
            )
        } else {
            (
                Style::default().fg(Color::Cyan),
                Style::default().fg(Color::Gray),
            )
        };

        lines.push(Line::from(vec![
            Span::styled(marker.to_string(), glyph_style),
            Span::styled(format!("{glyph} "), glyph_style),
            Span::styled(format!("{id_str} "), text_style),
            Span::styled(desc, text_style),
        ]));
    }

    // Scroll so the current task stays visible in long chains (1 = progress bar row).
    let visible = inner.height as usize;
    let cur_line = current_idx.map(|i| i + 1).unwrap_or(0);
    let scroll = if cur_line >= visible {
        (cur_line + 1 - visible) as u16
    } else {
        0
    };

    f.render_widget(Paragraph::new(lines).scroll((scroll, 0)), inner);
}

/// Right-hand panel showing the depth-1 dependency graph: blockers above the
/// current task, dependents below. Each node shows only id + status glyph +
/// PR/issue badge (reusing `link_flags_by_task`'s already-computed flags, not
/// recomputing badge precedence) — deliberately no description, to stay
/// glanceable. Replaces `render_chain_panel` when active: the underlying
/// model is a real DAG that can branch across multiple features, which a
/// single linear chain can't represent.
fn render_graph_panel(f: &mut Frame, area: ratatui::layout::Rect, d: &Detail, st: &EditState) {
    let title = if st.graph_full_impact {
        " Dependency graph — full impact "
    } else {
        " Dependency graph "
    };
    let block = Block::default()
        .borders(Borders::ALL)
        .title(title)
        .border_style(Style::default().fg(Color::Magenta));
    let inner = block.inner(area);
    f.render_widget(block, area);
    if inner.width == 0 || inner.height == 0 {
        return;
    }

    let mut lines: Vec<Line> = Vec::new();

    if st.graph_full_impact {
        lines.push(graph_section_header(&format!(
            "← blocked by, full impact ({})",
            st.full_impact.len()
        )));
        push_graph_node_lines(&mut lines, &st.full_impact, st.full_impact.len(), true);
    } else {
        lines.push(graph_section_header(&format!(
            "← blocked by ({})",
            d.graph.blockers.len()
        )));
        push_graph_node_lines(
            &mut lines,
            &d.graph.blockers,
            GRAPH_NEIGHBOR_CAP,
            st.graph_expanded,
        );
    }

    let rule = "".repeat(inner.width as usize);
    lines.push(Line::from(Span::styled(
        rule.clone(),
        Style::default().fg(Color::DarkGray),
    )));
    lines.push(current_task_graph_line(&d.task));
    lines.push(Line::from(Span::styled(
        rule,
        Style::default().fg(Color::DarkGray),
    )));

    lines.push(graph_section_header(&format!(
        "blocks → ({})",
        d.graph.dependents.len()
    )));
    push_graph_node_lines(
        &mut lines,
        &d.graph.dependents,
        GRAPH_NEIGHBOR_CAP,
        st.graph_expanded,
    );

    f.render_widget(Paragraph::new(lines), inner);
}

fn graph_section_header(text: &str) -> Line<'static> {
    Line::from(Span::styled(
        format!(" {text}"),
        Style::default()
            .fg(Color::Gray)
            .add_modifier(Modifier::BOLD),
    ))
}

fn current_task_graph_line(task: &Task) -> Line<'static> {
    let id_str = task
        .id
        .map(|n| format!("{n:>3}"))
        .unwrap_or_else(|| "  -".to_string());
    let style = Style::default()
        .fg(Color::White)
        .bg(Color::Blue)
        .add_modifier(Modifier::BOLD);
    Line::from(vec![
        Span::styled("", style),
        Span::styled(format!("{id_str} "), style),
        Span::styled(truncate_str(&task.description, 24), style),
    ])
}

/// Append one line per visible node, capped at `cap` unless `expanded`, plus
/// a "+N more" summary line for whatever's left over. A single dedicated key
/// ('d', pressed again) reveals the rest inline rather than opening a
/// separate filtered-list screen — simpler, and depth-1 lists are short
/// enough that a whole new screen for the overflow felt disproportionate.
fn push_graph_node_lines(
    lines: &mut Vec<Line<'static>>,
    nodes: &[GraphNode],
    cap: usize,
    expanded: bool,
) {
    if nodes.is_empty() {
        lines.push(Line::from(Span::styled(
            "   — none —",
            Style::default().fg(Color::DarkGray),
        )));
        return;
    }
    let visible = if expanded {
        nodes.len()
    } else {
        cap.min(nodes.len())
    };
    for node in &nodes[..visible] {
        lines.push(graph_node_line(node));
    }
    let overflow = nodes.len() - visible;
    if overflow > 0 {
        lines.push(Line::from(Span::styled(
            format!("   +{overflow} more  (d to expand)"),
            Style::default()
                .fg(Color::DarkGray)
                .add_modifier(Modifier::ITALIC),
        )));
    }
}

fn graph_node_line(node: &GraphNode) -> Line<'static> {
    let completed = node.status == crate::infrastructure::model::Status::Completed;
    let glyph = if completed { "" } else { "" };
    let id_str = node
        .id
        .map(|n| format!("{n:>3}"))
        .unwrap_or_else(|| "  -".to_string());
    let style = if completed {
        Style::default()
            .fg(Color::DarkGray)
            .add_modifier(Modifier::CROSSED_OUT)
    } else {
        Style::default().fg(Color::Cyan)
    };
    let mut spans = vec![
        Span::styled(format!("   {glyph} "), style),
        Span::styled(id_str, style),
    ];
    if let Some(label) = link_badge_label(node.badge.as_ref()) {
        spans.push(Span::styled(
            format!("  {label}"),
            Style::default().fg(Color::Yellow),
        ));
    }
    Line::from(spans)
}

/// Badge label for a task's PR/issue links, mirroring `sara list`'s badge
/// precedence (PR > issue > generic link). Kept local rather than reusing
/// `commands::list`'s private `LinkBadge` type — command slices don't import
/// each other; only the underlying data (`link_flags_by_task`) is shared.
fn link_badge_label(flags: Option<&db::LinkFlags>) -> Option<&'static str> {
    let f = flags?;
    if f.pr {
        Some("PR")
    } else if f.issue {
        Some("ISS")
    } else if f.any {
        Some("")
    } else {
        None
    }
}

fn graph_panel_height(d: &Detail, st: &EditState) -> u16 {
    let blocker_rows = if st.graph_full_impact {
        graph_side_rows(st.full_impact.len(), true)
    } else {
        graph_side_rows(d.graph.blockers.len(), st.graph_expanded)
    };
    let dependent_rows = graph_side_rows(d.graph.dependents.len(), st.graph_expanded);
    // 2 borders + 2 section headers + 2 separators + 1 current-task row.
    let fixed = 2 + 2 + 2 + 1;
    ((blocker_rows + dependent_rows + fixed) as u16).clamp(7, 20)
}

fn graph_side_rows(len: usize, expanded: bool) -> usize {
    if len == 0 {
        return 1; // "— none —"
    }
    let visible = if expanded {
        len
    } else {
        GRAPH_NEIGHBOR_CAP.min(len)
    };
    let overflow_row = usize::from(!expanded && len > GRAPH_NEIGHBOR_CAP);
    visible + overflow_row
}

/// Build lines for the History box at the bottom of the detail view.
fn render_project_stats(f: &mut Frame, area: ratatui::layout::Rect, d: &Detail) {
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Project ")
        .border_style(Style::default().fg(Color::DarkGray));
    let inner = block.inner(area);
    f.render_widget(block, area);

    let Some(ref s) = d.stats else {
        return;
    };

    // Mini bar: fill `width` chars proportionally
    let bar = |count: u32, total: u32, width: usize| -> String {
        if total == 0 {
            return " ".repeat(width);
        }
        let filled = ((count as f64 / total as f64) * width as f64).round() as usize;
        "".repeat(filled.min(width))
    };

    let total_ever = s.pending + s.completed_total;
    let completion_rate = if total_ever > 0 {
        format!(
            "{:.0}%",
            s.completed_total as f64 / total_ever as f64 * 100.0
        )
    } else {
        "".to_string()
    };

    let w = inner.width.saturating_sub(2) as usize;
    let bar_w = w.saturating_sub(16).clamp(3, 10);

    let mut lines: Vec<Line> = vec![];

    // Status counts
    lines.push(Line::from(vec![
        Span::styled(
            format!("  {:<10}", "Pending"),
            Style::default().fg(Color::Gray),
        ),
        Span::raw(format!("{:>3}", s.pending)),
    ]));
    lines.push(Line::from(vec![
        Span::styled(
            format!("  {:<10}", "Active"),
            Style::default().fg(Color::Gray),
        ),
        Span::styled(
            format!("{:>3}", s.active),
            Style::default().fg(if s.active > 0 {
                Color::Green
            } else {
                Color::Reset
            }),
        ),
    ]));
    lines.push(Line::from(vec![
        Span::styled(
            format!("  {:<10}", "Done"),
            Style::default().fg(Color::Gray),
        ),
        Span::raw(format!("{:>3}", s.completed_total)),
        Span::styled(
            format!("  {}", completion_rate),
            Style::default().fg(Color::DarkGray),
        ),
    ]));

    lines.push(Line::from(Span::styled(
        "  ─────────────",
        Style::default().fg(Color::DarkGray),
    )));

    // Priority mini bars
    let pri_total = s.pending.max(1);
    lines.push(Line::from(vec![
        Span::styled(
            format!("  {:<5}", "H"),
            Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("{:<bar_w$}", bar(s.high, pri_total, bar_w)),
            Style::default().fg(Color::Red),
        ),
        Span::styled(format!(" {}", s.high), Style::default().fg(Color::DarkGray)),
    ]));
    lines.push(Line::from(vec![
        Span::styled(format!("  {:<5}", "M"), Style::default().fg(Color::Yellow)),
        Span::styled(
            format!("{:<bar_w$}", bar(s.medium, pri_total, bar_w)),
            Style::default().fg(Color::Yellow),
        ),
        Span::styled(
            format!(" {}", s.medium),
            Style::default().fg(Color::DarkGray),
        ),
    ]));
    lines.push(Line::from(vec![
        Span::styled(format!("  {:<5}", "L"), Style::default().fg(Color::Green)),
        Span::styled(
            format!("{:<bar_w$}", bar(s.low, pri_total, bar_w)),
            Style::default().fg(Color::Green),
        ),
        Span::styled(format!(" {}", s.low), Style::default().fg(Color::DarkGray)),
    ]));
    lines.push(Line::from(vec![
        Span::styled(
            format!("  {:<5}", ""),
            Style::default().fg(Color::DarkGray),
        ),
        Span::styled(
            format!("{:<bar_w$}", bar(s.no_pri, pri_total, bar_w)),
            Style::default().fg(Color::DarkGray),
        ),
        Span::styled(
            format!(" {}", s.no_pri),
            Style::default().fg(Color::DarkGray),
        ),
    ]));

    lines.push(Line::from(Span::styled(
        "  ─────────────",
        Style::default().fg(Color::DarkGray),
    )));

    // Due status
    if s.overdue > 0 {
        lines.push(Line::from(vec![
            Span::styled(
                format!("  {:<10}", "Overdue"),
                Style::default().fg(Color::Red),
            ),
            Span::styled(
                format!("{:>3}", s.overdue),
                Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
            ),
        ]));
    }
    if s.due_today > 0 {
        lines.push(Line::from(vec![
            Span::styled(
                format!("  {:<10}", "Today"),
                Style::default().fg(Color::Yellow),
            ),
            Span::styled(
                format!("{:>3}", s.due_today),
                Style::default().fg(Color::Yellow),
            ),
        ]));
    }
    let due_later = s.due_week.saturating_sub(s.due_today);
    if due_later > 0 {
        lines.push(Line::from(vec![
            Span::styled(
                format!("  {:<10}", "This week"),
                Style::default().fg(Color::Gray),
            ),
            Span::raw(format!("{:>3}", due_later)),
        ]));
    }

    f.render_widget(Paragraph::new(lines), inner);
}

fn render_mini_heatmap(
    f: &mut Frame,
    area: ratatui::layout::Rect,
    counts: &std::collections::HashMap<chrono::NaiveDate, u32>,
    project: &str,
) {
    use chrono::{Datelike, Duration, Local};

    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" {} ", project))
        .border_style(Style::default().fg(Color::DarkGray));
    let inner = block.inner(area);
    f.render_widget(block, area);

    let max = counts.values().copied().max().unwrap_or(1).max(1);
    let today = Local::now().date_naive();

    // Align to most recent Sunday
    let days_since_sunday = today.weekday().num_days_from_sunday();
    let grid_end = today - Duration::days(days_since_sunday as i64);

    // Fit weeks into available inner width: label(4) + weeks * 3
    let cell_w: u16 = 3; // "██ "
    let label_w: u16 = 4;
    let num_weeks = ((inner.width.saturating_sub(label_w)) / cell_w).clamp(4, 16) as i64;
    let grid_start = grid_end - Duration::weeks(num_weeks) + Duration::days(1);

    // Month label row (row 0 of inner)
    {
        let mut spans: Vec<Span> = vec![Span::raw(format!(
            "{:<width$}",
            "",
            width = label_w as usize
        ))];
        let mut last_month = 0u32;
        let mut ws = grid_start;
        for _ in 0..num_weeks {
            let m = ws.month();
            if m != last_month {
                let name = &month_abbr(m)[..3];
                spans.push(Span::styled(
                    format!("{:<width$}", name, width = cell_w as usize),
                    Style::default().fg(Color::DarkGray),
                ));
                last_month = m;
            } else {
                spans.push(Span::raw(format!(
                    "{:<width$}",
                    "",
                    width = cell_w as usize
                )));
            }
            ws += Duration::weeks(1);
        }
        let month_area = ratatui::layout::Rect {
            x: inner.x,
            y: inner.y,
            width: inner.width,
            height: 1,
        };
        f.render_widget(Paragraph::new(Line::from(spans)), month_area);
    }

    // 7 day rows (1..=7 of inner)
    const DAY_LABELS: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    const SHOW_LABEL: [bool; 7] = [false, true, false, true, false, true, false];

    for row in 0..7u32 {
        if inner.y + 1 + row as u16 >= inner.y + inner.height {
            break;
        }
        let mut spans: Vec<Span> = vec![];
        let label = if SHOW_LABEL[row as usize] {
            DAY_LABELS[row as usize]
        } else {
            "   "
        };
        spans.push(Span::styled(
            format!("{label} "),
            Style::default().fg(Color::DarkGray),
        ));

        let mut ws = grid_start;
        for _ in 0..num_weeks {
            let day = ws + Duration::days(row as i64);
            let in_future = day > today;
            let count = if in_future {
                0
            } else {
                counts.get(&day).copied().unwrap_or(0)
            };
            let color = if in_future {
                Color::Rgb(12, 14, 18)
            } else {
                heat_color_mini(count, max)
            };
            spans.push(Span::styled("██ ", Style::default().bg(color).fg(color)));
            ws += Duration::weeks(1);
        }

        let row_area = ratatui::layout::Rect {
            x: inner.x,
            y: inner.y + 1 + row as u16,
            width: inner.width,
            height: 1,
        };
        f.render_widget(Paragraph::new(Line::from(spans)), row_area);
    }

    // Stats line at the bottom
    let total: u32 = counts.values().sum();
    let stats_area = ratatui::layout::Rect {
        x: inner.x,
        y: inner.y + 8,
        width: inner.width,
        height: 1,
    };
    if stats_area.y < inner.y + inner.height {
        f.render_widget(
            Paragraph::new(Line::from(Span::styled(
                format!("  {total} events (16w)"),
                Style::default().fg(Color::DarkGray),
            ))),
            stats_area,
        );
    }
}

fn heat_color_mini(count: u32, max: u32) -> Color {
    if count == 0 {
        return Color::Rgb(22, 27, 34);
    }
    let ratio = count as f64 / max.max(1) as f64;
    if ratio < 0.25 {
        Color::Rgb(14, 68, 41)
    } else if ratio < 0.5 {
        Color::Rgb(0, 109, 50)
    } else if ratio < 0.75 {
        Color::Rgb(38, 166, 65)
    } else {
        Color::Rgb(57, 211, 83)
    }
}

pub(super) fn history_lines(
    history: &[crate::infrastructure::db::HistoryEntry],
) -> Vec<Line<'static>> {
    let mut lines = vec![];
    for h in history.iter().rev() {
        let date = h
            .changed_at
            .with_timezone(&Local)
            .format("%m-%d %H:%M")
            .to_string();
        let label = if h.field == "annotation" {
            "comment"
        } else {
            &h.field
        };
        let mut spans = vec![
            Span::styled(format!("  {date}  "), Style::default().fg(Color::DarkGray)),
            Span::styled(format!("{:<11} ", label), Style::default().fg(Color::Cyan)),
        ];
        // Additive fields render as +/− when exactly one side is set; a
        // checklist toggle (both sides set) falls through to the arrow form.
        let additive = matches!(
            h.field.as_str(),
            "annotation" | "link" | "dependency" | "checklist" | "file"
        ) && h.old_value.is_none() != h.new_value.is_none();
        if h.field == "created" {
            spans.push(Span::raw(h.new_value.clone().unwrap_or_default()));
        } else if additive {
            if let Some(text) = &h.new_value {
                spans.push(Span::styled("+ ", Style::default().fg(Color::Green)));
                spans.push(Span::raw(text.clone()));
            } else if let Some(text) = &h.old_value {
                spans.push(Span::styled("", Style::default().fg(Color::Red)));
                spans.push(Span::raw(text.clone()));
            }
        } else {
            spans.push(Span::styled(
                h.old_value.clone().unwrap_or_else(|| "".into()),
                Style::default().fg(Color::Gray),
            ));
            spans.push(Span::styled("", Style::default().fg(Color::DarkGray)));
            spans.push(Span::raw(h.new_value.clone().unwrap_or_else(|| "".into())));
        }
        lines.push(Line::from(spans));
    }
    lines
}

/// Build the content lines for the Git branch panel.
fn git_panel_lines(d: &Detail) -> Vec<Line<'static>> {
    let mut lines: Vec<Line<'static>> = vec![];

    let Some(rec) = &d.branch else {
        lines.push(Line::from(Span::styled(
            "  No branch tied.",
            Style::default().fg(Color::DarkGray),
        )));
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "  Run: sara <id> addbranch",
            Style::default().fg(Color::Gray),
        )));
        lines.push(Line::from(Span::styled(
            "  Then: sara stop <id> to snapshot.",
            Style::default().fg(Color::Gray),
        )));
        return lines;
    };

    // Branch name line
    lines.push(Line::from(vec![
        Span::styled("  Branch  ", Style::default().fg(Color::DarkGray)),
        Span::styled(
            rec.branch.clone(),
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ),
    ]));
    if let Some(base) = &rec.base {
        lines.push(Line::from(vec![
            Span::styled("  Base    ", Style::default().fg(Color::DarkGray)),
            Span::styled(base.clone(), Style::default().fg(Color::Gray)),
        ]));
    }
    if let Some(logged_at) = rec.logged_at {
        let ts = logged_at
            .with_timezone(&Local)
            .format("%Y-%m-%d %H:%M")
            .to_string();
        lines.push(Line::from(vec![
            Span::styled("  Logged  ", Style::default().fg(Color::DarkGray)),
            Span::styled(ts, Style::default().fg(Color::Gray)),
        ]));
    }
    lines.push(Line::from(""));

    match &rec.files {
        None => {
            lines.push(Line::from(Span::styled(
                "  No snapshot yet.",
                Style::default().fg(Color::DarkGray),
            )));
            lines.push(Line::from(Span::styled(
                "  Run: sara stop <id>",
                Style::default().fg(Color::Gray),
            )));
        }
        Some(files) if files.is_empty() => {
            lines.push(Line::from(Span::styled(
                "  No changes vs base.",
                Style::default().fg(Color::Green),
            )));
        }
        Some(files) => {
            const MAX_FILES: usize = 20;
            lines.push(Line::from(Span::styled(
                format!(
                    "  {} file{} changed",
                    files.len(),
                    if files.len() == 1 { "" } else { "s" }
                ),
                Style::default().fg(Color::Yellow),
            )));
            for f in files.iter().take(MAX_FILES) {
                // Show only filename for brevity; full path on hover isn't feasible in TUI
                let name = std::path::Path::new(f)
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or(f.as_str());
                lines.push(Line::from(vec![
                    Span::styled("    ", Style::default()),
                    Span::styled(name.to_string(), Style::default().fg(Color::Cyan)),
                    if name != f.as_str() {
                        Span::styled(format!("  {}", f), Style::default().fg(Color::DarkGray))
                    } else {
                        Span::raw("")
                    },
                ]));
            }
            if files.len() > MAX_FILES {
                lines.push(Line::from(Span::styled(
                    format!("    +{} more", files.len() - MAX_FILES),
                    Style::default().fg(Color::DarkGray),
                )));
            }
        }
    }

    // Overlap section
    if !d.overlaps.is_empty() {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "  ⚠  Potential overlaps",
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        )));
        for ov in &d.overlaps {
            lines.push(Line::from(vec![
                Span::styled(
                    format!("  [{:>2}] ", ov.id),
                    Style::default().fg(Color::Gray),
                ),
                Span::styled(
                    truncate_str(&ov.description, 20),
                    Style::default().fg(Color::Yellow),
                ),
                Span::styled(
                    format!(" ({})", ov.branch),
                    Style::default().fg(Color::DarkGray),
                ),
            ]));
            for sf in &ov.shared_files {
                let name = std::path::Path::new(sf)
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or(sf.as_str());
                lines.push(Line::from(Span::styled(
                    format!("{name}"),
                    Style::default().fg(Color::Red),
                )));
            }
        }
    }

    lines
}

fn truncate_str(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        let t: String = s.chars().take(max - 1).collect();
        format!("{t}")
    }
}

/// A selectable file/link row with a `›` marker when focused.
fn nav_line<'a>(text: &str, color: Color, italic: bool, selected: bool) -> Line<'a> {
    let mut style = Style::default().fg(color);
    if italic {
        style = style.add_modifier(Modifier::ITALIC);
    }
    if selected {
        style = style
            .bg(Color::Blue)
            .fg(Color::White)
            .add_modifier(Modifier::BOLD);
    }
    let prefix = if selected { "" } else { "   " };
    Line::from(vec![
        Span::styled(prefix.to_string(), style),
        Span::styled(text.to_string(), style),
    ])
}

/// A single rendered row with optional selection highlight (blue bg).
#[allow(dead_code)]
fn sel_line<'a>(spans: Vec<Span<'a>>, selected: bool) -> Line<'a> {
    if !selected {
        return Line::from(spans);
    }
    // Paint the entire row blue so it's unmissable.
    let highlighted: Vec<Span> = spans
        .into_iter()
        .map(|s| Span::styled(s.content, s.style.bg(Color::Blue).fg(Color::White)))
        .collect();
    Line::from(highlighted)
}

fn editable_line<'a>(k: &str, v: &str, selected: bool, field: EditField, task: &Task) -> Line<'a> {
    let (bg, fg) = if selected {
        (Color::Blue, Color::White)
    } else {
        (Color::Reset, Color::Gray)
    };
    let key_style = if selected {
        Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(fg)
    };

    // Priority gets a colored value.
    let value_span = if field == EditField::Priority {
        match &task.priority {
            Some(Priority::H) => Span::styled("High", Style::default().fg(Color::Red)),
            Some(Priority::M) => Span::styled("Medium", Style::default().fg(Color::Yellow)),
            Some(Priority::L) => Span::styled("Low", Style::default().fg(Color::Green)),
            None => Span::styled("-", Style::default().fg(Color::Gray)),
        }
    } else if field == EditField::Due {
        due_value_span(task, v)
    } else {
        Span::raw(v.to_string())
    };

    let prefix = if selected { "" } else { "   " };
    let value_style = if selected {
        Style::default().fg(Color::White).bg(Color::Blue)
    } else {
        Style::default()
    };
    let value_span = Span::styled(value_span.content, value_span.style.patch(value_style));
    Line::from(vec![
        Span::styled(prefix.to_string(), key_style),
        Span::styled(format!("{:<12}", k), key_style),
        value_span,
    ])
}

fn due_value_span<'a>(task: &Task, fallback: &str) -> Span<'a> {
    if let Some(dd) = task.due {
        let days = (dd - Utc::now()).num_days();
        let color = if days < 0 {
            Color::Red
        } else if days <= 1 {
            Color::Yellow
        } else {
            Color::Reset
        };
        Span::styled(
            dd.with_timezone(&Local)
                .format("%Y-%m-%d %H:%M")
                .to_string(),
            Style::default().fg(color),
        )
    } else {
        Span::styled(fallback.to_string(), Style::default().fg(Color::Gray))
    }
}

fn key_span(k: &str) -> Span<'static> {
    Span::styled(format!("  {:<12}", k), Style::default().fg(Color::Gray))
}

fn field_line<'a>(k: &str, v: &str) -> Line<'a> {
    Line::from(vec![key_span(k), Span::raw(v.to_string())])
}

fn section(k: &str) -> Line<'static> {
    Line::from(Span::styled(
        k.to_string(),
        Style::default()
            .add_modifier(Modifier::BOLD)
            .fg(Color::Cyan),
    ))
}

fn month_abbr(m: u32) -> &'static str {
    match m {
        1 => "Jan",
        2 => "Feb",
        3 => "Mar",
        4 => "Apr",
        5 => "May",
        6 => "Jun",
        7 => "Jul",
        8 => "Aug",
        9 => "Sep",
        10 => "Oct",
        11 => "Nov",
        12 => "Dec",
        _ => "???",
    }
}

#[cfg(test)]
mod tests {
    use super::super::types::DependencyGraph;
    use super::*;
    use crate::infrastructure::model::{Status, Task};
    use ratatui::{Terminal, backend::TestBackend};

    fn task() -> Task {
        Task::new("root task".into(), "tk".into())
    }

    fn node(id: i64, status: Status) -> GraphNode {
        GraphNode {
            uuid: uuid::Uuid::new_v4(),
            id: Some(id),
            status,
            badge: None,
        }
    }

    fn base_detail(task: Task) -> Detail {
        Detail {
            task,
            blocked_by: vec![],
            blocking: vec![],
            depends_on_ids: vec![],
            manual_files: vec![],
            suggested_files: vec![],
            links: vec![],
            annotations: vec![],
            history: vec![],
            project_root: None,
            branch: None,
            overlaps: vec![],
            similar: vec![],
            checklist: vec![],
            urgency_breakdown: None,
            activity: std::collections::HashMap::new(),
            stats: None,
            guide: crate::infrastructure::db::TaskGuideFields::default(),
            anchors: vec![],
            ai_runs: vec![],
            head_commit: None,
            project_commands: crate::infrastructure::db::ProjectCommands::default(),
            chain: vec![],
            graph: DependencyGraph::default(),
        }
    }

    fn base_state(detail: Detail) -> EditState {
        EditState {
            detail,
            selected: 0,
            editing: false,
            commenting: false,
            adding_step: false,
            editor: tui_textarea::TextArea::default(),
            due_error: false,
            dep_error: None,
            scroll: 0,
            show_graph: true,
            graph_expanded: false,
            graph_full_impact: false,
            full_impact: vec![],
        }
    }

    fn draw(st: &EditState) -> String {
        // Wide enough that render()'s `chunks[0].width >= 96` gate shows the
        // side panel at all, and tall enough that the panel's own stacked
        // constraints (graph/chain + Git(14) + stats(11) + Min(4)) don't get
        // starved and silently truncated by Layout::split.
        let mut terminal = Terminal::new(TestBackend::new(140, 60)).unwrap();
        terminal.draw(|f| render(f, st)).unwrap();
        let buf = terminal.backend().buffer();
        let area = *buf.area();
        let mut out = String::new();
        for y in 0..area.height {
            let mut line = String::new();
            for x in 0..area.width {
                line.push_str(buf[(x, y)].symbol());
            }
            out.push_str(line.trim_end());
            out.push('\n');
        }
        out
    }

    #[test]
    fn graph_panel_does_not_panic_when_empty() {
        let mut d = base_detail(task());
        d.graph = DependencyGraph::default();
        let st = base_state(d);
        let out = draw(&st);
        assert!(out.contains("Dependency graph"));
        assert!(out.contains("none"));
    }

    #[test]
    fn graph_panel_shows_branching_blockers_and_dependents() {
        let mut d = base_detail(task());
        d.graph = DependencyGraph {
            blockers: vec![node(1, Status::Pending), node(2, Status::Completed)],
            dependents: vec![node(3, Status::Pending)],
        };
        let st = base_state(d);
        let out = draw(&st);
        // Both blockers (one completed, one pending) and the dependent render
        // as distinct rows — this is exactly what the old linear chain panel
        // couldn't do for a task with neighbors in different features.
        assert!(out.contains("blocked by (2)"));
        assert!(out.contains("blocks"));
        assert!(out.contains("1"));
        assert!(out.contains("2"));
        assert!(out.contains("3"));
    }

    #[test]
    fn graph_panel_collapses_overflow_to_a_summary_row_by_default() {
        let mut d = base_detail(task());
        d.graph = DependencyGraph {
            blockers: (1..=8).map(|i| node(i, Status::Pending)).collect(),
            dependents: vec![],
        };
        let st = base_state(d);
        let out = draw(&st);
        assert!(out.contains("more"));
        // Only the first GRAPH_NEIGHBOR_CAP ids should be visible, not all 8.
        assert!(out.contains(&format!("{GRAPH_NEIGHBOR_CAP}")) || out.contains("more"));
    }

    #[test]
    fn graph_panel_expanded_shows_everything_and_drops_the_summary_row() {
        let mut d = base_detail(task());
        d.graph = DependencyGraph {
            blockers: (1..=8).map(|i| node(i, Status::Pending)).collect(),
            dependents: vec![],
        };
        let mut st = base_state(d);
        st.graph_expanded = true;
        let out = draw(&st);
        assert!(!out.contains("more"));
        for i in 1..=8 {
            assert!(
                out.contains(&i.to_string()),
                "expected id {i} to be visible"
            );
        }
    }

    #[test]
    fn graph_panel_full_impact_shows_transitive_blockers_and_ignores_the_cap() {
        let mut d = base_detail(task());
        d.graph = DependencyGraph {
            blockers: vec![node(1, Status::Pending)],
            dependents: vec![],
        };
        let mut st = base_state(d);
        st.graph_full_impact = true;
        st.full_impact = (100..=106).map(|i| node(i, Status::Pending)).collect();
        let out = draw(&st);
        assert!(out.contains("full impact"));
        // The full-impact list (7 items) ignores GRAPH_NEIGHBOR_CAP entirely.
        assert!(!out.contains("more"));
        assert!(out.contains("100"));
        assert!(out.contains("106"));
    }
}