frame 0.1.5

A markdown task tracker with a terminal UI for humans and a CLI for 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
use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;

use regex::Regex;

use unicode_segmentation::UnicodeSegmentation;

use crate::model::{Metadata, Task, TaskState};
use crate::ops::task_ops;
use crate::tui::app::{App, DetailRegion, Mode, ReturnView, View, flatten_subtask_ids};
use crate::tui::input::{multiline_selection_range, selection_cols_for_line};
use crate::tui::theme::Theme;
use crate::tui::wrap;
use crate::util::unicode;

use super::helpers::{abbreviated_id, collect_metadata_list, state_symbol};
use super::push_highlighted_spans;

/// Render the detail view for a single task
pub fn render_detail_view(frame: &mut Frame, app: &mut App, area: Rect) {
    let (track_id, task_id) = match &app.view {
        View::Detail { track_id, task_id } => (track_id.clone(), task_id.clone()),
        _ => return,
    };

    let track = match App::find_track_in_project(&app.project, &track_id) {
        Some(t) => t,
        None => {
            let empty = Paragraph::new(" Task not found")
                .style(Style::default().fg(app.theme.dim).bg(app.theme.background));
            frame.render_widget(empty, area);
            return;
        }
    };

    let task = match task_ops::find_task_in_track(track, &task_id) {
        Some(t) => t,
        None => {
            let empty = Paragraph::new(" Task not found")
                .style(Style::default().fg(app.theme.dim).bg(app.theme.background));
            frame.render_widget(empty, area);
            return;
        }
    };

    // Rebuild regions from current task state
    let regions = App::build_detail_regions(task);
    // Rebuild flat_subtask_ids
    let flat_subtask_ids = flatten_subtask_ids(task);
    if let Some(ref mut ds) = app.detail_state {
        ds.regions = regions.clone();
        ds.regions_populated = regions
            .iter()
            .map(|r| App::is_detail_region_populated(task, *r))
            .collect();
        // Clamp region to valid range
        if !regions.contains(&ds.region) {
            ds.region = regions.first().copied().unwrap_or(DetailRegion::Title);
        }
        ds.flat_subtask_ids = flat_subtask_ids;
        // Clamp subtask_cursor
        if !ds.flat_subtask_ids.is_empty() {
            ds.subtask_cursor = ds.subtask_cursor.min(ds.flat_subtask_ids.len() - 1);
        } else {
            ds.subtask_cursor = 0;
        }
    }

    let is_flashing = app.is_flashing(&task_id);

    let detail_state = app.detail_state.as_ref();
    let current_region = detail_state
        .map(|ds| ds.region)
        .unwrap_or(DetailRegion::Title);
    let editing = detail_state.is_some_and(|ds| ds.editing);
    let selected_subtask_id = detail_state.and_then(|ds| {
        if ds.region == DetailRegion::Subtasks {
            ds.flat_subtask_ids.get(ds.subtask_cursor).cloned()
        } else {
            None
        }
    });

    let bg = app.theme.background;
    let text_style = Style::default().fg(app.theme.text).bg(bg);
    let bright_style = Style::default().fg(app.theme.text_bright).bg(bg);
    let dim_style = Style::default().fg(app.theme.dim).bg(bg);
    let region_indicator_style = Style::default().fg(app.theme.highlight).bg(bg);

    // Search highlighting
    let search_re = app.active_search_re();
    let highlight_style = Style::default()
        .fg(app.theme.search_match_fg)
        .bg(app.theme.search_match_bg)
        .add_modifier(Modifier::BOLD);

    let width = area.width as usize;

    // -----------------------------------------------------------------------
    // Build HEADER lines (fixed, non-scrolling): blank + breadcrumb + title + blank separator
    // -----------------------------------------------------------------------
    let mut header_lines: Vec<Line<'static>> = Vec::new();
    let mut header_active_line: Option<usize> = None;
    // Always track title line range for flash (independent of cursor region)
    #[allow(unused_assignments)]
    let mut title_line_start: usize = 0;
    #[allow(unused_assignments)]
    let mut title_line_end: usize = 0;

    // Blank line at top for breathing room
    header_lines.push(Line::from(""));

    // Breadcrumb trail: always visible, showing origin > [stack...] > current
    {
        let mut crumb_spans: Vec<Span> = Vec::new();
        crumb_spans.push(Span::styled("   ", Style::default().bg(bg)));

        // First crumb: origin view label
        let origin_label = match app
            .detail_state
            .as_ref()
            .map(|ds| &ds.return_view)
            .unwrap_or(&ReturnView::Track(0))
        {
            ReturnView::Recent => "Recent".to_string(),
            ReturnView::Board => "Board".to_string(),
            ReturnView::Track(idx) => {
                let tid = app.active_track_ids.get(*idx).cloned().unwrap_or_default();
                app.track_prefix(&tid).unwrap_or(&tid).to_string()
            }
        };
        crumb_spans.push(Span::styled(origin_label, dim_style));

        // Middle crumbs: from detail_stack
        for (_stack_track, stack_task) in app.detail_stack.iter() {
            crumb_spans.push(Span::styled(" > ", dim_style));
            crumb_spans.push(Span::styled(stack_task.clone(), dim_style));
        }

        // Last crumb: current task ID (bright)
        crumb_spans.push(Span::styled(" > ", dim_style));
        crumb_spans.push(Span::styled(
            task_id.clone(),
            Style::default().fg(app.theme.text).bg(bg),
        ));

        header_lines.push(Line::from(crumb_spans));
        header_lines.push(Line::from(""));
    }

    // --- Title region (in header) ---
    {
        let is_active = current_region == DetailRegion::Title;
        if is_active {
            header_active_line = Some(header_lines.len());
        }
        let state_color = app.theme.state_color(task.state);
        let state_sym = state_symbol(task.state);
        let mut spans: Vec<Span> = Vec::new();

        // Region indicator
        spans.push(region_indicator(is_active, region_indicator_style, bg));

        // State symbol
        spans.push(Span::styled(
            state_sym,
            Style::default()
                .fg(state_color)
                .bg(bg)
                .add_modifier(Modifier::BOLD),
        ));
        spans.push(Span::styled(" ", Style::default().bg(bg)));

        // ID
        if let Some(ref id) = task.id {
            push_highlighted_spans(
                &mut spans,
                &format!("{} ", id),
                text_style,
                highlight_style,
                search_re.as_ref(),
            );
        }

        // Title
        if is_active && editing && app.mode == Mode::Edit {
            // Render edit buffer with cursor
            let (aw, hs) = render_edit_inline_scrolled(&mut spans, app, bright_style, width);
            app.last_edit_available_width = aw;
            app.edit_h_scroll = hs;
            title_line_start = header_lines.len();
            title_line_end = title_line_start;
            header_lines.push(Line::from(spans));
        } else {
            push_highlighted_spans(
                &mut spans,
                &task.title,
                bright_style.add_modifier(Modifier::BOLD),
                highlight_style,
                search_re.as_ref(),
            );
            let wrapped = wrap_styled_spans(spans, width, 3, bg);
            let start = header_lines.len();
            header_lines.extend(wrapped);
            title_line_start = start;
            title_line_end = header_lines.len().saturating_sub(1);
            if is_active {
                header_active_line = Some(start);
            }
        }
    }

    // Blank line before metadata fields (end of header)
    header_lines.push(Line::from(""));

    // -----------------------------------------------------------------------
    // Build BODY lines (scrollable): tags through subtasks
    // -----------------------------------------------------------------------
    let mut body_lines: Vec<Line<'static>> = Vec::new();
    let mut body_active_line: Option<usize> = None;
    let mut edit_anchor_col: Option<u16> = None;
    let mut edit_anchor_line: Option<usize> = None; // index into body_lines
    #[allow(unused_assignments)]
    let mut note_header_idx: usize = 0; // index into body_lines
    // Track body line ranges per region for targeted flash
    let mut region_line_ranges: std::collections::HashMap<DetailRegion, (usize, usize)> =
        std::collections::HashMap::new();

    // --- Tags region ---
    {
        let region_start = body_lines.len();
        let is_active = current_region == DetailRegion::Tags;
        if is_active {
            body_active_line = Some(body_lines.len());
        }
        let mut spans: Vec<Span> = Vec::new();
        spans.push(region_indicator(is_active, region_indicator_style, bg));
        spans.push(Span::styled("tags: ", dim_style));

        if is_active && editing && app.mode == Mode::Edit {
            edit_anchor_col = Some(
                spans
                    .iter()
                    .map(|s| unicode::display_width(&s.content) as u16)
                    .sum(),
            );
            edit_anchor_line = Some(body_lines.len());
            let (aw, hs) = render_edit_inline_scrolled(&mut spans, app, bright_style, width);
            app.last_edit_available_width = aw;
            app.edit_h_scroll = hs;
            body_lines.push(Line::from(spans));
        } else if task.tags.is_empty() {
            spans.push(Span::styled("(none)", dim_style));
            body_lines.push(Line::from(spans));
        } else {
            for (i, tag) in task.tags.iter().enumerate() {
                let tag_color = app.theme.tag_color(tag);
                let tag_style = Style::default().fg(tag_color).bg(bg);
                if i > 0 {
                    spans.push(Span::styled(" ", Style::default().bg(bg)));
                }
                push_highlighted_spans(
                    &mut spans,
                    &format!("#{}", tag),
                    tag_style,
                    highlight_style,
                    search_re.as_ref(),
                );
            }
            let wrapped = wrap_styled_spans(spans, width, 9, bg);
            let start = body_lines.len();
            body_lines.extend(wrapped);
            if is_active {
                body_active_line = Some(start);
            }
        }
        if body_lines.len() > region_start {
            region_line_ranges.insert(DetailRegion::Tags, (region_start, body_lines.len() - 1));
        }
    }

    // --- Added region ---
    for meta in &task.metadata {
        if let Metadata::Added(date) = meta {
            let is_active = current_region == DetailRegion::Added;
            if is_active {
                body_active_line = Some(body_lines.len());
            }
            let spans: Vec<Span> = vec![
                region_indicator(is_active, region_indicator_style, bg),
                Span::styled("added: ", dim_style),
                Span::styled(date.clone(), text_style),
            ];
            body_lines.push(Line::from(spans));
            break;
        }
    }

    // --- Deps region ---
    {
        let region_start = body_lines.len();
        let is_active = current_region == DetailRegion::Deps;
        if is_active {
            body_active_line = Some(body_lines.len());
        }
        let deps = collect_metadata_list(task, |m| {
            if let Metadata::Dep(d) = m {
                Some(d)
            } else {
                None
            }
        });

        if is_active && editing && app.mode == Mode::Edit {
            let mut spans: Vec<Span> = Vec::new();
            spans.push(region_indicator(is_active, region_indicator_style, bg));
            spans.push(Span::styled("dep: ", dim_style));
            edit_anchor_col = Some(
                spans
                    .iter()
                    .map(|s| unicode::display_width(&s.content) as u16)
                    .sum(),
            );
            edit_anchor_line = Some(body_lines.len());
            let (aw, hs) = render_edit_inline_scrolled(&mut spans, app, bright_style, width);
            app.last_edit_available_width = aw;
            app.edit_h_scroll = hs;
            body_lines.push(Line::from(spans));
        } else if !deps.is_empty() {
            let mut spans: Vec<Span> = Vec::new();
            spans.push(region_indicator(is_active, region_indicator_style, bg));
            spans.push(Span::styled("dep: ", dim_style));

            for (i, dep_id) in deps.iter().enumerate() {
                if i > 0 {
                    spans.push(Span::styled(", ", dim_style));
                }
                // Look up dep state for inline symbol
                let dep_state = find_task_state_across_tracks(app, dep_id);
                let dep_style = if let Some(state) = dep_state {
                    Style::default().fg(app.theme.state_color(state)).bg(bg)
                } else {
                    text_style
                };
                push_highlighted_spans(
                    &mut spans,
                    dep_id,
                    text_style,
                    highlight_style,
                    search_re.as_ref(),
                );
                if let Some(state) = dep_state {
                    spans.push(Span::styled(format!(" {}", state_symbol(state)), dep_style));
                }
            }
            let wrapped = wrap_styled_spans(spans, width, 8, bg);
            let start = body_lines.len();
            body_lines.extend(wrapped);
            if is_active {
                body_active_line = Some(start);
            }
        } else if is_active {
            let spans: Vec<Span> = vec![
                region_indicator(is_active, region_indicator_style, bg),
                Span::styled("dep: ", dim_style),
                Span::styled("(none)", dim_style),
            ];
            body_lines.push(Line::from(spans));
        }
        if body_lines.len() > region_start {
            region_line_ranges.insert(DetailRegion::Deps, (region_start, body_lines.len() - 1));
        }
    }

    // --- Spec region ---
    {
        let region_start = body_lines.len();
        let is_active = current_region == DetailRegion::Spec;
        if is_active {
            body_active_line = Some(body_lines.len());
        }
        let spec = task.metadata.iter().find_map(|m| {
            if let Metadata::Spec(s) = m {
                Some(s.clone())
            } else {
                None
            }
        });

        if is_active && editing && app.mode == Mode::Edit {
            let mut spans: Vec<Span> = Vec::new();
            spans.push(region_indicator(is_active, region_indicator_style, bg));
            spans.push(Span::styled("spec: ", dim_style));
            edit_anchor_col = Some(
                spans
                    .iter()
                    .map(|s| unicode::display_width(&s.content) as u16)
                    .sum(),
            );
            edit_anchor_line = Some(body_lines.len());
            let (aw, hs) = render_edit_inline_scrolled(&mut spans, app, bright_style, width);
            app.last_edit_available_width = aw;
            app.edit_h_scroll = hs;
            body_lines.push(Line::from(spans));
        } else if let Some(spec_val) = &spec {
            let mut spans: Vec<Span> = vec![
                region_indicator(is_active, region_indicator_style, bg),
                Span::styled("spec: ", dim_style),
            ];
            let cyan_style = Style::default().fg(app.theme.cyan).bg(bg);
            push_highlighted_spans(
                &mut spans,
                spec_val,
                cyan_style,
                highlight_style,
                search_re.as_ref(),
            );
            let wrapped = wrap_styled_spans(spans, width, 9, bg);
            let start = body_lines.len();
            body_lines.extend(wrapped);
            if is_active {
                body_active_line = Some(start);
            }
        } else if is_active {
            let spans: Vec<Span> = vec![
                region_indicator(is_active, region_indicator_style, bg),
                Span::styled("spec: ", dim_style),
                Span::styled("(none)", dim_style),
            ];
            body_lines.push(Line::from(spans));
        }
        if body_lines.len() > region_start {
            region_line_ranges.insert(DetailRegion::Spec, (region_start, body_lines.len() - 1));
        }
    }

    // --- Refs region ---
    {
        let region_start = body_lines.len();
        let is_active = current_region == DetailRegion::Refs;
        if is_active {
            body_active_line = Some(body_lines.len());
        }
        let refs = collect_metadata_list(task, |m| {
            if let Metadata::Ref(r) = m {
                Some(r)
            } else {
                None
            }
        });

        if is_active && editing && app.mode == Mode::Edit {
            let mut spans: Vec<Span> = Vec::new();
            spans.push(region_indicator(is_active, region_indicator_style, bg));
            spans.push(Span::styled("ref: ", dim_style));
            edit_anchor_col = Some(
                spans
                    .iter()
                    .map(|s| unicode::display_width(&s.content) as u16)
                    .sum(),
            );
            edit_anchor_line = Some(body_lines.len());
            let (aw, hs) = render_edit_inline_scrolled(&mut spans, app, bright_style, width);
            app.last_edit_available_width = aw;
            app.edit_h_scroll = hs;
            body_lines.push(Line::from(spans));
        } else if !refs.is_empty() {
            let start = body_lines.len();
            for (i, ref_path) in refs.iter().enumerate() {
                let mut spans: Vec<Span> = Vec::new();
                spans.push(region_indicator(
                    is_active && i == 0,
                    region_indicator_style,
                    bg,
                ));
                if i == 0 {
                    spans.push(Span::styled("ref: ", dim_style));
                } else {
                    spans.push(Span::styled("     ", dim_style));
                }
                let cyan_style = Style::default().fg(app.theme.cyan).bg(bg);
                push_highlighted_spans(
                    &mut spans,
                    ref_path,
                    cyan_style,
                    highlight_style,
                    search_re.as_ref(),
                );
                let wrapped = wrap_styled_spans(spans, width, 8, bg);
                body_lines.extend(wrapped);
            }
            if is_active {
                body_active_line = Some(start);
            }
        } else if is_active {
            let spans: Vec<Span> = vec![
                region_indicator(is_active, region_indicator_style, bg),
                Span::styled("ref: ", dim_style),
                Span::styled("(none)", dim_style),
            ];
            body_lines.push(Line::from(spans));
        }
        if body_lines.len() > region_start {
            region_line_ranges.insert(DetailRegion::Refs, (region_start, body_lines.len() - 1));
        }
    }

    // Blank line before note
    body_lines.push(Line::from(""));

    let mut note_gutter_width: usize = 3;

    // --- Note region ---
    {
        let is_active = current_region == DetailRegion::Note;
        note_header_idx = body_lines.len();
        if is_active {
            body_active_line = Some(note_header_idx);
        }
        let note = task.metadata.iter().find_map(|m| {
            if let Metadata::Note(n) = m {
                Some(n.clone())
            } else {
                None
            }
        });

        if is_active && editing && app.mode == Mode::Edit {
            // Compute gutter width from edit buffer line count
            let edit_line_count = app
                .detail_state
                .as_ref()
                .map(|ds| ds.edit_buffer.split('\n').count())
                .unwrap_or(1);
            let gutter_width = wrap::gutter_width(edit_line_count);
            let num_display_width = gutter_width - 1;
            note_gutter_width = gutter_width;

            // Multi-line editing mode
            let header_prefix = format!("{}\u{258E} ", " ".repeat(gutter_width.saturating_sub(2)));
            let header_spans: Vec<Span> = vec![
                Span::styled(header_prefix, region_indicator_style),
                Span::styled("note:", dim_style),
            ];
            body_lines.push(Line::from(header_spans));

            // Render the multi-line edit buffer
            let note_available = width.saturating_sub(gutter_width);
            app.last_edit_available_width = note_available as u16;
            let mut adjusted_h_scroll = 0usize;
            if let Some(ref ds) = app.detail_state {
                let cursor_style = Style::default()
                    .fg(app.theme.background)
                    .bg(app.theme.text_bright);
                let selection_style = Style::default()
                    .fg(app.theme.text_bright)
                    .bg(app.theme.blue);
                let dim_arrow_style = Style::default().fg(app.theme.dim).bg(bg);
                let cursor_col = ds.edit_cursor_col;

                // Compute selection range (absolute offsets) if any
                let sel_range = multiline_selection_range(ds);
                let edit_lines: Vec<&str> = ds.edit_buffer.split('\n').collect();

                if app.note_wrap && note_available > 0 {
                    // --- Wrap-aware rendering ---
                    let visual_lines = wrap::wrap_lines_for_edit(
                        &edit_lines,
                        note_available,
                        ds.edit_cursor_line,
                        cursor_col,
                    );
                    let cursor_vrow =
                        wrap::logical_to_visual_row(&visual_lines, ds.edit_cursor_line, cursor_col);

                    for (vrow_idx, vl) in visual_lines.iter().enumerate() {
                        let mut spans: Vec<Span> = Vec::new();
                        let line_text = edit_lines.get(vl.logical_line).copied().unwrap_or("");
                        let slice = &line_text[vl.byte_start..vl.byte_end];
                        let graphemes: Vec<(usize, &str)> =
                            unicode_segmentation::UnicodeSegmentation::grapheme_indices(
                                slice, true,
                            )
                            .collect();

                        let has_cursor = vrow_idx == cursor_vrow;
                        if has_cursor {
                            body_active_line = Some(body_lines.len());
                        }

                        // Gutter: line number on first visual row, blank on continuations
                        if vl.is_first {
                            let num_str = format!(
                                "{:>width$} ",
                                vl.logical_line + 1,
                                width = num_display_width,
                            );
                            spans.push(Span::styled(num_str, text_style));
                        } else {
                            spans.push(Span::styled(
                                " ".repeat(gutter_width),
                                Style::default().bg(bg),
                            ));
                        }

                        // Compute selection columns for this visual row (in logical coords)
                        // These are byte offsets within the logical line.
                        let vl_sel = sel_range.and_then(|(s, e)| {
                            selection_cols_for_line(&ds.edit_buffer, s, e, vl.logical_line)
                        });

                        // Cursor byte offset within this visual row
                        let cursor_byte_in_row = if has_cursor {
                            Some(cursor_col.saturating_sub(vl.char_start))
                        } else {
                            None
                        };

                        if let Some((sc, ec)) = vl_sel {
                            // Selection active on this logical line
                            for &(gi, g) in &graphemes {
                                let abs_byte = vl.byte_start + gi;
                                let s = if abs_byte >= sc && abs_byte < ec {
                                    selection_style
                                } else {
                                    bright_style
                                };
                                if cursor_byte_in_row == Some(gi) {
                                    spans.push(Span::styled(g.to_string(), cursor_style));
                                } else {
                                    spans.push(Span::styled(g.to_string(), s));
                                }
                            }
                            // Blank line selection indicator
                            if sc == ec && graphemes.is_empty() && !has_cursor {
                                spans.push(Span::styled(" ", selection_style));
                            }
                            // Cursor past end of visual row
                            if has_cursor && cursor_col >= vl.char_end {
                                spans.push(Span::styled(" ", cursor_style));
                            }
                        } else if has_cursor {
                            let byte_in_row =
                                cursor_col.min(vl.char_end).saturating_sub(vl.char_start);
                            for &(gi, g) in &graphemes {
                                if gi == byte_in_row {
                                    spans.push(Span::styled(g.to_string(), cursor_style));
                                } else {
                                    spans.push(Span::styled(g.to_string(), bright_style));
                                }
                            }
                            if byte_in_row >= slice.len() {
                                spans.push(Span::styled(" ", cursor_style));
                            }
                        } else if !slice.is_empty() {
                            spans.push(Span::styled(slice.to_string(), bright_style));
                        }

                        body_lines.push(Line::from(spans));
                    }
                } else {
                    // --- Original horizontal-scroll rendering ---
                    let mut h_scroll = ds.note_h_scroll;
                    if note_available > 0 {
                        let margin = 10.min(note_available / 3);
                        let cursor_line_len =
                            edit_lines.get(ds.edit_cursor_line).map_or(0, |l| l.len());
                        let content_end = if cursor_col >= cursor_line_len {
                            cursor_line_len + 1
                        } else {
                            cursor_line_len
                        };
                        if cursor_col >= h_scroll + note_available.saturating_sub(margin) {
                            h_scroll = cursor_col
                                .saturating_sub(note_available.saturating_sub(margin + 1));
                        }
                        h_scroll = h_scroll
                            .min(content_end.saturating_sub(note_available.saturating_sub(1)));
                        if cursor_col < h_scroll + margin {
                            h_scroll = cursor_col.saturating_sub(margin);
                        }
                    }
                    adjusted_h_scroll = h_scroll;

                    for (line_idx, edit_line) in edit_lines.iter().enumerate() {
                        let mut spans: Vec<Span> = Vec::new();

                        let has_cursor = line_idx == ds.edit_cursor_line;
                        if has_cursor {
                            body_active_line = Some(body_lines.len());
                        }

                        let graphemes: Vec<(usize, &str)> =
                            unicode_segmentation::UnicodeSegmentation::grapheme_indices(
                                *edit_line, true,
                            )
                            .collect();
                        let total_graphemes = graphemes.len();
                        let clipped_left = h_scroll > 0 && total_graphemes > 0;
                        let left_indicator = if clipped_left { 1 } else { 0 };
                        let avail_after_left = note_available.saturating_sub(left_indicator);
                        let clipped_right = h_scroll + avail_after_left < total_graphemes;
                        let right_indicator = if clipped_right { 1 } else { 0 };
                        let view_count = avail_after_left.saturating_sub(right_indicator);
                        let view_start = h_scroll.min(total_graphemes);
                        let view_end = (view_start + view_count).min(total_graphemes);

                        let line_num_str =
                            format!("{:>width$}", line_idx + 1, width = num_display_width);
                        if clipped_left {
                            spans.push(Span::styled(line_num_str, text_style));
                            spans.push(Span::styled("\u{25C2}", dim_arrow_style)); // â—‚
                        } else {
                            spans.push(Span::styled(format!("{} ", line_num_str), text_style));
                        }

                        let line_sel = sel_range.and_then(|(s, e)| {
                            selection_cols_for_line(&ds.edit_buffer, s, e, line_idx)
                        });

                        // Convert cursor byte offset to grapheme index for comparison
                        let cursor_gi = graphemes
                            .iter()
                            .position(|&(bo, _)| bo >= cursor_col)
                            .unwrap_or(total_graphemes);

                        if let Some((sc, ec)) = line_sel {
                            for (gi, &(bo, g)) in graphemes
                                .iter()
                                .enumerate()
                                .skip(view_start)
                                .take(view_end - view_start)
                            {
                                let s = if bo >= sc && bo < ec {
                                    selection_style
                                } else {
                                    bright_style
                                };
                                if has_cursor && gi == cursor_gi {
                                    spans.push(Span::styled(g.to_string(), cursor_style));
                                } else {
                                    spans.push(Span::styled(g.to_string(), s));
                                }
                            }
                            if sc == ec && total_graphemes == 0 && !has_cursor {
                                spans.push(Span::styled(" ", selection_style));
                            }
                            if has_cursor && cursor_gi >= total_graphemes && cursor_gi >= view_start
                            {
                                spans.push(Span::styled(" ", cursor_style));
                            }
                        } else if has_cursor {
                            let col_gi = cursor_gi.min(total_graphemes);
                            for (gi, &(_bo, g)) in graphemes
                                .iter()
                                .enumerate()
                                .skip(view_start)
                                .take(view_end - view_start)
                            {
                                if gi == col_gi {
                                    spans.push(Span::styled(g.to_string(), cursor_style));
                                } else {
                                    spans.push(Span::styled(g.to_string(), bright_style));
                                }
                            }
                            if col_gi >= total_graphemes && col_gi >= view_start {
                                spans.push(Span::styled(" ", cursor_style));
                            }
                        } else if view_start < view_end {
                            let slice: String = graphemes[view_start..view_end]
                                .iter()
                                .map(|g| g.1)
                                .collect();
                            spans.push(Span::styled(slice, bright_style));
                        }

                        if clipped_right {
                            spans.push(Span::styled("\u{25B8}", dim_arrow_style)); // â–¸
                        }

                        body_lines.push(Line::from(spans));
                    }
                }
            }
            // Write back adjusted h_scroll (after immutable borrow of detail_state is released)
            if let Some(ds_mut) = app.detail_state.as_mut() {
                ds_mut.note_h_scroll = adjusted_h_scroll;
            }
        } else if let Some(note_text) = &note {
            // Compute gutter width from note line count
            let line_count = note_text.lines().count();
            let gutter_width = wrap::gutter_width(line_count);
            let num_display_width = gutter_width - 1;
            note_gutter_width = gutter_width;

            let header_prefix = if is_active {
                format!("{}\u{258E} ", " ".repeat(gutter_width.saturating_sub(2)))
            } else {
                " ".repeat(gutter_width)
            };
            let header_spans: Vec<Span> = vec![
                Span::styled(
                    header_prefix,
                    if is_active {
                        region_indicator_style
                    } else {
                        Style::default().bg(bg)
                    },
                ),
                Span::styled("note:", dim_style),
            ];
            body_lines.push(Line::from(header_spans));

            let line_num_style = Style::default().fg(app.theme.dim).bg(bg);
            let mut in_code_block = false;
            for (line_num, note_line) in note_text.lines().enumerate() {
                let trimmed = note_line.trim();
                if trimmed.starts_with("```") {
                    in_code_block = !in_code_block;
                }

                let num_str = format!("{:>width$} ", line_num + 1, width = num_display_width);
                if in_code_block || trimmed.starts_with("```") {
                    let code_style = Style::default().fg(app.theme.dim).bg(bg);
                    let mut spans: Vec<Span> = vec![Span::styled(num_str, line_num_style)];
                    push_highlighted_spans(
                        &mut spans,
                        note_line,
                        code_style,
                        highlight_style,
                        search_re.as_ref(),
                    );
                    body_lines.push(Line::from(spans));
                } else {
                    // Wrap content separately to keep line number as a single span
                    let mut content_spans: Vec<Span> = Vec::new();
                    push_highlighted_spans(
                        &mut content_spans,
                        note_line,
                        text_style,
                        highlight_style,
                        search_re.as_ref(),
                    );
                    let content_width = width.saturating_sub(gutter_width);
                    let wrapped = wrap_styled_spans(content_spans, content_width, 0, bg);
                    for (i, wrapped_line) in wrapped.into_iter().enumerate() {
                        let prefix = if i == 0 {
                            Span::styled(num_str.clone(), line_num_style)
                        } else {
                            Span::styled(" ".repeat(gutter_width), Style::default().bg(bg))
                        };
                        let mut line_spans = vec![prefix];
                        line_spans.extend(wrapped_line.spans);
                        body_lines.push(Line::from(line_spans));
                    }
                }
            }
        } else if is_active {
            let spans: Vec<Span> = vec![
                region_indicator(is_active, region_indicator_style, bg),
                Span::styled("note: ", dim_style),
                Span::styled("(empty)", dim_style),
            ];
            body_lines.push(Line::from(spans));
        }
    }
    let note_content_end_idx = body_lines.len().saturating_sub(1);
    if note_content_end_idx >= note_header_idx {
        region_line_ranges.insert(DetailRegion::Note, (note_header_idx, note_content_end_idx));
    }

    // --- Subtasks region ---
    if !task.subtasks.is_empty() {
        body_lines.push(Line::from(""));
        let is_active = current_region == DetailRegion::Subtasks;
        if is_active && selected_subtask_id.is_none() {
            // Only set header as active if no subtask is selected
            body_active_line = Some(body_lines.len());
        }

        let mut header_spans: Vec<Span> = Vec::new();
        let header_indicator = is_active && selected_subtask_id.is_none();
        header_spans.push(region_indicator(
            header_indicator,
            region_indicator_style,
            bg,
        ));
        header_spans.push(Span::styled(
            "Subtasks",
            bright_style.add_modifier(Modifier::BOLD),
        ));
        body_lines.push(Line::from(header_spans));

        let subtask_selected_line = render_subtask_tree(
            &mut body_lines,
            app,
            &task.subtasks,
            1,
            width,
            bg,
            selected_subtask_id.as_deref(),
            search_re.as_ref(),
            highlight_style,
        );
        // When a subtask is selected, use its line for scroll tracking
        if is_active && let Some(sl) = subtask_selected_line {
            body_active_line = Some(sl);
        }
    }

    // -----------------------------------------------------------------------
    // Apply flash/highlight/note decorations
    // -----------------------------------------------------------------------

    let (flash_bg, flash_border) = match app.flash_state {
        Some(state) => state_flash_colors(state, &app.theme),
        None => UNDO_FLASH_COLORS,
    };

    // Flash highlights the edited region: body region for field edits, header for state changes
    if is_flashing {
        if let Some(region) = app.flash_detail_region {
            if let Some(&(start, end)) = region_line_ranges.get(&region) {
                apply_flash_to_lines(&mut body_lines, start, end, flash_bg, flash_border, width);
            } else {
                // Region not visible — fall back to header
                apply_flash_to_lines(
                    &mut header_lines,
                    title_line_start,
                    title_line_end,
                    flash_bg,
                    flash_border,
                    width,
                );
            }
        } else {
            apply_flash_to_lines(
                &mut header_lines,
                title_line_start,
                title_line_end,
                flash_bg,
                flash_border,
                width,
            );
        }
    }

    // Store total lines, note header, and note content end for input handler use
    // (body-relative indices, since that's what the input handler scrolls through)
    if let Some(ds) = app.detail_state.as_mut() {
        ds.total_lines = body_lines.len();
        ds.note_header_line = Some(note_header_idx);
        ds.note_content_end = note_content_end_idx;
    }

    // If note_view_line is set, override body_active_line with the virtual cursor
    // and move the region indicator to that line (only within note content bounds)
    if let Some(ds) = app.detail_state.as_ref()
        && let Some(vl) = ds.note_view_line
    {
        let clamped = vl.min(note_content_end_idx);
        body_active_line = Some(clamped);
        // Replace the leading gutter with the cursor indicator on the target line
        let cursor_indicator = format!(
            "{}\u{258E} ",
            " ".repeat(note_gutter_width.saturating_sub(2))
        );
        if let Some(line) = body_lines.get_mut(clamped) {
            let mut new_spans: Vec<Span<'static>> = Vec::new();
            new_spans.push(Span::styled(
                cursor_indicator.clone(),
                region_indicator_style,
            ));
            // Skip the first span if it's the gutter (line number or blank padding)
            let mut skipped_prefix = false;
            for span in line.spans.iter() {
                if !skipped_prefix {
                    let content_len = unicode::display_width(&span.content);
                    if content_len == note_gutter_width {
                        skipped_prefix = true;
                        continue;
                    }
                }
                new_spans.push(span.clone());
            }
            *line = Line::from(new_spans);
        }
        // Remove indicator from the note header line (if different)
        if clamped != note_header_idx
            && let Some(line) = body_lines.get_mut(note_header_idx)
        {
            let mut new_spans: Vec<Span<'static>> = Vec::new();
            for span in line.spans.iter() {
                if span.content.contains('\u{258E}') {
                    new_spans.push(Span::styled(
                        " ".repeat(note_gutter_width),
                        Style::default().bg(bg),
                    ));
                } else {
                    new_spans.push(span.clone());
                }
            }
            *line = Line::from(new_spans);
        }
    }

    // Apply active-region highlight: selection_bg on the cursor line, pad to full width
    let is_editing = app.detail_state.as_ref().is_some_and(|ds| ds.editing);
    let on_subtask_region =
        current_region == DetailRegion::Subtasks && selected_subtask_id.is_some();
    if !is_flashing && !is_editing && !on_subtask_region {
        // Apply to header (Title region) or body (all other regions)
        let (target_lines, target_line) = if current_region == DetailRegion::Title {
            (
                &mut header_lines as &mut Vec<Line<'static>>,
                header_active_line,
            )
        } else {
            (&mut body_lines as &mut Vec<Line<'static>>, body_active_line)
        };
        if let Some(rl) = target_line {
            let sel_bg = app.theme.selection_bg;
            if let Some(line) = target_lines.get_mut(rl) {
                let mut new_spans: Vec<Span<'static>> = Vec::new();
                for span in line.spans.drain(..) {
                    let content = span.content.into_owned();
                    let is_indicator = content.contains('\u{258E}');
                    let is_search_match = span.style.bg == Some(app.theme.search_match_bg);
                    let new_style = if is_search_match {
                        // Preserve search highlight styling on the selection line
                        span.style
                    } else if is_indicator {
                        Style::default().fg(app.theme.selection_border).bg(sel_bg)
                    } else {
                        // Brighten text on the selection line
                        let fg = if span.style.fg == Some(app.theme.dim)
                            || span.style.fg == Some(app.theme.text)
                        {
                            app.theme.text_bright
                        } else {
                            span.style.fg.unwrap_or(app.theme.text_bright)
                        };
                        let mut s = Style::default().fg(fg).bg(sel_bg);
                        if span.style.add_modifier.contains(Modifier::BOLD) {
                            s = s.add_modifier(Modifier::BOLD);
                        }
                        s
                    };
                    new_spans.push(Span::styled(content, new_style));
                }
                let content_width: usize = new_spans
                    .iter()
                    .map(|s| unicode::display_width(&s.content))
                    .sum();
                if content_width < width {
                    new_spans.push(Span::styled(
                        " ".repeat(width - content_width),
                        Style::default().bg(sel_bg),
                    ));
                }
                *line = Line::from(new_spans);
            }
        }
    }

    // When Note region is active (not editing), brighten note body text
    let is_note_active = current_region == DetailRegion::Note && !is_editing;
    if is_note_active {
        // Brighten all note body lines (from header+1 to note_content_end)
        let note_body_start = note_header_idx + 1;
        for line_idx in note_body_start..=note_content_end_idx {
            // Skip the cursor line (already highlighted above)
            if body_active_line == Some(line_idx) {
                continue;
            }
            if let Some(line) = body_lines.get_mut(line_idx) {
                let mut new_spans: Vec<Span<'static>> = Vec::new();
                for (span_idx, span) in line.spans.drain(..).enumerate() {
                    let content = span.content.into_owned();
                    if span_idx == 0 {
                        // Keep line number gutter dim
                        new_spans.push(Span::styled(content, span.style));
                    } else {
                        let fg = if span.style.fg == Some(app.theme.text)
                            || span.style.fg == Some(app.theme.dim)
                        {
                            app.theme.text_bright
                        } else {
                            span.style.fg.unwrap_or(app.theme.text_bright)
                        };
                        new_spans.push(Span::styled(content, span.style.fg(fg)));
                    }
                }
                *line = Line::from(new_spans);
            }
        }
    }

    // -----------------------------------------------------------------------
    // Layout: split area into header (fixed) and body (scrollable)
    // -----------------------------------------------------------------------
    let header_height = header_lines.len().min(area.height as usize);
    let header_area = Rect::new(area.x, area.y, area.width, header_height as u16);
    let body_area = Rect::new(
        area.x,
        area.y + header_height as u16,
        area.width,
        area.height.saturating_sub(header_height as u16),
    );

    // Render header (no scroll)
    let header_paragraph = Paragraph::new(header_lines).style(Style::default().bg(bg));
    frame.render_widget(header_paragraph, header_area);

    // Handle body scrolling using tracked body region line index with margin-aware logic
    let body_visible_height = body_area.height as usize;
    let body_total_lines = body_lines.len();

    let is_note_editing = app
        .detail_state
        .as_ref()
        .is_some_and(|ds| ds.editing && ds.region == DetailRegion::Note);
    let scroll_margin = if is_note_editing { 4 } else { 2 };

    if let (Some(ds), Some(rl)) = (&mut app.detail_state, body_active_line) {
        let top_bound = ds.scroll_offset + scroll_margin;
        let bottom_bound = ds
            .scroll_offset
            .saturating_add(body_visible_height.saturating_sub(scroll_margin + 1));
        if rl < top_bound {
            ds.scroll_offset = rl.saturating_sub(scroll_margin);
        } else if rl > bottom_bound {
            ds.scroll_offset = (rl + scroll_margin + 1).saturating_sub(body_visible_height);
        }
    }

    let scroll = app
        .detail_state
        .as_ref()
        .map(|ds| ds.scroll_offset)
        .unwrap_or(0);

    let body_paragraph = Paragraph::new(body_lines)
        .style(Style::default().bg(bg))
        .scroll((scroll as u16, 0));
    frame.render_widget(body_paragraph, body_area);

    // Vertical scroll indicators (in body area)
    let dim_indicator_style = Style::default().fg(app.theme.dim).bg(bg);
    if scroll > 0 && body_area.height > 0 {
        let arrow = Paragraph::new("\u{25B2}").style(dim_indicator_style); // â–²
        frame.render_widget(
            arrow,
            Rect::new(body_area.right().saturating_sub(2), body_area.y, 1, 1),
        );
    }
    if scroll + body_visible_height < body_total_lines && body_area.height > 0 {
        let arrow = Paragraph::new("\u{25BC}").style(dim_indicator_style); // â–¼
        frame.render_widget(
            arrow,
            Rect::new(
                body_area.right().saturating_sub(2),
                body_area.bottom().saturating_sub(1),
                1,
                1,
            ),
        );
    }

    // Set autocomplete anchor for detail view edits (body-relative)
    if let (Some(prefix_w), Some(line_idx)) = (edit_anchor_col, edit_anchor_line) {
        let word_offset = app
            .autocomplete
            .as_ref()
            .map(|ac| ac.word_start_in_buffer(&app.edit_buffer) as u16)
            .unwrap_or(0);
        let screen_y = body_area.y + line_idx.saturating_sub(scroll) as u16;
        let screen_x = body_area.x + prefix_w + word_offset;
        app.autocomplete_anchor = Some((screen_x, screen_y));
    } else if app.mode == Mode::Triage {
        // Cross-track move from detail view: anchor autocomplete to title in header area
        let screen_y = header_area.y + header_active_line.unwrap_or(0) as u16;
        let screen_x = header_area.x + 4;
        app.autocomplete_anchor = Some((screen_x, screen_y));
    }
}

/// Wrap styled spans across multiple lines, respecting word boundaries.
/// `continuation_indent` is the number of spaces to prepend on wrapped continuation lines.
pub(super) fn wrap_styled_spans(
    spans: Vec<Span<'static>>,
    max_width: usize,
    continuation_indent: usize,
    bg: ratatui::style::Color,
) -> Vec<Line<'static>> {
    if max_width == 0 {
        return vec![Line::from(spans)];
    }

    let mut result_lines: Vec<Vec<Span<'static>>> = Vec::new();
    let mut current_line: Vec<Span<'static>> = Vec::new();
    let mut col: usize = 0; // current column position on this line

    for span in spans {
        let style = span.style;
        let text: &str = &span.content;

        if text.is_empty() {
            current_line.push(span);
            continue;
        }

        // Process this span's text character by character, splitting at word boundaries
        let mut remaining = text;
        while !remaining.is_empty() {
            // Find the next word boundary (whitespace vs non-whitespace transition)
            let chunk_end = if remaining.starts_with(char::is_whitespace) {
                // Whitespace chunk
                remaining
                    .find(|c: char| !c.is_whitespace())
                    .unwrap_or(remaining.len())
            } else {
                // Word chunk
                remaining
                    .find(char::is_whitespace)
                    .unwrap_or(remaining.len())
            };
            let chunk = &remaining[..chunk_end];
            let chunk_chars = unicode::display_width(chunk);

            if col + chunk_chars <= max_width {
                // Fits on current line
                current_line.push(Span::styled(chunk.to_string(), style));
                col += chunk_chars;
            } else if chunk.starts_with(char::is_whitespace) {
                // Whitespace at wrap point — include as many chars as fit
                // on the current line, put the rest on the next line.
                let remaining_space = max_width.saturating_sub(col);
                let mut fit_end = 0;
                let mut fit_width = 0;
                for grapheme in unicode_segmentation::UnicodeSegmentation::graphemes(chunk, true) {
                    let gw = unicode::display_width(grapheme);
                    if fit_width + gw > remaining_space {
                        break;
                    }
                    fit_width += gw;
                    fit_end += grapheme.len();
                }
                if fit_end > 0 {
                    current_line.push(Span::styled(chunk[..fit_end].to_string(), style));
                }
                result_lines.push(std::mem::take(&mut current_line));
                let indent_str = " ".repeat(continuation_indent);
                current_line.push(Span::styled(indent_str, Style::default().bg(bg)));
                col = continuation_indent;
                let rest = &chunk[fit_end..];
                if !rest.is_empty() {
                    current_line.push(Span::styled(rest.to_string(), style));
                    col += unicode::display_width(rest);
                }
            } else {
                // Word doesn't fit on current line.
                // Decide whether to break mid-word or wrap to next line.
                let remaining_space = max_width.saturating_sub(col);
                let blank_fraction = if max_width > 0 {
                    remaining_space as f64 / max_width as f64
                } else {
                    0.0
                };

                if blank_fraction <= 0.5 || remaining_space == 0 {
                    // Word-wrap: start new line first
                    result_lines.push(std::mem::take(&mut current_line));
                    let indent_str = " ".repeat(continuation_indent);
                    current_line.push(Span::styled(indent_str, Style::default().bg(bg)));
                    col = continuation_indent;
                }

                // Grapheme-wrap the chunk across as many lines as needed
                let mut effective_width = max_width.saturating_sub(col);
                let mut seg = String::new();
                let mut seg_width = 0usize;
                for grapheme in unicode_segmentation::UnicodeSegmentation::graphemes(chunk, true) {
                    let gw = unicode::display_width(grapheme);
                    if seg_width + gw > effective_width && !seg.is_empty() {
                        // Emit current segment and start new line
                        current_line.push(Span::styled(std::mem::take(&mut seg), style));
                        result_lines.push(std::mem::take(&mut current_line));
                        let indent_str = " ".repeat(continuation_indent);
                        current_line.push(Span::styled(indent_str, Style::default().bg(bg)));
                        col = continuation_indent;
                        seg_width = 0;
                        effective_width = max_width.saturating_sub(continuation_indent);
                    }
                    seg.push_str(grapheme);
                    seg_width += gw;
                }
                if !seg.is_empty() {
                    current_line.push(Span::styled(seg, style));
                    col += seg_width;
                }
            }
            remaining = &remaining[chunk_end..];
        }
    }

    // Push the last line
    if !current_line.is_empty() {
        result_lines.push(current_line);
    }

    if result_lines.is_empty() {
        vec![Line::from("")]
    } else {
        result_lines.into_iter().map(Line::from).collect()
    }
}

/// Render the edit buffer inline with horizontal scrolling for the detail view.
/// Auto-adjusts h_scroll to keep the cursor visible.
/// Returns `(available_width, adjusted_h_scroll)` for the caller to persist on App.
fn render_edit_inline_scrolled(
    spans: &mut Vec<Span<'static>>,
    app: &App,
    style: Style,
    total_width: usize,
) -> (u16, usize) {
    let prefix_width: usize = spans
        .iter()
        .map(|s| unicode::display_width(&s.content))
        .sum();
    let available = total_width.saturating_sub(prefix_width);

    if available == 0 {
        return (available as u16, app.edit_h_scroll);
    }

    let buf = &app.edit_buffer;
    let total_display = unicode::display_width(buf);
    let cursor_col = unicode::byte_offset_to_display_col(buf, app.edit_cursor.min(buf.len()));

    // Auto-adjust h_scroll (in display columns) to keep cursor visible.
    let content_end = if cursor_col >= total_display {
        total_display + 1
    } else {
        total_display
    };
    let mut h_scroll = app.edit_h_scroll;
    let margin = 10.min(available / 3);
    if cursor_col >= h_scroll + available.saturating_sub(margin) {
        h_scroll = cursor_col.saturating_sub(available.saturating_sub(margin + 1));
    }
    h_scroll = h_scroll.min(content_end.saturating_sub(available.saturating_sub(1)));
    if cursor_col < h_scroll + margin {
        h_scroll = cursor_col.saturating_sub(margin);
    }

    let clipped_left = h_scroll > 0;
    let indicator_overhead = if clipped_left { 1 } else { 0 };
    let effective_available = available.saturating_sub(indicator_overhead);
    let clipped_right = h_scroll + effective_available < total_display;
    let effective_available = if clipped_right {
        effective_available.saturating_sub(1)
    } else {
        effective_available
    };

    let dim_arrow_style = Style::default().fg(app.theme.dim).bg(app.theme.background);

    if clipped_left {
        spans.push(Span::styled("\u{25C2}", dim_arrow_style));
    }

    let cursor_style = Style::default()
        .fg(app.theme.background)
        .bg(app.theme.text_bright);
    let selection_style = Style::default()
        .fg(app.theme.text_bright)
        .bg(app.theme.blue);

    // Selection range in display columns
    let sel_col_range = app.edit_selection_range().and_then(|(sb, se)| {
        if sb == se {
            return None;
        }
        let sc = unicode::byte_offset_to_display_col(buf, sb);
        let ec = unicode::byte_offset_to_display_col(buf, se);
        Some((sc, ec))
    });

    // Iterate graphemes, tracking display column
    let mut col = 0;
    for grapheme in buf.graphemes(true) {
        let gw = unicode::display_width(grapheme);
        let next_col = col + gw;

        // Skip graphemes before visible window
        if next_col <= h_scroll {
            col = next_col;
            continue;
        }
        // Stop if past visible window
        if col >= h_scroll + effective_available {
            break;
        }

        let is_cursor = col == cursor_col;
        let in_selection =
            sel_col_range.is_some_and(|(sel_start, sel_end)| col >= sel_start && col < sel_end);

        let s = if is_cursor && sel_col_range.is_none() {
            cursor_style
        } else if in_selection {
            selection_style
        } else {
            style
        };
        spans.push(Span::styled(grapheme.to_string(), s));
        col = next_col;
    }

    // Cursor block at end if cursor is at/past end of content
    if cursor_col >= total_display
        && cursor_col >= h_scroll
        && cursor_col < h_scroll + effective_available + 1
    {
        spans.push(Span::styled(" ", cursor_style));
    }

    if clipped_right {
        spans.push(Span::styled("\u{25B8}", dim_arrow_style));
    }

    (available as u16, h_scroll)
}

/// Render subtask tree for the detail view.
/// Returns the line index of the selected subtask (if any).
#[allow(clippy::too_many_arguments)]
fn render_subtask_tree(
    lines: &mut Vec<Line<'static>>,
    app: &App,
    tasks: &[Task],
    depth: usize,
    width: usize,
    bg: ratatui::style::Color,
    selected_subtask_id: Option<&str>,
    search_re: Option<&Regex>,
    highlight_style: Style,
) -> Option<usize> {
    let selection_bg = app.theme.selection_bg;
    let mut selected_line: Option<usize> = None;

    for (i, task) in tasks.iter().enumerate() {
        let is_last = i == tasks.len() - 1;
        let state_color = app.theme.state_color(task.state);

        let is_selected =
            selected_subtask_id.is_some() && task.id.as_deref() == selected_subtask_id;
        let is_subtask_flashing = task.id.as_deref().is_some_and(|id| app.is_flashing(id));

        let (flash_bg, flash_border) = if is_subtask_flashing {
            match app.flash_state {
                Some(state) => state_flash_colors(state, &app.theme),
                None => UNDO_FLASH_COLORS,
            }
        } else {
            (bg, bg) // unused, but avoids Option
        };

        let row_bg = if is_subtask_flashing {
            flash_bg
        } else if is_selected {
            selection_bg
        } else {
            bg
        };
        let row_dim_style = Style::default().fg(app.theme.dim).bg(row_bg);

        let mut spans: Vec<Span> = Vec::new();

        // Selection indicator (â–Ž) or space
        if is_subtask_flashing {
            spans.push(Span::styled(
                "\u{258E}",
                Style::default().fg(flash_border).bg(row_bg),
            ));
        } else if is_selected {
            spans.push(Span::styled(
                "\u{258E}",
                Style::default().fg(app.theme.selection_border).bg(row_bg),
            ));
        } else {
            spans.push(Span::styled(" ", Style::default().bg(row_bg)));
        }

        // Indent
        for _ in 0..depth {
            spans.push(Span::styled("  ", row_dim_style));
        }

        // Tree char
        let tree_char = if is_last { "\u{2514}" } else { "\u{251C}" };
        spans.push(Span::styled(tree_char, row_dim_style));
        spans.push(Span::styled(" ", row_dim_style));

        // State symbol
        let state_style = if is_selected {
            Style::default()
                .fg(state_color)
                .bg(row_bg)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(state_color).bg(row_bg)
        };
        spans.push(Span::styled(state_symbol(task.state), state_style));
        spans.push(Span::styled(" ", Style::default().bg(row_bg)));

        // Abbreviated ID
        if let Some(ref id) = task.id {
            let abbrev = abbreviated_id(id);
            let id_style = if is_selected {
                Style::default().fg(app.theme.selection_id).bg(row_bg)
            } else {
                Style::default().fg(app.theme.text).bg(row_bg)
            };
            push_highlighted_spans(
                &mut spans,
                &format!("{} ", abbrev),
                id_style,
                highlight_style,
                search_re,
            );
        }

        // Title
        let title_style = if task.state == TaskState::Done {
            Style::default().fg(app.theme.dim).bg(row_bg)
        } else if is_selected {
            Style::default()
                .fg(app.theme.text_bright)
                .bg(row_bg)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(app.theme.text_bright).bg(row_bg)
        };
        push_highlighted_spans(
            &mut spans,
            &task.title,
            title_style,
            highlight_style,
            search_re,
        );

        // Tags
        if !task.tags.is_empty() {
            spans.push(Span::styled("  ", Style::default().bg(row_bg)));
            for (j, tag) in task.tags.iter().enumerate() {
                let tag_color = app.theme.tag_color(tag);
                let tag_style = if task.state == TaskState::Done {
                    Style::default().fg(app.theme.dim).bg(row_bg)
                } else {
                    Style::default().fg(tag_color).bg(row_bg)
                };
                if j > 0 {
                    spans.push(Span::styled(" ", Style::default().bg(row_bg)));
                }
                push_highlighted_spans(
                    &mut spans,
                    &format!("#{}", tag),
                    tag_style,
                    highlight_style,
                    search_re,
                );
            }
        }

        // Pad to full width
        let content_width: usize = spans
            .iter()
            .map(|s| unicode::display_width(&s.content))
            .sum();
        if content_width < width {
            spans.push(Span::styled(
                " ".repeat(width - content_width),
                Style::default().bg(row_bg),
            ));
        }

        if is_selected {
            selected_line = Some(lines.len());
        }

        lines.push(Line::from(spans));

        // Recurse into sub-subtasks
        if !task.subtasks.is_empty() {
            let child_result = render_subtask_tree(
                lines,
                app,
                &task.subtasks,
                depth + 1,
                width,
                bg,
                selected_subtask_id,
                search_re,
                highlight_style,
            );
            if selected_line.is_none() {
                selected_line = child_result;
            }
        }
    }

    selected_line
}

/// Region indicator: a small accent mark on the left for the active region
fn region_indicator(
    is_active: bool,
    active_style: Style,
    bg: ratatui::style::Color,
) -> Span<'static> {
    if is_active {
        Span::styled(" \u{258E} ", active_style)
    } else {
        Span::styled("   ", Style::default().bg(bg))
    }
}

/// Undo flash colors: bright orange bg + orange border (distinct from parked yellow)
pub const UNDO_FLASH_COLORS: (ratatui::style::Color, ratatui::style::Color) = (
    ratatui::style::Color::Rgb(0x50, 0x30, 0x10), // dark orange bg
    ratatui::style::Color::Rgb(0xFF, 0xA0, 0x30), // orange border
);

/// Apply flash highlight to a range of lines (modifies bg and border indicator).
fn apply_flash_to_lines(
    lines: &mut [Line<'static>],
    start_idx: usize,
    end_idx: usize,
    flash_bg: ratatui::style::Color,
    flash_border: ratatui::style::Color,
    width: usize,
) {
    for line_idx in start_idx..=end_idx {
        if let Some(line) = lines.get_mut(line_idx) {
            let mut new_spans: Vec<Span<'static>> = Vec::new();
            for (i, span) in line.spans.drain(..).enumerate() {
                if i == 0 && line_idx == start_idx && span.content.contains('\u{258E}') {
                    new_spans.push(Span::styled(
                        span.content.into_owned(),
                        Style::default().fg(flash_border).bg(flash_bg),
                    ));
                } else {
                    new_spans.push(Span::styled(
                        span.content.into_owned(),
                        span.style.bg(flash_bg),
                    ));
                }
            }
            let content_width: usize = new_spans
                .iter()
                .map(|s| unicode::display_width(&s.content))
                .sum();
            if content_width < width {
                new_spans.push(Span::styled(
                    " ".repeat(width - content_width),
                    Style::default().bg(flash_bg),
                ));
            }
            *line = Line::from(new_spans);
        }
    }
}

/// Get state-specific flash colors (background, border) for a task state.
pub fn state_flash_colors(
    state: TaskState,
    theme: &Theme,
) -> (ratatui::style::Color, ratatui::style::Color) {
    use ratatui::style::Color;
    match state {
        TaskState::Active => (Color::Rgb(0x5A, 0x1A, 0x48), theme.highlight), // pink bg, pink border
        TaskState::Blocked => (Color::Rgb(0x55, 0x1A, 0x1A), theme.red),      // red bg, red border
        TaskState::Parked => (Color::Rgb(0x4A, 0x3A, 0x15), theme.yellow), // amber bg, yellow border
        TaskState::Todo => (Color::Rgb(0x3A, 0x1A, 0x58), theme.purple), // purple bg, purple border
        TaskState::Done => (Color::Rgb(0x1A, 0x2A, 0x55), theme.blue),   // blue bg, blue border
    }
}

/// Find the state of a task by ID across all tracks
fn find_task_state_across_tracks(app: &App, task_id: &str) -> Option<TaskState> {
    for (_, track) in &app.project.tracks {
        if let Some(task) = task_ops::find_task_in_track(track, task_id) {
            return Some(task.state);
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tui::render::test_helpers::*;
    use insta::assert_snapshot;

    #[test]
    fn basic_task_detail() {
        let md = "\
# Test

## Backlog

- [ ] `T-1` First task #core
  - added: 2025-05-10
  - dep: T-2
  - note: Some notes about this task.

## Done
";
        let mut app = app_in_detail_view(md, "T-1");
        let output = render_to_string(TERM_W, TERM_H, |frame, area| {
            render_detail_view(frame, &mut app, area);
        });
        assert_snapshot!(output);
    }

    #[test]
    fn minimal_task_detail() {
        let md = "\
# Test

## Backlog

- [ ] `T-1` Simple task

## Done
";
        let mut app = app_in_detail_view(md, "T-1");
        let output = render_to_string(TERM_W, TERM_H, |frame, area| {
            render_detail_view(frame, &mut app, area);
        });
        assert_snapshot!(output);
    }

    #[test]
    fn task_with_subtasks() {
        let md = "\
# Test

## Backlog

- [ ] `T-1` Parent task #core
  - [ ] `T-1.1` Child one
  - [>] `T-1.2` Child two

## Done
";
        let mut app = app_in_detail_view(md, "T-1");
        let output = render_to_string(TERM_W, TERM_H, |frame, area| {
            render_detail_view(frame, &mut app, area);
        });
        assert_snapshot!(output);
    }

    #[test]
    fn task_not_found() {
        let md = "# Test\n\n## Backlog\n\n## Done\n";
        let mut app = app_in_detail_view(md, "NONEXISTENT");
        let output = render_to_string(TERM_W, TERM_H, |frame, area| {
            render_detail_view(frame, &mut app, area);
        });
        assert_snapshot!(output);
    }
}