roam-sdk 0.3.0

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

use crate::api::types::{Block, DailyNote};
use crate::app::LinkedRefsState;
use crate::edit_buffer::EditBuffer;
use crate::highlight::CodeHighlighter;
use crate::markdown;

pub struct MainArea<'a> {
    pub days: &'a [DailyNote],
    pub selected_block: usize,
    pub cursor_col: usize,
    pub loading: bool,
    pub loading_more: bool,
    pub edit_info: Option<EditInfo<'a>>,
    pub block_ref_cache: &'a std::collections::HashMap<String, String>,
    pub linked_refs: &'a std::collections::HashMap<String, LinkedRefsState>,
}

pub struct EditInfo<'a> {
    pub buffer: &'a EditBuffer,
    pub block_index: usize,
}

#[derive(Debug, Clone)]
enum VisibleLine {
    DayHeading(String),
    DaySeparator,
    Block {
        depth: usize,
        text: String,
        block_index: usize,
        collapsed_children: usize,
    },
    CodeLabel {
        depth: usize,
        spans: Vec<Span<'static>>,
        block_index: usize,
    },
    CodeLine {
        depth: usize,
        spans: Vec<Span<'static>>,
        block_index: usize,
        line_number: usize,
    },
    Blockquote {
        depth: usize,
        text: String,
        block_index: usize,
    },
    LoadingMore,
    LinkedRefsSeparator,
    LinkedRefsHeader {
        count: usize,
        collapsed: bool,
        block_index: usize,
    },
    LinkedRefsGroupHeader {
        page_title: String,
        block_index: usize,
    },
    LinkedRefsBlock {
        text: String,
        block_index: usize,
    },
}

/// Check if a block's text represents a code block (starts with ```)
fn is_code_block(text: &str) -> bool {
    text.starts_with("```")
}

/// Check if a block's text represents a blockquote (starts with `> `)
fn is_blockquote(text: &str) -> bool {
    text.starts_with("> ")
}

/// Markdown lang code blocks should be rendered with inline formatting, not as code
fn is_markdown_lang(lang: &str) -> bool {
    matches!(lang, "md" | "markdown" | "")
}

/// Parse a code block string into (language, code_lines).
/// Roam stores code blocks as: ```\nlang\ncode...```
fn parse_code_block(text: &str) -> (&str, &str) {
    let content = text.strip_prefix("```").unwrap_or(text);
    let content = content.strip_suffix("```").unwrap_or(content);
    let content = content.strip_prefix('\n').unwrap_or(content);

    // First line is the language
    if let Some(newline_pos) = content.find('\n') {
        let lang = content[..newline_pos].trim();
        let code = &content[newline_pos + 1..];
        (lang, code)
    } else {
        // No newline — just a language tag with no code
        (content.trim(), "")
    }
}

fn build_visible_lines(
    days: &[DailyNote],
    loading_more: bool,
    highlighter: &mut CodeHighlighter,
    linked_refs: &std::collections::HashMap<String, LinkedRefsState>,
) -> Vec<VisibleLine> {
    let mut lines = Vec::new();
    let mut block_index = 0;

    for (i, day) in days.iter().enumerate() {
        if i > 0 {
            lines.push(VisibleLine::DaySeparator);
        }
        lines.push(VisibleLine::DayHeading(day.title.clone()));
        flatten_blocks(&day.blocks, 0, &mut lines, &mut block_index, highlighter);

        // Append linked references for this day
        if let Some(lr) = linked_refs.get(&day.title) {
            append_linked_refs(lr, &mut lines, &mut block_index);
        }
    }

    if loading_more {
        lines.push(VisibleLine::DaySeparator);
        lines.push(VisibleLine::LoadingMore);
    }

    lines
}

fn append_linked_refs(lr: &LinkedRefsState, lines: &mut Vec<VisibleLine>, block_index: &mut usize) {
    if lr.loading {
        lines.push(VisibleLine::LinkedRefsSeparator);
        lines.push(VisibleLine::LinkedRefsHeader {
            count: 0,
            collapsed: false,
            block_index: *block_index,
        });
    } else if !lr.groups.is_empty() {
        let total_count: usize = lr.groups.iter().map(|g| g.blocks.len()).sum();
        lines.push(VisibleLine::LinkedRefsSeparator);
        lines.push(VisibleLine::LinkedRefsHeader {
            count: total_count,
            collapsed: lr.collapsed,
            block_index: *block_index,
        });
        *block_index += 1;

        if !lr.collapsed {
            for group in &lr.groups {
                lines.push(VisibleLine::LinkedRefsGroupHeader {
                    page_title: group.page_title.clone(),
                    block_index: *block_index,
                });
                *block_index += 1;

                for block in &group.blocks {
                    lines.push(VisibleLine::LinkedRefsBlock {
                        text: block.string.clone(),
                        block_index: *block_index,
                    });
                    *block_index += 1;
                }
            }
        }
    }
}

fn flatten_blocks(
    blocks: &[Block],
    depth: usize,
    lines: &mut Vec<VisibleLine>,
    block_index: &mut usize,
    highlighter: &mut CodeHighlighter,
) {
    for block in blocks {
        if is_code_block(&block.string) {
            let (lang, code) = parse_code_block(&block.string);
            let bi = *block_index;

            let base_style = Style::default().fg(Color::White).bg(Color::DarkGray);

            // Language label line
            if !lang.is_empty() {
                lines.push(VisibleLine::CodeLabel {
                    depth,
                    spans: vec![Span::styled(
                        format!(" {} ", lang),
                        Style::default().fg(Color::DarkGray),
                    )],
                    block_index: bi,
                });
            }

            // Code lines
            if !code.is_empty() {
                let code_lines: Vec<Vec<Span<'static>>> = if is_markdown_lang(lang) {
                    code.lines()
                        .map(|line_text| markdown::render_spans(line_text, base_style))
                        .collect()
                } else {
                    highlighter.highlight_code(lang, code, base_style)
                };

                for (idx, spans) in code_lines.into_iter().enumerate() {
                    lines.push(VisibleLine::CodeLine {
                        depth,
                        spans,
                        block_index: bi,
                        line_number: idx + 1,
                    });
                }
            }
        } else if is_blockquote(&block.string) {
            lines.push(VisibleLine::Blockquote {
                depth,
                text: block.string[2..].to_string(),
                block_index: *block_index,
            });
        } else {
            let collapsed_children = if !block.open && !block.children.is_empty() {
                block.children.len()
            } else {
                0
            };
            lines.push(VisibleLine::Block {
                depth,
                text: block.string.clone(),
                block_index: *block_index,
                collapsed_children,
            });
        }

        *block_index += 1;
        if block.open {
            flatten_blocks(&block.children, depth + 1, lines, block_index, highlighter);
        }
    }
}

/// Inject a block cursor (inverted color) at the given character position within spans.
fn inject_cursor(spans: Vec<Span<'static>>, cursor_pos: usize) -> Vec<Span<'static>> {
    let cursor_style = Style::default().fg(Color::Black).bg(Color::White);
    let chars: Vec<(char, Style)> = spans
        .iter()
        .flat_map(|s| s.content.chars().map(move |c| (c, s.style)))
        .collect();

    if chars.is_empty() {
        return vec![Span::styled(" ", cursor_style)];
    }

    let pos = cursor_pos.min(chars.len().saturating_sub(1));
    let mut modified = chars;
    modified[pos].1 = cursor_style;
    chars_to_spans(&modified)
}

fn render_centered_message(msg: &str, area: Rect, buf: &mut Buffer) {
    if area.height > 0 {
        let line = Line::styled(msg, Style::default().fg(Color::DarkGray));
        let y = area.y + area.height / 2;
        let render_area = Rect::new(area.x, y, area.width, 1);
        line.render(render_area, buf);
    }
}

/// Reconstruct `Vec<Span<'static>>` from a slice of (char, Style) pairs,
/// merging consecutive chars that share the same style into a single Span.
fn chars_to_spans(chars: &[(char, Style)]) -> Vec<Span<'static>> {
    if chars.is_empty() {
        return vec![];
    }
    let mut spans = Vec::new();
    let mut current_text = String::new();
    let mut current_style = chars[0].1;

    for &(ch, style) in chars {
        if style == current_style {
            current_text.push(ch);
        } else {
            spans.push(Span::styled(current_text.clone(), current_style));
            current_text.clear();
            current_text.push(ch);
            current_style = style;
        }
    }
    if !current_text.is_empty() {
        spans.push(Span::styled(current_text, current_style));
    }
    spans
}

/// Word-wrap a sequence of styled spans into multiple lines.
///
/// - `first_width`: max chars available on the first line (after prefix like "  • ")
/// - `cont_width`: max chars available on continuation lines (after prefix like "    ")
///
/// Breaks at word boundaries (spaces) when possible, hard-wraps otherwise.
/// Returns `Vec<Vec<Span>>` where each inner Vec is one visual line.
fn wrap_spans(
    spans: Vec<Span<'static>>,
    first_width: usize,
    cont_width: usize,
) -> Vec<Vec<Span<'static>>> {
    let first_width = first_width.max(1);
    let cont_width = cont_width.max(1);

    // Flatten spans into (char, style) pairs
    let chars: Vec<(char, Style)> = spans
        .iter()
        .flat_map(|s| s.content.chars().map(move |c| (c, s.style)))
        .collect();

    let total_chars = chars.len();

    // Fast path: fits on first line
    if total_chars <= first_width {
        return vec![spans];
    }

    let mut result = Vec::new();
    let mut pos = 0;
    let mut is_first = true;

    while pos < total_chars {
        let width = if is_first { first_width } else { cont_width };
        let remaining = total_chars - pos;

        if remaining <= width {
            result.push(chars_to_spans(&chars[pos..]));
            break;
        }

        // Find break point: last space within [pos, pos+width)
        let end = pos + width;
        let break_at = chars[pos..end]
            .iter()
            .rposition(|&(c, _)| c == ' ')
            .map(|offset| pos + offset + 1) // break after space
            .unwrap_or(end); // hard break if no space

        result.push(chars_to_spans(&chars[pos..break_at]));
        pos = break_at;
        is_first = false;
    }

    result
}

impl<'a> Widget for MainArea<'a> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        if self.loading {
            render_centered_message(" Loading today's notes...", area, buf);
            return;
        }

        if self.days.is_empty() {
            render_centered_message(" No notes for today", area, buf);
            return;
        }

        let mut highlighter = CodeHighlighter::new();
        let mut block_map = markdown::build_block_text_map(self.days);
        block_map.extend(
            self.block_ref_cache
                .iter()
                .map(|(k, v)| (k.clone(), v.clone())),
        );
        let visible_lines = build_visible_lines(
            self.days,
            self.loading_more,
            &mut highlighter,
            self.linked_refs,
        );
        let max_width = area.width as usize;

        // Phase 1: Build all visual rows (blocks may expand to multiple rows)
        let mut rows: Vec<Line<'static>> = Vec::new();
        let mut selected_row: usize = 0;
        let mut found_selected = false;

        for vline in &visible_lines {
            match vline {
                VisibleLine::DayHeading(title) => {
                    let text = format!("  {}", title);
                    let style = Style::default()
                        .fg(Color::White)
                        .add_modifier(Modifier::BOLD);
                    let truncated = truncate(&text, max_width);
                    rows.push(Line::styled(truncated, style));
                }
                VisibleLine::DaySeparator => {
                    let sep = "─".repeat(max_width);
                    rows.push(Line::styled(
                        sep,
                        Style::default()
                            .fg(Color::DarkGray)
                            .add_modifier(Modifier::DIM),
                    ));
                }
                VisibleLine::Block {
                    depth,
                    text,
                    block_index,
                    collapsed_children,
                } => {
                    let indent = "  ".repeat(depth + 1);
                    let is_selected = *block_index == self.selected_block;

                    if !found_selected && is_selected {
                        selected_row = rows.len();
                        found_selected = true;
                    }

                    let is_editing = is_selected
                        && self
                            .edit_info
                            .as_ref()
                            .is_some_and(|e| e.block_index == *block_index);

                    if is_editing {
                        let edit = self.edit_info.as_ref().unwrap();
                        let style = Style::default().fg(Color::White).bg(Color::DarkGray);
                        let prefix = format!("{}• ", indent);
                        let cont_prefix = format!("{}  ", indent);
                        let buf_text = edit.buffer.to_string();
                        let cursor_pos = edit.buffer.cursor;

                        // Map flat cursor position to (line, col)
                        let text_lines: Vec<&str> = buf_text.split('\n').collect();
                        let mut line_start = 0;
                        let mut cursor_line = text_lines.len().saturating_sub(1);
                        let mut cursor_col = 0;

                        for (i, tl) in text_lines.iter().enumerate() {
                            let line_end = line_start + tl.chars().count();
                            if cursor_pos <= line_end {
                                cursor_line = i;
                                cursor_col = cursor_pos - line_start;
                                break;
                            }
                            line_start = line_end + 1; // skip \n
                        }

                        let edit_start_row = rows.len();
                        for (line_idx, text_line) in text_lines.iter().enumerate() {
                            let lp = if line_idx == 0 {
                                prefix.clone()
                            } else {
                                cont_prefix.clone()
                            };
                            let mut spans = vec![Span::styled(lp, style)];

                            if line_idx == cursor_line {
                                let line_chars: Vec<char> = text_line.chars().collect();
                                let before: String = line_chars[..cursor_col].iter().collect();
                                let cursor_char =
                                    line_chars.get(cursor_col).copied().unwrap_or(' ');
                                let after: String = if cursor_col < line_chars.len() {
                                    line_chars[cursor_col + 1..].iter().collect()
                                } else {
                                    String::new()
                                };

                                spans.push(Span::styled(before, style));
                                spans.push(Span::styled(
                                    cursor_char.to_string(),
                                    Style::default().fg(Color::Black).bg(Color::White),
                                ));
                                if !after.is_empty() {
                                    spans.push(Span::styled(after, style));
                                }
                            } else {
                                spans.push(Span::styled(text_line.to_string(), style));
                            }

                            rows.push(Line::from(spans));
                        }
                        // Scroll to the cursor row, not the first row of the block
                        selected_row = edit_start_row + cursor_line;
                    } else {
                        let mut style = if is_selected {
                            Style::default().fg(Color::White).bg(Color::DarkGray)
                        } else {
                            Style::default().fg(Color::Gray)
                        };

                        // Dim for deep nesting
                        if !is_selected && *depth >= 3 {
                            style = style.add_modifier(Modifier::DIM);
                        }

                        let bullet = if *collapsed_children > 0 {
                            "â–¸"
                        } else {
                            "•"
                        };
                        let bullet_style = if *collapsed_children > 0 {
                            Style::default().fg(Color::Cyan).bg(if is_selected {
                                Color::DarkGray
                            } else {
                                Color::Reset
                            })
                        } else {
                            style
                        };

                        // Selection indicator: replace first 2 chars of indent with "â–Ž "
                        let selection_indicator = if is_selected && indent.len() >= 2 {
                            Some(Span::styled(
                                "â–Ž",
                                Style::default().fg(Color::Cyan).bg(Color::DarkGray),
                            ))
                        } else {
                            None
                        };

                        let prefix_indent = if selection_indicator.is_some() {
                            " ".repeat(indent.chars().count().saturating_sub(1))
                        } else {
                            indent.clone()
                        };

                        let cont_prefix = format!("{}  ", indent);
                        let prefix_width = indent.chars().count() + 2; // bullet + space
                        let cont_prefix_width = cont_prefix.chars().count();

                        let first_w = max_width.saturating_sub(prefix_width);
                        let cont_w = max_width.saturating_sub(cont_prefix_width);
                        let mut is_first_row = true;

                        let mut rendered_char_offset = 0;
                        for text_line in text.split('\n') {
                            let mut line_spans = markdown::render_spans_with_refs(
                                text_line,
                                style,
                                Some(&block_map),
                            );

                            // Inject cursor in normal mode for selected block
                            if is_selected && self.edit_info.is_none() {
                                let line_rendered_len: usize =
                                    line_spans.iter().map(|s| s.content.chars().count()).sum();
                                if self.cursor_col >= rendered_char_offset
                                    && self.cursor_col - rendered_char_offset <= line_rendered_len
                                {
                                    let cursor_in_line = self.cursor_col - rendered_char_offset;
                                    line_spans = inject_cursor(line_spans, cursor_in_line);
                                }
                                rendered_char_offset += line_rendered_len + 1;
                            }

                            let w = if is_first_row { first_w } else { cont_w };
                            let wrapped = wrap_spans(line_spans, w, cont_w);
                            for (wrap_idx, wline) in wrapped.into_iter().enumerate() {
                                let mut full_spans: Vec<Span<'static>> =
                                    if is_first_row && wrap_idx == 0 {
                                        let mut v: Vec<Span<'static>> = Vec::new();
                                        if let Some(ref ind) = selection_indicator {
                                            v.push(ind.clone());
                                        }
                                        v.push(Span::styled(prefix_indent.clone(), style));
                                        v.push(Span::styled(format!("{} ", bullet), bullet_style));
                                        v
                                    } else {
                                        vec![Span::styled(cont_prefix.clone(), style)]
                                    };
                                full_spans.extend(wline);

                                // Append collapsed children count on first row
                                if is_first_row && wrap_idx == 0 && *collapsed_children > 0 {
                                    full_spans.push(Span::styled(
                                        format!(" [{}]", collapsed_children),
                                        Style::default().fg(Color::DarkGray),
                                    ));
                                }

                                rows.push(Line::from(full_spans));
                                is_first_row = false;
                            }
                        }
                    }
                }
                VisibleLine::Blockquote {
                    depth,
                    text,
                    block_index,
                } => {
                    let indent = "  ".repeat(depth + 1);
                    let is_selected = *block_index == self.selected_block;

                    if !found_selected && is_selected {
                        selected_row = rows.len();
                        found_selected = true;
                    }

                    let border_style = if is_selected {
                        Style::default().fg(Color::DarkGray).bg(Color::DarkGray)
                    } else {
                        Style::default().fg(Color::DarkGray)
                    };

                    let text_style = if is_selected {
                        Style::default().fg(Color::White).bg(Color::DarkGray)
                    } else {
                        Style::default().fg(Color::Gray)
                    };

                    let prefix_str = format!("{}│ ", indent);
                    let prefix_width = prefix_str.chars().count();

                    let text_w = max_width.saturating_sub(prefix_width);

                    for text_line in text.split('\n') {
                        let line_spans = markdown::render_spans_with_refs(
                            text_line,
                            text_style,
                            Some(&block_map),
                        );
                        let wrapped = wrap_spans(line_spans, text_w, text_w);
                        for wline in wrapped {
                            let mut full_spans = vec![
                                Span::styled(indent.clone(), text_style),
                                Span::styled("│ ".to_string(), border_style),
                            ];
                            full_spans.extend(wline);
                            rows.push(Line::from(full_spans));
                        }
                    }
                }
                VisibleLine::CodeLabel {
                    depth,
                    spans,
                    block_index,
                }
                | VisibleLine::CodeLine {
                    depth,
                    spans,
                    block_index,
                    ..
                } => {
                    let indent = "  ".repeat(depth + 1);
                    let is_selected = *block_index == self.selected_block;

                    if !found_selected
                        && is_selected
                        && matches!(vline, VisibleLine::CodeLabel { .. })
                    {
                        selected_row = rows.len();
                        found_selected = true;
                    }

                    let indent_style = if is_selected {
                        Style::default().bg(Color::DarkGray)
                    } else {
                        Style::default()
                    };

                    let mut line_spans = vec![Span::styled(format!("{}  ", indent), indent_style)];

                    if let VisibleLine::CodeLine { line_number, .. } = vline {
                        let gutter_style = Style::default().fg(Color::Gray).bg(Color::DarkGray);
                        line_spans.push(Span::styled(format!("{:>3} ", line_number), gutter_style));
                    }

                    line_spans.extend(spans.iter().cloned());

                    // Pad background to full width
                    let used: usize = line_spans.iter().map(|s| s.content.chars().count()).sum();
                    let remaining = max_width.saturating_sub(used);
                    if remaining > 0 {
                        line_spans.push(Span::styled(
                            " ".repeat(remaining),
                            Style::default().bg(Color::DarkGray),
                        ));
                    }

                    rows.push(Line::from(line_spans));
                }
                VisibleLine::LoadingMore => {
                    rows.push(Line::styled(
                        "  Loading more...".to_string(),
                        Style::default().fg(Color::DarkGray),
                    ));
                }
                VisibleLine::LinkedRefsSeparator => {
                    let sep = "─".repeat(max_width);
                    rows.push(Line::styled(
                        sep,
                        Style::default()
                            .fg(Color::DarkGray)
                            .add_modifier(Modifier::DIM),
                    ));
                }
                VisibleLine::LinkedRefsHeader {
                    count,
                    collapsed,
                    block_index,
                } => {
                    let is_selected = *block_index == self.selected_block;
                    if !found_selected && is_selected {
                        selected_row = rows.len();
                        found_selected = true;
                    }
                    let arrow = if *collapsed { "â–¸" } else { "â–¾" };
                    let label = if *count == 0 {
                        format!("  {} Linked References (loading...)", arrow)
                    } else {
                        format!("  {} Linked References ({})", arrow, count)
                    };
                    let style = if is_selected {
                        Style::default()
                            .fg(Color::Cyan)
                            .bg(Color::DarkGray)
                            .add_modifier(Modifier::BOLD)
                    } else {
                        Style::default()
                            .fg(Color::Cyan)
                            .add_modifier(Modifier::BOLD)
                    };
                    rows.push(Line::styled(truncate(&label, max_width), style));
                }
                VisibleLine::LinkedRefsGroupHeader {
                    page_title,
                    block_index,
                } => {
                    let is_selected = *block_index == self.selected_block;
                    if !found_selected && is_selected {
                        selected_row = rows.len();
                        found_selected = true;
                    }
                    let style = if is_selected {
                        Style::default().fg(Color::Yellow).bg(Color::DarkGray)
                    } else {
                        Style::default().fg(Color::Yellow)
                    };
                    let label = format!("    {}", page_title);
                    rows.push(Line::styled(truncate(&label, max_width), style));
                }
                VisibleLine::LinkedRefsBlock {
                    text, block_index, ..
                } => {
                    let is_selected = *block_index == self.selected_block;
                    if !found_selected && is_selected {
                        selected_row = rows.len();
                        found_selected = true;
                    }
                    let style = if is_selected {
                        Style::default().fg(Color::White).bg(Color::DarkGray)
                    } else {
                        Style::default().fg(Color::DarkGray)
                    };
                    let prefix = "      • ";
                    let prefix_width = prefix.chars().count();
                    let text_w = max_width.saturating_sub(prefix_width);
                    let line_spans =
                        markdown::render_spans_with_refs(text, style, Some(&block_map));
                    let wrapped = wrap_spans(line_spans, text_w, text_w);
                    for (i, wline) in wrapped.into_iter().enumerate() {
                        let pfx = if i == 0 {
                            prefix.to_string()
                        } else {
                            " ".repeat(prefix_width)
                        };
                        let mut full_spans = vec![Span::styled(pfx, style)];
                        full_spans.extend(wline);
                        rows.push(Line::from(full_spans));
                    }
                }
            }
        }

        // Phase 2: Scroll (half-page centering on selected row)
        let viewport_height = area.height as usize;
        let half = viewport_height / 2;
        let scroll_offset = if selected_row > half {
            (selected_row - half).min(rows.len().saturating_sub(viewport_height))
        } else {
            0
        };

        // Phase 3: Render rows to terminal
        for (i, row) in rows.into_iter().skip(scroll_offset).enumerate() {
            if i >= viewport_height {
                break;
            }
            let y = area.y + i as u16;
            let render_area = Rect::new(area.x, y, area.width, 1);
            row.render(render_area, buf);
        }
    }
}

fn truncate(s: &str, max_len: usize) -> String {
    s.chars().take(max_len).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::NaiveDate;
    use std::collections::HashMap;

    fn read_line(buf: &Buffer, y: u16, width: u16) -> String {
        (0..width)
            .map(|x| {
                buf.cell((x, y))
                    .unwrap()
                    .symbol()
                    .chars()
                    .next()
                    .unwrap_or(' ')
            })
            .collect()
    }

    fn make_block(uid: &str, text: &str, order: i64) -> Block {
        Block {
            uid: uid.into(),
            string: text.into(),
            order,
            children: vec![],
            open: true,
            refs: vec![],
        }
    }

    fn make_daily_note(
        title: &str,
        year: i32,
        month: u32,
        day: u32,
        blocks: Vec<Block>,
    ) -> DailyNote {
        DailyNote {
            date: NaiveDate::from_ymd_opt(year, month, day).unwrap(),
            uid: format!("{:02}-{:02}-{}", month, day, year),
            title: title.into(),
            blocks,
        }
    }

    #[test]
    fn build_visible_lines_single_day() {
        let day = make_daily_note(
            "February 21, 2026",
            2026,
            2,
            21,
            vec![make_block("b1", "Hello", 0), make_block("b2", "World", 1)],
        );
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day], false, &mut hl, &HashMap::new());

        assert_eq!(lines.len(), 3); // heading + 2 blocks
        assert!(matches!(&lines[0], VisibleLine::DayHeading(t) if t == "February 21, 2026"));
        assert!(
            matches!(&lines[1], VisibleLine::Block { block_index: 0, text, .. } if text == "Hello")
        );
        assert!(
            matches!(&lines[2], VisibleLine::Block { block_index: 1, text, .. } if text == "World")
        );
    }

    #[test]
    fn build_visible_lines_nested_blocks() {
        let parent = Block {
            uid: "p".into(),
            string: "Parent".into(),
            order: 0,
            children: vec![make_block("c1", "Child", 0)],
            open: true,
            refs: vec![],
        };
        let day = make_daily_note("Feb 21", 2026, 2, 21, vec![parent]);
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day], false, &mut hl, &HashMap::new());

        assert_eq!(lines.len(), 3); // heading + parent + child
        assert!(matches!(
            &lines[1],
            VisibleLine::Block {
                depth: 0,
                block_index: 0,
                ..
            }
        ));
        assert!(matches!(
            &lines[2],
            VisibleLine::Block {
                depth: 1,
                block_index: 1,
                ..
            }
        ));
    }

    #[test]
    fn build_visible_lines_two_days_has_separator() {
        let day1 = make_daily_note("Day 1", 2026, 2, 21, vec![make_block("a", "A", 0)]);
        let day2 = make_daily_note("Day 2", 2026, 2, 20, vec![make_block("b", "B", 0)]);
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day1, day2], false, &mut hl, &HashMap::new());

        assert_eq!(lines.len(), 5);
        assert!(matches!(&lines[2], VisibleLine::DaySeparator));
        assert!(matches!(&lines[3], VisibleLine::DayHeading(t) if t == "Day 2"));
    }

    #[test]
    fn build_visible_lines_loading_more() {
        let day = make_daily_note("Day 1", 2026, 2, 21, vec![make_block("a", "A", 0)]);
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day], true, &mut hl, &HashMap::new());

        let last = lines.last().unwrap();
        assert!(matches!(last, VisibleLine::LoadingMore));
    }

    #[test]
    fn renders_loading_state() {
        let area = Rect::new(0, 0, 40, 5);
        let mut buf = Buffer::empty(area);

        let widget = MainArea {
            days: &[],
            selected_block: 0,
            cursor_col: 0,
            loading: true,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        let found = (0..area.height).any(|y| read_line(&buf, y, area.width).contains("Loading"));
        assert!(found);
    }

    #[test]
    fn renders_empty_state() {
        let area = Rect::new(0, 0, 40, 5);
        let mut buf = Buffer::empty(area);

        let widget = MainArea {
            days: &[],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        let found = (0..area.height).any(|y| read_line(&buf, y, area.width).contains("No notes"));
        assert!(found);
    }

    #[test]
    fn renders_day_heading_and_blocks() {
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);

        let day = make_daily_note(
            "February 21, 2026",
            2026,
            2,
            21,
            vec![
                make_block("b1", "Block one", 0),
                make_block("b2", "Block two", 1),
            ],
        );

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        assert!(read_line(&buf, 0, area.width).contains("February 21, 2026"));
        assert!(read_line(&buf, 1, area.width).contains("Block one"));
    }

    #[test]
    fn renders_selected_block_with_bullet() {
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);

        let day = make_daily_note(
            "Feb 21",
            2026,
            2,
            21,
            vec![make_block("b1", "First", 0), make_block("b2", "Second", 1)],
        );

        let widget = MainArea {
            days: &[day],
            selected_block: 1,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        assert!(read_line(&buf, 2, area.width).contains("Second"));
    }

    #[test]
    fn renders_nested_block_with_indentation() {
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);

        let parent = Block {
            uid: "p".into(),
            string: "Parent".into(),
            order: 0,
            children: vec![make_block("c1", "Child", 0)],
            open: true,
            refs: vec![],
        };
        let day = make_daily_note("Feb 21", 2026, 2, 21, vec![parent]);

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        let line1 = read_line(&buf, 1, area.width);
        let line2 = read_line(&buf, 2, area.width);

        assert!(line1.contains("Parent"));
        assert!(line2.contains("Child"));
        let parent_leading = line1.len() - line1.trim_start().len();
        let child_leading = line2.len() - line2.trim_start().len();
        assert!(child_leading > parent_leading);
    }

    #[test]
    fn code_block_expands_to_multiple_lines() {
        let code_text = "```\nrust\nfn main() {}\nlet x = 1;```";
        let day = make_daily_note(
            "Feb 21",
            2026,
            2,
            21,
            vec![make_block("c1", code_text, 0), make_block("b2", "After", 1)],
        );
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day], false, &mut hl, &HashMap::new());

        // heading + lang label + 2 code lines + "After" block = 5
        let code_line_count = lines
            .iter()
            .filter(|l| matches!(l, VisibleLine::CodeLine { .. }))
            .count();
        assert!(
            code_line_count >= 2,
            "Expected at least 2 code lines, got {}",
            code_line_count
        );

        // "After" block should still be there
        let has_after = lines
            .iter()
            .any(|l| matches!(l, VisibleLine::Block { text, .. } if text == "After"));
        assert!(has_after, "Expected 'After' block in visible lines");
    }

    #[test]
    fn code_lines_have_line_numbers() {
        let code_text = "```\nrust\nfn main() {}\nlet x = 1;```";
        let day = make_daily_note("Feb 21", 2026, 2, 21, vec![make_block("c1", code_text, 0)]);
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day], false, &mut hl, &HashMap::new());

        let code_lines: Vec<_> = lines
            .iter()
            .filter(|l| matches!(l, VisibleLine::CodeLine { .. }))
            .collect();

        assert!(code_lines.len() >= 2);
        if let VisibleLine::CodeLine { line_number, .. } = &code_lines[0] {
            assert_eq!(*line_number, 1);
        }
        if let VisibleLine::CodeLine { line_number, .. } = &code_lines[1] {
            assert_eq!(*line_number, 2);
        }
    }

    #[test]
    fn code_label_is_separate_variant() {
        let code_text = "```\nrust\nfn main() {}```";
        let day = make_daily_note("Feb 21", 2026, 2, 21, vec![make_block("c1", code_text, 0)]);
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day], false, &mut hl, &HashMap::new());

        let label = lines
            .iter()
            .find(|l| matches!(l, VisibleLine::CodeLabel { .. }));
        assert!(
            label.is_some(),
            "Expected a CodeLabel variant for the language label"
        );
    }

    #[test]
    fn code_line_number_rendered_in_buffer() {
        let area = Rect::new(0, 0, 60, 10);
        let mut buf = Buffer::empty(area);

        let code_text = "```\nrust\nfn main() {}\nlet x = 1;```";
        let day = make_daily_note("Feb 21", 2026, 2, 21, vec![make_block("c1", code_text, 0)]);

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        // Line 2 (after heading + label) should contain "1" (line number)
        // Line 3 should contain "2"
        let line2 = read_line(&buf, 2, area.width);
        let line3 = read_line(&buf, 3, area.width);
        assert!(
            line2.contains('1'),
            "Expected line number '1' in '{}'",
            line2
        );
        assert!(line2.contains("fn"), "Expected code content in '{}'", line2);
        assert!(
            line3.contains('2'),
            "Expected line number '2' in '{}'",
            line3
        );
    }

    #[test]
    fn renders_bold_text_with_styling() {
        let area = Rect::new(0, 0, 60, 10);
        let mut buf = Buffer::empty(area);

        let day = make_daily_note(
            "Feb 21",
            2026,
            2,
            21,
            vec![make_block("b1", "**bold text**", 0)],
        );

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        // The rendered line should contain "bold text" (without **)
        let line1 = read_line(&buf, 1, area.width);
        assert!(
            line1.contains("bold text"),
            "Expected 'bold text', got: '{}'",
            line1
        );
        assert!(
            !line1.contains("**"),
            "Should not contain ** delimiters, got: '{}'",
            line1
        );
    }

    #[test]
    fn renders_page_link_without_brackets() {
        let area = Rect::new(0, 0, 60, 10);
        let mut buf = Buffer::empty(area);

        let day = make_daily_note(
            "Feb 21",
            2026,
            2,
            21,
            vec![make_block("b1", "See [[my page]]", 0)],
        );

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        assert!(
            read_line(&buf, 1, area.width).contains("my page"),
            "Expected 'my page'"
        );
    }

    #[test]
    fn blockquote_detected_in_visible_lines() {
        let day = make_daily_note(
            "Feb 21",
            2026,
            2,
            21,
            vec![make_block("b1", "> quoted text", 0)],
        );
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day], false, &mut hl, &HashMap::new());

        assert!(matches!(
            &lines[1],
            VisibleLine::Blockquote { text, block_index: 0, .. } if text == "quoted text"
        ));
    }

    #[test]
    fn blockquote_strips_prefix() {
        let day = make_daily_note(
            "Feb 21",
            2026,
            2,
            21,
            vec![make_block("b1", "> hello world", 0)],
        );
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day], false, &mut hl, &HashMap::new());

        if let VisibleLine::Blockquote { text, .. } = &lines[1] {
            assert!(
                !text.starts_with("> "),
                "Text should not contain '> ' prefix, got: '{}'",
                text
            );
            assert_eq!(text, "hello world");
        } else {
            panic!("Expected Blockquote variant, got: {:?}", &lines[1]);
        }
    }

    #[test]
    fn blockquote_preserves_depth() {
        let parent = Block {
            uid: "p".into(),
            string: "Parent".into(),
            order: 0,
            children: vec![make_block("c1", "> nested quote", 0)],
            open: true,
            refs: vec![],
        };
        let day = make_daily_note("Feb 21", 2026, 2, 21, vec![parent]);
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day], false, &mut hl, &HashMap::new());

        assert!(matches!(
            &lines[2],
            VisibleLine::Blockquote { depth: 1, text, block_index: 1, .. } if text == "nested quote"
        ));
    }

    #[test]
    fn blockquote_renders_with_border() {
        let area = Rect::new(0, 0, 60, 10);
        let mut buf = Buffer::empty(area);

        let day = make_daily_note(
            "Feb 21",
            2026,
            2,
            21,
            vec![make_block("b1", "> quoted text", 0)],
        );

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        let line1 = read_line(&buf, 1, area.width);
        assert!(
            line1.contains('│'),
            "Expected '│' border in blockquote, got: '{}'",
            line1
        );
        assert!(
            line1.contains("quoted text"),
            "Expected 'quoted text', got: '{}'",
            line1
        );
    }

    #[test]
    fn blockquote_with_inline_formatting() {
        let area = Rect::new(0, 0, 60, 10);
        let mut buf = Buffer::empty(area);

        let day = make_daily_note(
            "Feb 21",
            2026,
            2,
            21,
            vec![make_block("b1", "> **bold** and [[link]]", 0)],
        );

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        let line1 = read_line(&buf, 1, area.width);
        assert!(
            line1.contains("bold"),
            "Expected 'bold' in blockquote, got: '{}'",
            line1
        );
        assert!(
            line1.contains("link"),
            "Expected 'link' in blockquote, got: '{}'",
            line1
        );
        assert!(
            !line1.contains("**"),
            "Should not contain ** delimiters, got: '{}'",
            line1
        );
    }

    #[test]
    fn regular_block_not_affected_by_blockquote() {
        let day = make_daily_note(
            "Feb 21",
            2026,
            2,
            21,
            vec![
                make_block("b1", "normal text", 0),
                make_block("b2", "> quoted", 1),
                make_block("b3", "also normal", 2),
            ],
        );
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day], false, &mut hl, &HashMap::new());

        assert!(matches!(&lines[1], VisibleLine::Block { text, .. } if text == "normal text"));
        assert!(matches!(&lines[2], VisibleLine::Blockquote { text, .. } if text == "quoted"));
        assert!(matches!(&lines[3], VisibleLine::Block { text, .. } if text == "also normal"));
    }

    #[test]
    fn renders_todo_as_checkbox() {
        let area = Rect::new(0, 0, 60, 10);
        let mut buf = Buffer::empty(area);

        let day = make_daily_note(
            "Feb 21",
            2026,
            2,
            21,
            vec![make_block("b1", "{{TODO}} buy milk", 0)],
        );

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        assert!(
            read_line(&buf, 1, area.width).contains("buy milk"),
            "Expected 'buy milk'"
        );
    }

    // --- wrap_spans tests ---

    fn collect_line_text(spans: &[Span]) -> String {
        spans.iter().map(|s| s.content.as_ref()).collect()
    }

    #[test]
    fn wrap_spans_short_text_no_wrap() {
        let style = Style::default().fg(Color::White);
        let spans = vec![Span::styled("hello", style)];
        let result = wrap_spans(spans, 20, 20);
        assert_eq!(result.len(), 1);
        assert_eq!(collect_line_text(&result[0]), "hello");
    }

    #[test]
    fn wrap_spans_long_text_wraps_at_word() {
        let style = Style::default().fg(Color::White);
        let spans = vec![Span::styled("hello world foo", style)];
        let result = wrap_spans(spans, 10, 10);
        assert_eq!(result.len(), 2);
        assert_eq!(collect_line_text(&result[0]), "hello ");
        assert_eq!(collect_line_text(&result[1]), "world foo");
    }

    #[test]
    fn wrap_spans_no_space_hard_wraps() {
        let style = Style::default().fg(Color::White);
        let spans = vec![Span::styled("abcdefghijklmno", style)];
        let result = wrap_spans(spans, 10, 10);
        assert_eq!(result.len(), 2);
        assert_eq!(collect_line_text(&result[0]), "abcdefghij");
        assert_eq!(collect_line_text(&result[1]), "klmno");
    }

    #[test]
    fn wrap_spans_preserves_styles() {
        let bold = Style::default().add_modifier(Modifier::BOLD);
        let normal = Style::default();
        let spans = vec![
            Span::styled("aaaa", bold),
            Span::styled(" bbbb cccc", normal),
        ];
        // "aaaa bbbb cccc" = 14 chars, width 10
        // Line 1: "aaaa bbbb " (break at last space within 10 chars)
        // Line 2: "cccc"
        let result = wrap_spans(spans, 10, 10);
        assert_eq!(result.len(), 2);

        // First line has mixed styles
        assert_eq!(result[0].len(), 2);
        assert_eq!(result[0][0].content, "aaaa");
        assert!(result[0][0].style.add_modifier.contains(Modifier::BOLD));
        assert_eq!(result[0][1].content, " bbbb ");
        assert!(!result[0][1].style.add_modifier.contains(Modifier::BOLD));

        // Second line is normal style
        assert_eq!(collect_line_text(&result[1]), "cccc");
    }

    #[test]
    fn wrap_spans_different_first_cont_widths() {
        let style = Style::default();
        let spans = vec![Span::styled("aaa bbb ccc ddd eee", style)];
        // 19 chars, first_width=15, cont_width=8
        let result = wrap_spans(spans, 15, 8);
        assert_eq!(result.len(), 2);
        // First line fits within 15 chars
        let line1 = collect_line_text(&result[0]);
        assert!(
            line1.len() <= 15,
            "Line 1 '{}' exceeds first_width 15",
            line1
        );
        // Second line fits within 8 chars
        let line2 = collect_line_text(&result[1]);
        assert!(line2.len() <= 8, "Line 2 '{}' exceeds cont_width 8", line2);
    }

    #[test]
    fn wrap_spans_empty_returns_single_empty_line() {
        let result = wrap_spans(vec![], 10, 10);
        assert_eq!(result.len(), 1);
        assert!(result[0].is_empty());
    }

    #[test]
    fn multiline_block_respects_newlines() {
        let area = Rect::new(0, 0, 60, 10);
        let mut buf = Buffer::empty(area);

        let text = "First paragraph\n\nSecond paragraph";
        let day = make_daily_note("Feb 21", 2026, 2, 21, vec![make_block("b1", text, 0)]);

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        // Row 0: heading
        // Row 1: "  • First paragraph"
        // Row 2: "    " (empty line from \n\n)
        // Row 3: "    Second paragraph"
        let line1 = read_line(&buf, 1, area.width);
        let line2 = read_line(&buf, 2, area.width);
        let line3 = read_line(&buf, 3, area.width);
        assert!(line1.contains("First paragraph"), "Row 1: '{}'", line1);
        assert!(line1.contains('•'), "Row 1 should have bullet: '{}'", line1);
        assert!(
            !line2.contains("Second"),
            "Row 2 should be blank separator: '{}'",
            line2
        );
        assert!(line3.contains("Second paragraph"), "Row 3: '{}'", line3);
        assert!(
            !line3.contains('•'),
            "Row 3 should not have bullet: '{}'",
            line3
        );
    }

    #[test]
    fn long_block_wraps_in_visible_output() {
        let area = Rect::new(0, 0, 30, 10);
        let mut buf = Buffer::empty(area);

        // "  • " prefix is 4 chars, leaving 26 chars for text
        // This text is ~40 chars, should wrap to 2+ lines
        let long_text = "this is a very long block text that should wrap";
        let day = make_daily_note("Feb 21", 2026, 2, 21, vec![make_block("b1", long_text, 0)]);

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        // Row 0: heading
        // Row 1: first line of wrapped block (with bullet)
        // Row 2: continuation line (with indent)
        let line1 = read_line(&buf, 1, area.width);
        let line2 = read_line(&buf, 2, area.width);
        assert!(
            line1.contains("this"),
            "Expected first part of text on row 1, got: '{}'",
            line1
        );
        assert!(
            !line2.trim().is_empty(),
            "Expected continuation on row 2, got: '{}'",
            line2
        );
        // Continuation should NOT have a bullet
        assert!(
            !line2.contains('•'),
            "Continuation line should not have bullet, got: '{}'",
            line2
        );
    }

    #[test]
    fn test_collapsed_block_shows_arrow_indicator() {
        let parent = Block {
            uid: "p".into(),
            string: "Parent".into(),
            order: 0,
            children: vec![make_block("c1", "Child", 0)],
            open: false,
            refs: vec![],
        };
        let day = make_daily_note("Feb 21", 2026, 2, 21, vec![parent]);
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day], false, &mut hl, &HashMap::new());

        assert!(matches!(
            &lines[1],
            VisibleLine::Block {
                collapsed_children: 1,
                ..
            }
        ));
    }

    #[test]
    fn test_collapsed_block_shows_children_count() {
        let area = Rect::new(0, 0, 60, 10);
        let mut buf = Buffer::empty(area);

        let parent = Block {
            uid: "p".into(),
            string: "Parent".into(),
            order: 0,
            children: vec![
                make_block("c1", "Child1", 0),
                make_block("c2", "Child2", 1),
                make_block("c3", "Child3", 2),
            ],
            open: false,
            refs: vec![],
        };
        let day = make_daily_note("Feb 21", 2026, 2, 21, vec![parent]);

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        let line1 = read_line(&buf, 1, area.width);
        assert!(
            line1.contains("â–¸"),
            "Expected 'â–¸' for collapsed block, got: '{}'",
            line1
        );
        assert!(
            line1.contains("[3]"),
            "Expected '[3]' children count, got: '{}'",
            line1
        );
    }

    #[test]
    fn test_open_block_shows_bullet() {
        let area = Rect::new(0, 0, 60, 10);
        let mut buf = Buffer::empty(area);

        let day = make_daily_note(
            "Feb 21",
            2026,
            2,
            21,
            vec![make_block("b1", "Normal block", 0)],
        );

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        let line1 = read_line(&buf, 1, area.width);
        assert!(
            line1.contains('•'),
            "Expected '•' for open block, got: '{}'",
            line1
        );
        assert!(
            !line1.contains('â–¸'),
            "Should not contain 'â–¸' for open block, got: '{}'",
            line1
        );
    }

    #[test]
    fn test_day_separator_rendered() {
        let area = Rect::new(0, 0, 40, 10);
        let mut buf = Buffer::empty(area);

        let day1 = make_daily_note("Day 1", 2026, 2, 21, vec![make_block("a", "A", 0)]);
        let day2 = make_daily_note("Day 2", 2026, 2, 20, vec![make_block("b", "B", 0)]);

        let widget = MainArea {
            days: &[day1, day2],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        // Row 0: Day 1 heading
        // Row 1: block A
        // Row 2: separator (─ chars)
        // Row 3: Day 2 heading
        let sep_line = read_line(&buf, 2, area.width);
        assert!(
            sep_line.contains('─'),
            "Expected '─' separator between days, got: '{}'",
            sep_line
        );
    }

    #[test]
    fn test_selected_block_has_indicator() {
        let area = Rect::new(0, 0, 60, 10);
        let mut buf = Buffer::empty(area);

        let day = make_daily_note(
            "Feb 21",
            2026,
            2,
            21,
            vec![make_block("b1", "First", 0), make_block("b2", "Second", 1)],
        );

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        let line1 = read_line(&buf, 1, area.width);
        assert!(
            line1.contains('â–Ž'),
            "Expected 'â–Ž' selection indicator, got: '{}'",
            line1
        );

        // Non-selected block should NOT have indicator
        let line2 = read_line(&buf, 2, area.width);
        assert!(
            !line2.contains('â–Ž'),
            "Non-selected should not have 'â–Ž', got: '{}'",
            line2
        );
    }

    // --- Empty day with blocks renders heading (no "No notes" message) ---

    #[test]
    fn day_with_blocks_renders_heading_not_no_notes_message() {
        let area = Rect::new(0, 0, 40, 5);
        let mut buf = Buffer::empty(area);

        let day = make_daily_note(
            "February 25th, 2026",
            2026,
            2,
            25,
            vec![make_block("b1", "Some block", 0)],
        );

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        let no_notes_found =
            (0..area.height).any(|y| read_line(&buf, y, area.width).contains("No notes"));
        assert!(
            !no_notes_found,
            "Should not show 'No notes' when day has blocks"
        );

        let heading_found = (0..area.height)
            .any(|y| read_line(&buf, y, area.width).contains("February 25th, 2026"));
        assert!(heading_found, "Should render the day heading");
    }

    #[test]
    fn day_with_empty_blocks_vec_renders_heading_not_no_notes() {
        let area = Rect::new(0, 0, 40, 5);
        let mut buf = Buffer::empty(area);

        // days slice has one entry but no blocks — still renders heading, not "No notes"
        let day = make_daily_note("February 25th, 2026", 2026, 2, 25, vec![]);

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &HashMap::new(),
        };
        widget.render(area, &mut buf);

        let no_notes_found =
            (0..area.height).any(|y| read_line(&buf, y, area.width).contains("No notes"));
        assert!(
            !no_notes_found,
            "Should not show 'No notes' when days slice is non-empty"
        );

        let heading_found = (0..area.height)
            .any(|y| read_line(&buf, y, area.width).contains("February 25th, 2026"));
        assert!(
            heading_found,
            "Should render the day heading even with no blocks"
        );
    }

    // --- inject_cursor renders cursor character with inverted style ---

    #[test]
    fn inject_cursor_at_zero_inverts_first_char() {
        let style = Style::default().fg(Color::Gray);
        let spans = vec![Span::styled("hello", style)];
        let result = inject_cursor(spans, 0);

        let cursor_style = Style::default().fg(Color::Black).bg(Color::White);
        // First char 'h' should have cursor style
        assert_eq!(result[0].content.chars().next().unwrap(), 'h');
        assert_eq!(result[0].style, cursor_style);
    }

    #[test]
    fn inject_cursor_at_mid_inverts_correct_char() {
        let style = Style::default().fg(Color::Gray);
        let spans = vec![Span::styled("hello", style)];
        let result = inject_cursor(spans, 2);

        // Characters should be split: "he" | "l" (cursor) | "lo"
        let all_chars: String = result.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(all_chars, "hello");

        // Find the span containing the cursor char 'l' at position 2
        let cursor_style = Style::default().fg(Color::Black).bg(Color::White);
        let cursor_span = result.iter().find(|s| s.style == cursor_style);
        assert!(cursor_span.is_some(), "Expected a span with cursor style");
        assert_eq!(cursor_span.unwrap().content.as_ref(), "l");
    }

    #[test]
    fn inject_cursor_on_empty_spans_returns_space_with_cursor_style() {
        let result = inject_cursor(vec![], 0);
        let cursor_style = Style::default().fg(Color::Black).bg(Color::White);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].content.as_ref(), " ");
        assert_eq!(result[0].style, cursor_style);
    }

    #[test]
    fn inject_cursor_out_of_bounds_clamps_to_last_char() {
        let style = Style::default().fg(Color::Gray);
        let spans = vec![Span::styled("abc", style)];
        // Cursor position 99 is beyond text length, should clamp to last char 'c'
        let result = inject_cursor(spans, 99);

        let cursor_style = Style::default().fg(Color::Black).bg(Color::White);
        let cursor_span = result.iter().find(|s| s.style == cursor_style);
        assert!(cursor_span.is_some(), "Expected cursor style on last char");
        assert_eq!(cursor_span.unwrap().content.as_ref(), "c");
    }

    #[test]
    fn inject_cursor_preserves_all_chars() {
        let style = Style::default().fg(Color::Gray);
        let spans = vec![Span::styled("world", style)];
        let result = inject_cursor(spans, 3);

        let all_chars: String = result.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(all_chars, "world", "All characters must be preserved");
    }

    // --- Linked References rendering tests ---

    use crate::api::types::{LinkedRefBlock, LinkedRefGroup};

    fn make_linked_refs() -> LinkedRefsState {
        LinkedRefsState {
            groups: vec![LinkedRefGroup {
                page_title: "Source Page".into(),
                blocks: vec![LinkedRefBlock {
                    uid: "lr1".into(),
                    string: "mentions [[Target]]".into(),
                    page_title: "Source Page".into(),
                }],
            }],
            collapsed: false,
            loading: false,
        }
    }

    #[test]
    fn build_visible_lines_includes_linked_refs() {
        let day = make_daily_note("Feb 25", 2026, 2, 25, vec![make_block("b1", "Block", 0)]);
        let lr = make_linked_refs();
        let lr_map = HashMap::from([("Feb 25".to_string(), lr)]);
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day], false, &mut hl, &lr_map);

        // heading + block + separator + header + group header + block = 6
        assert_eq!(lines.len(), 6);
        assert!(matches!(&lines[2], VisibleLine::LinkedRefsSeparator));
        assert!(matches!(
            &lines[3],
            VisibleLine::LinkedRefsHeader {
                count: 1,
                collapsed: false,
                ..
            }
        ));
        assert!(matches!(
            &lines[4],
            VisibleLine::LinkedRefsGroupHeader { ref page_title, .. } if page_title == "Source Page"
        ));
        assert!(matches!(
            &lines[5],
            VisibleLine::LinkedRefsBlock { ref text, .. } if text.contains("Target")
        ));
    }

    #[test]
    fn build_visible_lines_collapsed_linked_refs() {
        let day = make_daily_note("Feb 25", 2026, 2, 25, vec![make_block("b1", "Block", 0)]);
        let lr = LinkedRefsState {
            groups: vec![LinkedRefGroup {
                page_title: "P".into(),
                blocks: vec![LinkedRefBlock {
                    uid: "x".into(),
                    string: "ref".into(),
                    page_title: "P".into(),
                }],
            }],
            collapsed: true,
            loading: false,
        };
        let lr_map = HashMap::from([("Feb 25".to_string(), lr)]);
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day], false, &mut hl, &lr_map);

        // heading + block + separator + header = 4 (no group/block lines)
        assert_eq!(lines.len(), 4);
        assert!(matches!(
            &lines[3],
            VisibleLine::LinkedRefsHeader {
                collapsed: true,
                ..
            }
        ));
    }

    #[test]
    fn build_visible_lines_empty_linked_refs_not_shown() {
        let day = make_daily_note("Feb 25", 2026, 2, 25, vec![make_block("b1", "Block", 0)]);
        let lr = LinkedRefsState {
            groups: vec![],
            collapsed: false,
            loading: false,
        };
        let lr_map = HashMap::from([("Feb 25".to_string(), lr)]);
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day], false, &mut hl, &lr_map);

        // heading + block = 2 (no linked refs section)
        assert_eq!(lines.len(), 2);
    }

    #[test]
    fn renders_linked_refs_header() {
        let area = Rect::new(0, 0, 60, 15);
        let mut buf = Buffer::empty(area);

        let day = make_daily_note("Feb 25", 2026, 2, 25, vec![make_block("b1", "Block", 0)]);
        let lr = make_linked_refs();
        let lr_map = HashMap::from([("Feb 25".to_string(), lr)]);

        let widget = MainArea {
            days: &[day],
            selected_block: 0,
            cursor_col: 0,
            loading: false,
            loading_more: false,
            edit_info: None,
            block_ref_cache: &HashMap::new(),
            linked_refs: &lr_map,
        };
        widget.render(area, &mut buf);

        let found_header =
            (0..area.height).any(|y| read_line(&buf, y, area.width).contains("Linked References"));
        assert!(found_header, "Expected 'Linked References' header");

        let found_source =
            (0..area.height).any(|y| read_line(&buf, y, area.width).contains("Source Page"));
        assert!(found_source, "Expected 'Source Page' group header");
    }

    #[test]
    fn linked_refs_block_index_starts_after_flat_blocks() {
        let day = make_daily_note(
            "Feb 25",
            2026,
            2,
            25,
            vec![make_block("b1", "A", 0), make_block("b2", "B", 1)],
        );
        let lr = make_linked_refs();
        let lr_map = HashMap::from([("Feb 25".to_string(), lr)]);
        let mut hl = CodeHighlighter::new();
        let lines = build_visible_lines(&[day], false, &mut hl, &lr_map);

        // Lines: [0]=heading, [1]=block(0), [2]=block(1), [3]=separator, [4]=header(2), [5]=group(3), [6]=block(4)
        if let VisibleLine::LinkedRefsHeader { block_index, .. } = &lines[4] {
            assert_eq!(*block_index, 2);
        } else {
            panic!("Expected LinkedRefsHeader at index 4, got {:?}", &lines[4]);
        }
        if let VisibleLine::LinkedRefsGroupHeader { block_index, .. } = &lines[5] {
            assert_eq!(*block_index, 3);
        } else {
            panic!(
                "Expected LinkedRefsGroupHeader at index 5, got {:?}",
                &lines[5]
            );
        }
    }
}