turbovault-parser 1.3.0

Obsidian Flavored Markdown (OFM) parser
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
//! Block-level content parsing for markdown documents.
//!
//! This module provides full block-level parsing using pulldown-cmark,
//! producing a structured representation of markdown content including:
//! - Paragraphs, headings, code blocks
//! - Lists (ordered, unordered, task lists)
//! - Tables, blockquotes, images
//! - HTML details blocks
//!
//! The parser handles inline formatting within blocks, producing
//! `InlineElement` vectors for text content.

use pulldown_cmark::{
    Alignment as CmarkAlignment, CodeBlockKind, Event, Options, Parser, Tag, TagEnd,
};
use regex::Regex;
use std::sync::LazyLock;
use turbovault_core::{ContentBlock, InlineElement, ListItem, TableAlignment};

// ============================================================================
// Wikilink preprocessing (converts [[x]] to [x](wikilink:x) for pulldown-cmark)
// ============================================================================

/// Regex for wikilinks: [[target]] or [[target|alias]]
static WIKILINK_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\[\[([^\]|]+)(?:\|([^\]]+))?\]\]").unwrap());

/// Preprocess wikilinks to standard markdown links with wikilink: prefix.
/// This allows pulldown-cmark to parse them as regular links.
fn preprocess_wikilinks(markdown: &str) -> String {
    WIKILINK_RE
        .replace_all(markdown, |caps: &regex::Captures| {
            let target = caps.get(1).map(|m| m.as_str().trim()).unwrap_or("");
            let alias = caps.get(2).map(|m| m.as_str().trim());
            let display_text = alias.unwrap_or(target);
            format!("[{}](wikilink:{})", display_text, target)
        })
        .to_string()
}

/// Regex for links with spaces in URL (not valid CommonMark but common in wikis)
static LINK_WITH_SPACES_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\[([^\]]+)\]\(([^)<>]+\s[^)<>]*)\)").unwrap());

/// Preprocess links with spaces to angle bracket syntax.
fn preprocess_links_with_spaces(markdown: &str) -> String {
    LINK_WITH_SPACES_RE
        .replace_all(markdown, |caps: &regex::Captures| {
            let text = &caps[1];
            let url = &caps[2];
            if url.contains(' ') {
                format!("[{}](<{}>)", text, url)
            } else {
                caps[0].to_string()
            }
        })
        .to_string()
}

// ============================================================================
// Details block extraction (HTML <details><summary>)
// ============================================================================

/// Extract HTML <details> blocks and replace with placeholders.
fn extract_details_blocks(markdown: &str) -> (String, Vec<ContentBlock>) {
    let mut details_blocks = Vec::new();
    let mut result = String::new();
    let mut current_pos = 0;

    while current_pos < markdown.len() {
        if markdown[current_pos..].starts_with("<details")
            && let Some(tag_end) = markdown[current_pos..].find('>')
            && let details_start = current_pos + tag_end + 1
            && let Some(details_end_pos) = markdown[details_start..].find("</details>")
        {
            let details_end = details_start + details_end_pos;
            let details_content = &markdown[details_start..details_end];

            // Extract summary
            let summary = extract_summary(details_content);

            // Extract content after </summary>
            let content_start = if let Some(summary_end_pos) = details_content.find("</summary>") {
                let summary_tag_end = summary_end_pos + "</summary>".len();
                &details_content[summary_tag_end..]
            } else {
                details_content
            };

            let content_trimmed = content_start.trim();

            // Parse nested content
            let nested_blocks = if !content_trimmed.is_empty() {
                parse_blocks(content_trimmed)
            } else {
                Vec::new()
            };

            details_blocks.push(ContentBlock::Details {
                summary,
                content: content_trimmed.to_string(),
                blocks: nested_blocks,
            });

            result.push_str(&format!("\n[DETAILS_BLOCK_{}]\n", details_blocks.len() - 1));
            current_pos = details_end + "</details>".len();
            continue;
        }

        if let Some(ch) = markdown[current_pos..].chars().next() {
            result.push(ch);
            current_pos += ch.len_utf8();
        } else {
            break;
        }
    }

    (result, details_blocks)
}

/// Extract summary text from details content.
fn extract_summary(details_content: &str) -> String {
    if let Some(summary_start_pos) = details_content.find("<summary")
        && let Some(summary_tag_end) = details_content[summary_start_pos..].find('>')
        && let summary_content_start = summary_start_pos + summary_tag_end + 1
        && let Some(summary_end_pos) = details_content[summary_content_start..].find("</summary>")
    {
        let summary_end = summary_content_start + summary_end_pos;
        return details_content[summary_content_start..summary_end]
            .trim()
            .to_string();
    }
    String::new()
}

// ============================================================================
// Parser state machine
// ============================================================================

struct BlockParserState {
    current_line: usize,
    paragraph_buffer: String,
    inline_buffer: Vec<InlineElement>,
    list_items: Vec<ListItem>,
    list_ordered: bool,
    list_depth: usize,
    item_depth: usize,
    task_list_marker: Option<bool>,
    saved_task_markers: Vec<Option<bool>>,
    item_blocks: Vec<ContentBlock>,
    code_buffer: String,
    code_language: Option<String>,
    code_start_line: usize,
    blockquote_buffer: String,
    table_headers: Vec<String>,
    table_alignments: Vec<TableAlignment>,
    table_rows: Vec<Vec<String>>,
    current_row: Vec<String>,
    heading_level: Option<usize>,
    heading_buffer: String,
    heading_inline: Vec<InlineElement>,
    in_paragraph: bool,
    in_list: bool,
    in_code: bool,
    in_blockquote: bool,
    in_table: bool,
    in_heading: bool,
    in_strong: bool,
    in_emphasis: bool,
    in_strikethrough: bool,
    in_code_inline: bool,
    in_link: bool,
    link_url: String,
    link_text: String,
    image_in_link: bool,
    in_image: bool,
    saved_link_url: String,
    /// Tracks relative line offset within current list item (for nested items)
    nested_line_offset: usize,
}

impl BlockParserState {
    fn new(start_line: usize) -> Self {
        Self {
            current_line: start_line,
            paragraph_buffer: String::new(),
            inline_buffer: Vec::new(),
            list_items: Vec::new(),
            list_ordered: false,
            list_depth: 0,
            item_depth: 0,
            task_list_marker: None,
            saved_task_markers: Vec::new(),
            item_blocks: Vec::new(),
            code_buffer: String::new(),
            code_language: None,
            code_start_line: 0,
            blockquote_buffer: String::new(),
            table_headers: Vec::new(),
            table_alignments: Vec::new(),
            table_rows: Vec::new(),
            current_row: Vec::new(),
            heading_level: None,
            heading_buffer: String::new(),
            heading_inline: Vec::new(),
            in_paragraph: false,
            in_list: false,
            in_code: false,
            in_blockquote: false,
            in_table: false,
            in_heading: false,
            in_strong: false,
            in_emphasis: false,
            in_strikethrough: false,
            in_code_inline: false,
            in_link: false,
            link_url: String::new(),
            link_text: String::new(),
            image_in_link: false,
            in_image: false,
            saved_link_url: String::new(),
            nested_line_offset: 0,
        }
    }

    fn finalize(&mut self, blocks: &mut Vec<ContentBlock>) {
        self.flush_paragraph(blocks);
        self.flush_list(blocks);
        self.flush_code(blocks);
        self.flush_blockquote(blocks);
        self.flush_table(blocks);
    }

    fn flush_paragraph(&mut self, blocks: &mut Vec<ContentBlock>) {
        if self.in_paragraph && !self.paragraph_buffer.is_empty() {
            blocks.push(ContentBlock::Paragraph {
                content: self.paragraph_buffer.clone(),
                inline: self.inline_buffer.clone(),
            });
            self.paragraph_buffer.clear();
            self.inline_buffer.clear();
            self.in_paragraph = false;
        }
    }

    fn flush_list(&mut self, blocks: &mut Vec<ContentBlock>) {
        if self.in_list && !self.list_items.is_empty() {
            blocks.push(ContentBlock::List {
                ordered: self.list_ordered,
                items: self.list_items.clone(),
            });
            self.list_items.clear();
            self.in_list = false;
        }
    }

    fn flush_code(&mut self, blocks: &mut Vec<ContentBlock>) {
        if self.in_code && !self.code_buffer.is_empty() {
            blocks.push(ContentBlock::Code {
                language: self.code_language.clone(),
                content: self.code_buffer.trim_end().to_string(),
                start_line: self.code_start_line,
                end_line: self.current_line,
            });
            self.code_buffer.clear();
            self.code_language = None;
            self.in_code = false;
        }
    }

    fn flush_blockquote(&mut self, blocks: &mut Vec<ContentBlock>) {
        if self.in_blockquote && !self.blockquote_buffer.is_empty() {
            let nested_blocks = parse_blocks(&self.blockquote_buffer);
            blocks.push(ContentBlock::Blockquote {
                content: self.blockquote_buffer.clone(),
                blocks: nested_blocks,
            });
            self.blockquote_buffer.clear();
            self.in_blockquote = false;
        }
    }

    fn flush_table(&mut self, blocks: &mut Vec<ContentBlock>) {
        if self.in_table && !self.table_headers.is_empty() {
            blocks.push(ContentBlock::Table {
                headers: self.table_headers.clone(),
                alignments: self.table_alignments.clone(),
                rows: self.table_rows.clone(),
            });
            self.table_headers.clear();
            self.table_alignments.clear();
            self.table_rows.clear();
            self.current_row.clear();
            self.paragraph_buffer.clear();
            self.inline_buffer.clear();
            self.in_table = false;
        }
    }

    fn add_inline_text(&mut self, text: &str) {
        if text.is_empty() {
            return;
        }

        let element = if self.in_code_inline {
            InlineElement::Code {
                value: text.to_string(),
            }
        } else if self.in_strong {
            InlineElement::Strong {
                value: text.to_string(),
            }
        } else if self.in_emphasis {
            InlineElement::Emphasis {
                value: text.to_string(),
            }
        } else if self.in_strikethrough {
            InlineElement::Strikethrough {
                value: text.to_string(),
            }
        } else {
            InlineElement::Text {
                value: text.to_string(),
            }
        };

        self.inline_buffer.push(element);
        self.paragraph_buffer.push_str(text);
    }
}

// ============================================================================
// Event processing
// ============================================================================

#[allow(clippy::too_many_lines)]
fn process_event(event: Event, state: &mut BlockParserState, blocks: &mut Vec<ContentBlock>) {
    match event {
        Event::Start(Tag::Paragraph) => {
            state.in_paragraph = true;
        }
        Event::End(TagEnd::Paragraph) => {
            if state.item_depth >= 1 && state.in_paragraph && !state.paragraph_buffer.is_empty() {
                state.item_blocks.push(ContentBlock::Paragraph {
                    content: state.paragraph_buffer.clone(),
                    inline: state.inline_buffer.clone(),
                });
                state.paragraph_buffer.clear();
                state.inline_buffer.clear();
                state.in_paragraph = false;
            } else {
                state.flush_paragraph(blocks);
            }
        }
        Event::Start(Tag::CodeBlock(kind)) => {
            state.in_code = true;
            state.code_start_line = state.current_line;
            state.code_language = match kind {
                CodeBlockKind::Fenced(lang) => {
                    if lang.is_empty() {
                        None
                    } else {
                        Some(lang.to_string())
                    }
                }
                CodeBlockKind::Indented => None,
            };
        }
        Event::End(TagEnd::CodeBlock) => {
            if state.item_depth >= 1 && state.in_code && !state.code_buffer.is_empty() {
                state.item_blocks.push(ContentBlock::Code {
                    language: state.code_language.clone(),
                    content: state.code_buffer.trim_end().to_string(),
                    start_line: state.code_start_line,
                    end_line: state.current_line,
                });
                state.code_buffer.clear();
                state.code_language = None;
                state.in_code = false;
            } else {
                state.flush_code(blocks);
            }
        }
        Event::Start(Tag::List(start_number)) => {
            state.list_depth += 1;
            if state.list_depth == 1 {
                state.in_list = true;
                state.list_ordered = start_number.is_some();
            }
        }
        Event::End(TagEnd::List(_)) => {
            state.list_depth = state.list_depth.saturating_sub(1);
            if state.list_depth == 0 {
                state.flush_list(blocks);
            }
        }
        Event::Start(Tag::Item) => {
            state.item_depth += 1;
            if state.item_depth > 1 {
                state.saved_task_markers.push(state.task_list_marker);
                state.task_list_marker = None;
            }
            if state.item_depth == 1 {
                state.paragraph_buffer.clear();
                state.inline_buffer.clear();
                state.item_blocks.clear();
                state.nested_line_offset = 0;
            }
        }
        Event::End(TagEnd::Item) => {
            if state.item_depth > 1
                && let Some(saved) = state.saved_task_markers.pop()
            {
                state.task_list_marker = saved;
            }
            if state.item_depth == 1 {
                let (content, mut inline, remaining_blocks) = if !state.paragraph_buffer.is_empty()
                {
                    let all_blocks: Vec<ContentBlock> = state.item_blocks.drain(..).collect();
                    (
                        state.paragraph_buffer.clone(),
                        state.inline_buffer.clone(),
                        all_blocks,
                    )
                } else if let Some(ContentBlock::Paragraph { content, inline }) =
                    state.item_blocks.first().cloned()
                {
                    let remaining: Vec<ContentBlock> = state.item_blocks.drain(1..).collect();
                    (content, inline, remaining)
                } else {
                    let all_blocks: Vec<ContentBlock> = state.item_blocks.drain(..).collect();
                    (String::new(), Vec::new(), all_blocks)
                };

                // Collect inline elements from all nested blocks (paragraphs, lists, etc.)
                collect_inline_elements(&remaining_blocks, &mut inline);

                state.list_items.push(ListItem {
                    checked: state.task_list_marker,
                    content,
                    inline,
                    blocks: remaining_blocks,
                });
                state.paragraph_buffer.clear();
                state.inline_buffer.clear();
                state.item_blocks.clear();
                state.task_list_marker = None;
            }
            state.item_depth = state.item_depth.saturating_sub(1);
        }
        Event::TaskListMarker(checked) => {
            state.task_list_marker = Some(checked);
        }
        Event::Start(Tag::BlockQuote(_)) => {
            state.in_blockquote = true;
        }
        Event::End(TagEnd::BlockQuote(_)) => {
            state.flush_blockquote(blocks);
        }
        Event::Start(Tag::Table(alignments)) => {
            state.in_table = true;
            state.table_alignments = alignments
                .iter()
                .map(|a| match a {
                    CmarkAlignment::Left => TableAlignment::Left,
                    CmarkAlignment::Center => TableAlignment::Center,
                    CmarkAlignment::Right => TableAlignment::Right,
                    CmarkAlignment::None => TableAlignment::None,
                })
                .collect();
        }
        Event::End(TagEnd::Table) => {
            state.flush_table(blocks);
        }
        Event::Start(Tag::TableHead) => {}
        Event::End(TagEnd::TableHead) => {
            state.table_headers = state.current_row.clone();
            state.current_row.clear();
        }
        Event::Start(Tag::TableRow) => {}
        Event::End(TagEnd::TableRow) => {
            state.table_rows.push(state.current_row.clone());
            state.current_row.clear();
        }
        Event::Start(Tag::TableCell) => {
            state.paragraph_buffer.clear();
            state.inline_buffer.clear();
        }
        Event::End(TagEnd::TableCell) => {
            state.current_row.push(state.paragraph_buffer.clone());
            state.paragraph_buffer.clear();
            state.inline_buffer.clear();
        }
        Event::Start(Tag::Strong) => {
            state.in_strong = true;
        }
        Event::End(TagEnd::Strong) => {
            state.in_strong = false;
        }
        Event::Start(Tag::Emphasis) => {
            state.in_emphasis = true;
        }
        Event::End(TagEnd::Emphasis) => {
            state.in_emphasis = false;
        }
        Event::Start(Tag::Strikethrough) => {
            state.in_strikethrough = true;
        }
        Event::End(TagEnd::Strikethrough) => {
            state.in_strikethrough = false;
        }
        Event::Code(text) => {
            state.in_code_inline = true;
            state.add_inline_text(&text);
            state.in_code_inline = false;
        }
        Event::Start(Tag::Link { dest_url, .. }) => {
            // For nested list items, add newline and indent before the link
            // (same logic as in Event::Text for nested items)
            if state.in_list && state.item_depth > 1 {
                if !state.paragraph_buffer.is_empty() && !state.paragraph_buffer.ends_with('\n') {
                    state.paragraph_buffer.push('\n');
                    state.nested_line_offset += 1;
                }
                let indent = "  ".repeat(state.item_depth - 1);
                state.paragraph_buffer.push_str(&indent);

                if let Some(checked) = state.task_list_marker {
                    let marker = if checked { "[x] " } else { "[ ] " };
                    state.paragraph_buffer.push_str(marker);
                    state.task_list_marker = None;
                }
            }
            state.in_link = true;
            state.link_url = dest_url.to_string();
            state.link_text.clear();
        }
        Event::End(TagEnd::Link) => {
            state.in_link = false;

            // Capture line_offset for nested list items
            let line_offset = if state.in_list && state.item_depth >= 1 {
                Some(state.nested_line_offset)
            } else {
                None
            };

            if state.image_in_link {
                state.inline_buffer.push(InlineElement::Link {
                    text: state.link_text.clone(),
                    url: state.saved_link_url.clone(),
                    title: None,
                    line_offset,
                });
                state
                    .paragraph_buffer
                    .push_str(&format!("[{}]({})", state.link_text, state.saved_link_url));
            } else {
                state.inline_buffer.push(InlineElement::Link {
                    text: state.link_text.clone(),
                    url: state.link_url.clone(),
                    title: None,
                    line_offset,
                });
                state
                    .paragraph_buffer
                    .push_str(&format!("[{}]({})", state.link_text, state.link_url));
            }

            state.link_text.clear();
            state.link_url.clear();
            state.saved_link_url.clear();
            state.image_in_link = false;
        }
        Event::Start(Tag::Image {
            dest_url, title, ..
        }) => {
            if state.in_link {
                state.image_in_link = true;
                state.saved_link_url = state.link_url.clone();
            }
            state.in_image = true;
            state.link_url = dest_url.to_string();
            state.link_text.clear();
            state.paragraph_buffer = title.to_string();
        }
        Event::End(TagEnd::Image) => {
            state.in_image = false;

            if !state.image_in_link {
                // Capture title before we modify paragraph_buffer
                let title = if state.paragraph_buffer.is_empty() {
                    None
                } else {
                    Some(state.paragraph_buffer.clone())
                };

                // Capture line_offset for inline images in list items
                let line_offset = if state.in_list && state.item_depth >= 1 {
                    Some(state.nested_line_offset)
                } else {
                    None
                };

                if state.in_paragraph {
                    // Reset paragraph_buffer for image representation
                    state.paragraph_buffer.clear();
                    state.inline_buffer.push(InlineElement::Image {
                        alt: state.link_text.clone(),
                        src: state.link_url.clone(),
                        title,
                        line_offset,
                    });
                    // Add image placeholder to paragraph content
                    state
                        .paragraph_buffer
                        .push_str(&format!("![{}]({})", state.link_text, state.link_url));
                } else {
                    state.flush_paragraph(blocks);
                    blocks.push(ContentBlock::Image {
                        alt: state.link_text.clone(),
                        src: state.link_url.clone(),
                        title,
                    });
                    state.paragraph_buffer.clear();
                }

                state.link_text.clear();
                state.link_url.clear();
            }
        }
        Event::Text(text) => {
            if state.in_code {
                state.code_buffer.push_str(&text);
            } else if state.in_blockquote {
                state.blockquote_buffer.push_str(&text);
            } else if state.in_heading {
                state.heading_buffer.push_str(&text);
                let element = if state.in_code_inline {
                    InlineElement::Code {
                        value: text.to_string(),
                    }
                } else if state.in_strong {
                    InlineElement::Strong {
                        value: text.to_string(),
                    }
                } else if state.in_emphasis {
                    InlineElement::Emphasis {
                        value: text.to_string(),
                    }
                } else {
                    InlineElement::Text {
                        value: text.to_string(),
                    }
                };
                state.heading_inline.push(element);
            } else if state.in_link || state.in_image {
                state.link_text.push_str(&text);
            } else {
                if state.in_list && state.item_depth > 1 {
                    if !state.paragraph_buffer.is_empty() && !state.paragraph_buffer.ends_with('\n')
                    {
                        state.paragraph_buffer.push('\n');
                    }
                    let indent = "  ".repeat(state.item_depth - 1);
                    state.paragraph_buffer.push_str(&indent);

                    if let Some(checked) = state.task_list_marker {
                        let marker = if checked { "[x] " } else { "[ ] " };
                        state.paragraph_buffer.push_str(marker);
                        state.task_list_marker = None;
                    }
                }
                state.add_inline_text(&text);
            }
        }
        Event::SoftBreak => {
            if state.in_paragraph {
                state.paragraph_buffer.push(' ');
                state.inline_buffer.push(InlineElement::Text {
                    value: " ".to_string(),
                });
            }
        }
        Event::HardBreak => {
            if state.in_paragraph {
                state.paragraph_buffer.push('\n');
                state.inline_buffer.push(InlineElement::Text {
                    value: "\n".to_string(),
                });
            }
        }
        Event::Rule => {
            state.flush_paragraph(blocks);
            blocks.push(ContentBlock::HorizontalRule);
        }
        Event::Start(Tag::Heading { level, .. }) => {
            state.flush_paragraph(blocks);
            state.in_heading = true;
            state.heading_level = Some(level as usize);
            state.heading_buffer.clear();
            state.heading_inline.clear();
        }
        Event::End(TagEnd::Heading(_)) => {
            if state.in_heading
                && !state.heading_buffer.is_empty()
                && let Some(level) = state.heading_level
            {
                let anchor = Some(slugify(&state.heading_buffer));
                blocks.push(ContentBlock::Heading {
                    level,
                    content: state.heading_buffer.clone(),
                    inline: state.heading_inline.clone(),
                    anchor,
                });
            }
            state.in_heading = false;
            state.heading_level = None;
            state.heading_buffer.clear();
            state.heading_inline.clear();
        }
        _ => {}
    }
}

// ============================================================================
// Slug generation
// ============================================================================

/// Generate URL-friendly slug from heading text.
pub fn slugify(text: &str) -> String {
    text.to_lowercase()
        .chars()
        .map(|c| {
            if c.is_alphanumeric() {
                c
            } else if c.is_whitespace() || c == '-' {
                '-'
            } else {
                '\0'
            }
        })
        .filter(|&c| c != '\0')
        .collect::<String>()
        .split('-')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("-")
}

// ============================================================================
// Helper functions
// ============================================================================

/// Recursively collect inline elements from content blocks.
///
/// This traverses nested structures (paragraphs, lists, blockquotes) to gather
/// all inline elements, enabling consumers to find links and other inline
/// content from nested list items.
fn collect_inline_elements(blocks: &[ContentBlock], output: &mut Vec<InlineElement>) {
    for block in blocks {
        match block {
            ContentBlock::Paragraph { inline, .. } => {
                output.extend(inline.iter().cloned());
            }
            ContentBlock::List { items, .. } => {
                for item in items {
                    output.extend(item.inline.iter().cloned());
                    collect_inline_elements(&item.blocks, output);
                }
            }
            ContentBlock::Blockquote { blocks, .. } => {
                collect_inline_elements(blocks, output);
            }
            ContentBlock::Details { blocks, .. } => {
                collect_inline_elements(blocks, output);
            }
            // Headings, Code, HorizontalRule, Table, Image don't have nested inline elements
            // that we need to collect (or they store them differently)
            _ => {}
        }
    }
}

// ============================================================================
// Public API
// ============================================================================

/// Parse markdown content into structured blocks.
///
/// This is the main entry point for block-level parsing. It handles:
/// - Wikilink preprocessing (converts [[x]] to markdown links)
/// - HTML details block extraction
/// - Full pulldown-cmark parsing with GFM extensions
///
/// # Example
///
/// ```
/// use turbovault_parser::parse_blocks;
/// use turbovault_core::ContentBlock;
///
/// let markdown = "# Hello World\n\nThis is a **paragraph** with *inline* formatting.";
///
/// let blocks = parse_blocks(markdown);
/// assert!(matches!(blocks[0], ContentBlock::Heading { level: 1, .. }));
/// ```
pub fn parse_blocks(markdown: &str) -> Vec<ContentBlock> {
    parse_blocks_from_line(markdown, 0)
}

/// Parse markdown content into structured blocks, starting from a specific line.
///
/// Use this when you need accurate line numbers for nested content.
pub fn parse_blocks_from_line(markdown: &str, start_line: usize) -> Vec<ContentBlock> {
    // Pre-process wikilinks
    let preprocessed = preprocess_wikilinks(markdown);

    // Pre-process links with spaces
    let preprocessed = preprocess_links_with_spaces(&preprocessed);

    // Extract details blocks
    let (processed_markdown, details_blocks) = extract_details_blocks(&preprocessed);

    // Enable GFM extensions
    let mut options = Options::empty();
    options.insert(Options::ENABLE_TABLES);
    options.insert(Options::ENABLE_STRIKETHROUGH);
    options.insert(Options::ENABLE_TASKLISTS);

    let parser = Parser::new_ext(&processed_markdown, options);
    let mut blocks = Vec::new();
    let mut state = BlockParserState::new(start_line);

    for event in parser {
        process_event(event, &mut state, &mut blocks);
    }

    state.finalize(&mut blocks);

    // Replace placeholders with actual Details blocks
    let mut final_blocks = Vec::new();
    for block in blocks {
        let replaced = if let ContentBlock::Paragraph { content, .. } = &block {
            let trimmed = content.trim();
            trimmed
                .strip_prefix("[DETAILS_BLOCK_")
                .and_then(|s| s.strip_suffix(']'))
                .and_then(|s| s.parse::<usize>().ok())
                .and_then(|idx| details_blocks.get(idx).cloned())
        } else {
            None
        };

        final_blocks.push(replaced.unwrap_or(block));
    }

    final_blocks
}

/// Extract plain text from markdown content.
///
/// Strips all markdown syntax, returning only text that would be
/// visible when rendered. This is useful for:
/// - **Search indexing**: Index only searchable text
/// - **Accessibility**: Screen reader text extraction
/// - **Word counts**: Accurate content word counts
/// - **Diffs**: Compare semantic content, not syntax
///
/// # Elements stripped
///
/// | Markdown | Plain Text |
/// |----------|------------|
/// | `[text](url)` | `text` |
/// | `![alt](url)` | `alt` |
/// | `[[Page]]` | `Page` |
/// | `[[Page\|Display]]` | `Display` |
/// | `**bold**` | `bold` |
/// | `*italic*` | `italic` |
/// | `` `code` `` | `code` |
/// | `~~strike~~` | `strike` |
/// | `# Heading` | `Heading` |
/// | `> quote` | (quote content) |
/// | Code fences | (content preserved) |
///
/// # Example
///
/// ```
/// use turbovault_parser::to_plain_text;
///
/// let plain = to_plain_text("[Overview](#overview) and **bold**");
/// assert_eq!(plain, "Overview and bold");
///
/// // Wikilinks are handled properly
/// let plain = to_plain_text("See [[Note]] and [[Other|display]]");
/// assert_eq!(plain, "See Note and display");
/// ```
pub fn to_plain_text(markdown: &str) -> String {
    let blocks = parse_blocks(markdown);
    blocks
        .iter()
        .map(ContentBlock::to_plain_text)
        .collect::<Vec<_>>()
        .join("\n")
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_paragraph() {
        let markdown = "This is a simple paragraph.";
        let blocks = parse_blocks(markdown);

        assert_eq!(blocks.len(), 1);
        assert!(matches!(blocks[0], ContentBlock::Paragraph { .. }));
        if let ContentBlock::Paragraph { content, .. } = &blocks[0] {
            assert_eq!(content, "This is a simple paragraph.");
        }
    }

    #[test]
    fn test_parse_heading() {
        let markdown = "# Hello World";
        let blocks = parse_blocks(markdown);

        assert_eq!(blocks.len(), 1);
        if let ContentBlock::Heading {
            level,
            content,
            anchor,
            ..
        } = &blocks[0]
        {
            assert_eq!(*level, 1);
            assert_eq!(content, "Hello World");
            assert_eq!(anchor.as_deref(), Some("hello-world"));
        } else {
            panic!("Expected Heading block");
        }
    }

    #[test]
    fn test_parse_code_block() {
        let markdown = "```rust\nfn main() {}\n```";
        let blocks = parse_blocks(markdown);

        assert_eq!(blocks.len(), 1);
        if let ContentBlock::Code {
            language, content, ..
        } = &blocks[0]
        {
            assert_eq!(language.as_deref(), Some("rust"));
            assert_eq!(content, "fn main() {}");
        } else {
            panic!("Expected Code block");
        }
    }

    #[test]
    fn test_parse_unordered_list() {
        let markdown = "- Item 1\n- Item 2\n- Item 3";
        let blocks = parse_blocks(markdown);

        assert_eq!(blocks.len(), 1);
        if let ContentBlock::List { ordered, items } = &blocks[0] {
            assert!(!ordered);
            assert_eq!(items.len(), 3);
            assert_eq!(items[0].content, "Item 1");
            assert_eq!(items[1].content, "Item 2");
            assert_eq!(items[2].content, "Item 3");
        } else {
            panic!("Expected List block");
        }
    }

    #[test]
    fn test_parse_ordered_list() {
        let markdown = "1. First\n2. Second\n3. Third";
        let blocks = parse_blocks(markdown);

        assert_eq!(blocks.len(), 1);
        if let ContentBlock::List { ordered, items } = &blocks[0] {
            assert!(ordered);
            assert_eq!(items.len(), 3);
        } else {
            panic!("Expected List block");
        }
    }

    #[test]
    fn test_parse_task_list() {
        let markdown = "- [ ] Todo\n- [x] Done";
        let blocks = parse_blocks(markdown);

        assert_eq!(blocks.len(), 1);
        if let ContentBlock::List { items, .. } = &blocks[0] {
            assert_eq!(items.len(), 2);
            assert_eq!(items[0].checked, Some(false));
            assert_eq!(items[0].content, "Todo");
            assert_eq!(items[1].checked, Some(true));
            assert_eq!(items[1].content, "Done");
        } else {
            panic!("Expected List block");
        }
    }

    #[test]
    fn test_parse_table() {
        let markdown = "| A | B |\n|---|---|\n| 1 | 2 |";
        let blocks = parse_blocks(markdown);

        assert_eq!(blocks.len(), 1);
        if let ContentBlock::Table { headers, rows, .. } = &blocks[0] {
            assert_eq!(headers.len(), 2);
            assert_eq!(headers[0], "A");
            assert_eq!(headers[1], "B");
            assert_eq!(rows.len(), 1);
            assert_eq!(rows[0][0], "1");
            assert_eq!(rows[0][1], "2");
        } else {
            panic!("Expected Table block");
        }
    }

    #[test]
    fn test_parse_blockquote() {
        let markdown = "> This is a quote";
        let blocks = parse_blocks(markdown);

        assert_eq!(blocks.len(), 1);
        if let ContentBlock::Blockquote { content, .. } = &blocks[0] {
            assert!(content.contains("This is a quote"));
        } else {
            panic!("Expected Blockquote block");
        }
    }

    #[test]
    fn test_parse_horizontal_rule() {
        let markdown = "Before\n\n---\n\nAfter";
        let blocks = parse_blocks(markdown);

        assert_eq!(blocks.len(), 3);
        assert!(matches!(blocks[1], ContentBlock::HorizontalRule));
    }

    #[test]
    fn test_parse_inline_formatting() {
        let markdown = "This has **bold** and *italic* and `code`.";
        let blocks = parse_blocks(markdown);

        assert_eq!(blocks.len(), 1);
        if let ContentBlock::Paragraph { inline, .. } = &blocks[0] {
            assert!(
                inline
                    .iter()
                    .any(|e| matches!(e, InlineElement::Strong { .. }))
            );
            assert!(
                inline
                    .iter()
                    .any(|e| matches!(e, InlineElement::Emphasis { .. }))
            );
            assert!(
                inline
                    .iter()
                    .any(|e| matches!(e, InlineElement::Code { .. }))
            );
        } else {
            panic!("Expected Paragraph block");
        }
    }

    #[test]
    fn test_parse_link() {
        let markdown = "See [example](https://example.com) for more.";
        let blocks = parse_blocks(markdown);

        assert_eq!(blocks.len(), 1);
        if let ContentBlock::Paragraph { inline, .. } = &blocks[0] {
            let link = inline
                .iter()
                .find(|e| matches!(e, InlineElement::Link { .. }));
            assert!(link.is_some());
            if let Some(InlineElement::Link { text, url, .. }) = link {
                assert_eq!(text, "example");
                assert_eq!(url, "https://example.com");
            }
        } else {
            panic!("Expected Paragraph block");
        }
    }

    #[test]
    fn test_wikilink_preprocessing() {
        let markdown = "See [[Note]] and [[Other|display]] for info.";
        let blocks = parse_blocks(markdown);

        assert_eq!(blocks.len(), 1);
        if let ContentBlock::Paragraph { inline, .. } = &blocks[0] {
            let links: Vec<_> = inline
                .iter()
                .filter(|e| matches!(e, InlineElement::Link { .. }))
                .collect();
            assert_eq!(links.len(), 2);

            if let InlineElement::Link { text, url, .. } = &links[0] {
                assert_eq!(text, "Note");
                assert_eq!(url, "wikilink:Note");
            }
            if let InlineElement::Link { text, url, .. } = &links[1] {
                assert_eq!(text, "display");
                assert_eq!(url, "wikilink:Other");
            }
        } else {
            panic!("Expected Paragraph block");
        }
    }

    #[test]
    fn test_list_with_nested_code() {
        let markdown = r#"1. First item
   ```rust
   code here
   ```

2. Second item"#;

        let blocks = parse_blocks(markdown);

        assert_eq!(blocks.len(), 1);
        if let ContentBlock::List { items, .. } = &blocks[0] {
            assert_eq!(items.len(), 2);
            assert!(!items[0].blocks.is_empty());
            assert!(matches!(items[0].blocks[0], ContentBlock::Code { .. }));
        } else {
            panic!("Expected List block");
        }
    }

    #[test]
    fn test_parse_image() {
        // Standalone image is wrapped in paragraph by pulldown-cmark
        let markdown = "![Alt text](image.png)";
        let blocks = parse_blocks(markdown);

        // pulldown-cmark wraps standalone images in paragraphs
        assert_eq!(blocks.len(), 1);
        if let ContentBlock::Paragraph { inline, .. } = &blocks[0] {
            let img = inline
                .iter()
                .find(|e| matches!(e, InlineElement::Image { .. }));
            assert!(img.is_some(), "Should have inline image");
        } else {
            panic!("Expected Paragraph block with inline image");
        }
    }

    #[test]
    fn test_parse_block_image() {
        // Image following other content becomes a block image
        let markdown = "Some text\n\n![Alt](image.png)";
        let blocks = parse_blocks(markdown);

        // First paragraph, then image (inline or block)
        assert!(blocks.len() >= 2);
    }

    #[test]
    fn test_parse_details_block() {
        let markdown = r#"<details>
<summary>Click to expand</summary>

Inner content here.

</details>"#;

        let blocks = parse_blocks(markdown);

        assert_eq!(blocks.len(), 1);
        if let ContentBlock::Details {
            summary,
            blocks: inner,
            ..
        } = &blocks[0]
        {
            assert_eq!(summary, "Click to expand");
            assert!(!inner.is_empty());
        } else {
            panic!("Expected Details block");
        }
    }

    #[test]
    fn test_slugify() {
        assert_eq!(slugify("Hello World"), "hello-world");
        assert_eq!(slugify("API Reference"), "api-reference");
        assert_eq!(slugify("1. Getting Started"), "1-getting-started");
        assert_eq!(slugify("What's New?"), "whats-new");
    }

    #[test]
    fn test_strikethrough() {
        let markdown = "This is ~~deleted~~ text.";
        let blocks = parse_blocks(markdown);

        assert_eq!(blocks.len(), 1);
        if let ContentBlock::Paragraph { inline, .. } = &blocks[0] {
            assert!(
                inline
                    .iter()
                    .any(|e| matches!(e, InlineElement::Strikethrough { .. }))
            );
        }
    }

    #[test]
    fn test_indented_code_blocks_in_list_items() {
        // Bug report: indented fenced code blocks in list items should be recognized
        // Per CommonMark spec, code blocks can be indented up to 3 spaces to be part of a list item
        let markdown = r#"## Installation

1. Install from crates.io:
   ```bash
   cargo install treemd
   ```

2. Or build from source:
   ```bash
   git clone https://github.com/example/repo
   cd repo
   cargo install --path .
   ```"#;

        let blocks = parse_blocks(markdown);

        // Should have: Heading, List
        assert_eq!(blocks.len(), 2, "Expected 2 blocks (heading + list)");
        assert!(
            matches!(blocks[0], ContentBlock::Heading { level: 2, .. }),
            "First block should be H2"
        );

        if let ContentBlock::List { ordered, items } = &blocks[1] {
            assert!(ordered, "Should be an ordered list");
            assert_eq!(items.len(), 2, "Should have 2 list items");

            // First item should have code block in its nested blocks
            assert!(
                !items[0].blocks.is_empty(),
                "First item should have nested blocks"
            );
            assert!(
                matches!(items[0].blocks[0], ContentBlock::Code { .. }),
                "First item's nested block should be Code"
            );
            if let ContentBlock::Code {
                language, content, ..
            } = &items[0].blocks[0]
            {
                assert_eq!(language.as_deref(), Some("bash"));
                assert!(content.contains("cargo install treemd"));
            }

            // Second item should also have code block in its nested blocks
            assert!(
                !items[1].blocks.is_empty(),
                "Second item should have nested blocks"
            );
            assert!(
                matches!(items[1].blocks[0], ContentBlock::Code { .. }),
                "Second item's nested block should be Code"
            );
            if let ContentBlock::Code {
                language, content, ..
            } = &items[1].blocks[0]
            {
                assert_eq!(language.as_deref(), Some("bash"));
                assert!(content.contains("git clone"));
            }
        } else {
            panic!("Expected List block");
        }
    }

    // ========================================================================
    // to_plain_text tests
    // ========================================================================

    #[test]
    fn test_to_plain_text_simple_paragraph() {
        let markdown = "This is a simple paragraph.";
        let plain = to_plain_text(markdown);
        assert_eq!(plain, "This is a simple paragraph.");
    }

    #[test]
    fn test_to_plain_text_with_link() {
        let markdown = "[Overview](#overview) and more text";
        let plain = to_plain_text(markdown);
        assert_eq!(plain, "Overview and more text");
    }

    #[test]
    fn test_to_plain_text_with_bold_and_italic() {
        let markdown = "This has **bold** and *italic* text.";
        let plain = to_plain_text(markdown);
        assert_eq!(plain, "This has bold and italic text.");
    }

    #[test]
    fn test_to_plain_text_with_inline_code() {
        let markdown = "Use the `println!` macro.";
        let plain = to_plain_text(markdown);
        assert_eq!(plain, "Use the println! macro.");
    }

    #[test]
    fn test_to_plain_text_with_strikethrough() {
        let markdown = "This is ~~deleted~~ text.";
        let plain = to_plain_text(markdown);
        assert_eq!(plain, "This is deleted text.");
    }

    #[test]
    fn test_to_plain_text_wikilinks() {
        let markdown = "See [[Note]] and [[Other|display]] for info.";
        let plain = to_plain_text(markdown);
        assert_eq!(plain, "See Note and display for info.");
    }

    #[test]
    fn test_to_plain_text_heading() {
        let markdown = "# Hello World";
        let plain = to_plain_text(markdown);
        assert_eq!(plain, "Hello World");
    }

    #[test]
    fn test_to_plain_text_code_block() {
        let markdown = "```rust\nfn main() {}\n```";
        let plain = to_plain_text(markdown);
        assert_eq!(plain, "fn main() {}");
    }

    #[test]
    fn test_to_plain_text_list() {
        let markdown = "- Item 1\n- Item 2\n- Item 3";
        let plain = to_plain_text(markdown);
        assert_eq!(plain, "Item 1\nItem 2\nItem 3");
    }

    #[test]
    fn test_to_plain_text_table() {
        let markdown = "| A | B |\n|---|---|\n| 1 | 2 |";
        let plain = to_plain_text(markdown);
        // Table headers and rows separated by tabs
        assert!(plain.contains("A\tB"));
        assert!(plain.contains("1\t2"));
    }

    #[test]
    fn test_to_plain_text_blockquote() {
        let markdown = "> This is a quote";
        let plain = to_plain_text(markdown);
        assert!(plain.contains("This is a quote"));
    }

    #[test]
    fn test_to_plain_text_image() {
        let markdown = "![Alt text](image.png)";
        let plain = to_plain_text(markdown);
        assert_eq!(plain, "Alt text");
    }

    #[test]
    fn test_to_plain_text_horizontal_rule() {
        let markdown = "Before\n\n---\n\nAfter";
        let plain = to_plain_text(markdown);
        // Horizontal rules produce empty strings, paragraphs separated by newlines
        assert!(plain.contains("Before"));
        assert!(plain.contains("After"));
    }

    #[test]
    fn test_to_plain_text_complex_document() {
        let markdown = r#"# Document Title

This is a paragraph with **bold** and *italic* text.

- [Link One](#one)
- [Link Two](#two)
- [Link Three](#three)

See [[WikiNote]] for more info."#;

        let plain = to_plain_text(markdown);

        // Should contain heading text
        assert!(plain.contains("Document Title"));
        // Should contain paragraph with formatting stripped
        assert!(plain.contains("bold"));
        assert!(plain.contains("italic"));
        // Should contain link text, not URLs
        assert!(plain.contains("Link One"));
        assert!(plain.contains("Link Two"));
        // Should contain wikilink display text
        assert!(plain.contains("WikiNote"));
        // Should NOT contain URLs
        assert!(!plain.contains("#one"));
        assert!(!plain.contains("#two"));
    }

    #[test]
    fn test_to_plain_text_treemd_use_case() {
        // This test validates the original treemd use case:
        // searching in "[Overview](#overview)" should only match visible text "Overview"
        // not the hidden anchor "#overview"
        let markdown = "[Overview](#overview)";
        let plain = to_plain_text(markdown);
        assert_eq!(plain, "Overview");

        // The visible text "Overview" has 1 'O', while raw markdown has 2 'o's total
        // (capital O in "Overview" + lowercase o in "#overview")
        // Plain text extraction should only show the visible part
        let o_count = plain.chars().filter(|c| *c == 'o' || *c == 'O').count();
        assert_eq!(
            o_count, 1,
            "Should only count 'o' in visible text, not hidden anchor"
        );

        // More explicitly: the anchor URL should not be in plain text
        assert!(!plain.contains("#overview"));
        assert!(!plain.contains("overview")); // lowercase version from anchor
    }

    #[test]
    fn test_to_plain_text_nested_formatting() {
        // Test nested structures
        let markdown = "**[bold link](url)** and *[italic link](url2)*";
        let plain = to_plain_text(markdown);
        // The link text should be extracted
        assert!(plain.contains("bold link"));
        assert!(plain.contains("italic link"));
        // URLs should not appear
        assert!(!plain.contains("url"));
    }

    #[test]
    fn test_nested_list_item_inline_elements() {
        // Test that inline elements from nested list items are collected
        // into the parent item's inline field
        let markdown = r#"- [Features](#features)
  - [Interactive TUI](#interactive-tui)
  - [CLI Mode](#cli-mode)"#;

        let blocks = parse_blocks(markdown);
        assert_eq!(blocks.len(), 1);

        if let ContentBlock::List { items, .. } = &blocks[0] {
            assert_eq!(items.len(), 1, "Should have 1 top-level item");

            let item = &items[0];
            // The inline field should contain ALL links, including from nested items
            let links: Vec<_> = item
                .inline
                .iter()
                .filter_map(|e| {
                    if let InlineElement::Link { text, url, .. } = e {
                        Some((text.as_str(), url.as_str()))
                    } else {
                        None
                    }
                })
                .collect();

            assert_eq!(links.len(), 3, "Should have 3 links total");
            assert!(
                links.iter().any(|(text, _)| *text == "Features"),
                "Should have Features link"
            );
            assert!(
                links.iter().any(|(text, _)| *text == "Interactive TUI"),
                "Should have Interactive TUI link"
            );
            assert!(
                links.iter().any(|(text, _)| *text == "CLI Mode"),
                "Should have CLI Mode link"
            );
        } else {
            panic!("Expected List block");
        }
    }

    #[test]
    fn test_deeply_nested_list_inline_elements() {
        // Test deeply nested list items
        let markdown = r#"- Level 1 [link1](url1)
  - Level 2 [link2](url2)
    - Level 3 [link3](url3)"#;

        let blocks = parse_blocks(markdown);

        if let ContentBlock::List { items, .. } = &blocks[0] {
            let item = &items[0];
            let links: Vec<_> = item
                .inline
                .iter()
                .filter(|e| matches!(e, InlineElement::Link { .. }))
                .collect();

            assert_eq!(links.len(), 3, "Should collect all 3 nested links");
        } else {
            panic!("Expected List block");
        }
    }

    #[test]
    fn test_inline_element_line_offset() {
        // Test that line_offset is correctly tracked for nested list items
        let markdown = r#"- [Features](#features)
  - [Interactive TUI](#interactive-tui)
  - [CLI Mode](#cli-mode)"#;

        let blocks = parse_blocks(markdown);

        if let ContentBlock::List { items, .. } = &blocks[0] {
            let item = &items[0];
            let links: Vec<_> = item
                .inline
                .iter()
                .filter_map(|e| {
                    if let InlineElement::Link {
                        text, line_offset, ..
                    } = e
                    {
                        Some((text.as_str(), *line_offset))
                    } else {
                        None
                    }
                })
                .collect();

            assert_eq!(links.len(), 3);

            // Features is on line 0 (first line of the item)
            let features = links.iter().find(|(t, _)| *t == "Features").unwrap();
            assert_eq!(features.1, Some(0), "Features should be on line 0");

            // Interactive TUI is on line 1 (after first newline)
            let tui = links.iter().find(|(t, _)| *t == "Interactive TUI").unwrap();
            assert_eq!(tui.1, Some(1), "Interactive TUI should be on line 1");

            // CLI Mode is on line 2 (after second newline)
            let cli = links.iter().find(|(t, _)| *t == "CLI Mode").unwrap();
            assert_eq!(cli.1, Some(2), "CLI Mode should be on line 2");
        } else {
            panic!("Expected List block");
        }
    }

    #[test]
    fn test_line_offset_not_set_outside_lists() {
        // line_offset should be None for links outside of list items
        let markdown = "See [example](url) for more.";
        let blocks = parse_blocks(markdown);

        if let ContentBlock::Paragraph { inline, .. } = &blocks[0] {
            let link = inline
                .iter()
                .find(|e| matches!(e, InlineElement::Link { .. }));
            if let Some(InlineElement::Link { line_offset, .. }) = link {
                assert_eq!(
                    *line_offset, None,
                    "line_offset should be None outside lists"
                );
            }
        } else {
            panic!("Expected Paragraph block");
        }
    }
}