boko 0.2.0

Fast ebook conversion library for EPUB and Kindle formats
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
//! IR optimization passes.
//!
//! This module contains optimization passes that run after the initial
//! HTML-to-IR transform but before export. All passes follow the "Zipper"
//! principle: O(n) traversal, in-place mutation, stable NodeIds.
//!
//! ## Pipeline Order
//!
//! The passes run in this order for optimal results:
//!
//! 1. **Vacuum** - Remove structural whitespace noise
//! 2. **Span Merge** - Coalesce adjacent text with same style
//! 3. **List Fuser** - Merge fragmented lists
//! 4. **Pruner** - Remove empty containers (cascading)

use crate::ir::{IRChapter, NodeId, Role};

/// Run all optimization passes on a chapter.
///
/// Passes are ordered for maximum effectiveness:
/// 1. Vacuum removes whitespace noise
/// 2. Hoist dissolves redundant wrapper containers (enables span merge)
/// 3. Span merge coalesces adjacent text with same style
/// 4. List fuser repairs fragmented lists
/// 5. Wrap mixed content normalizes inline/block siblings
/// 6. Pruner removes any containers emptied by previous passes
pub fn optimize(chapter: &mut IRChapter) {
    vacuum(chapter);
    hoist_nested_inlines(chapter);
    merge_adjacent_spans(chapter);
    fuse_lists(chapter);
    wrap_mixed_content(chapter);
    prune_empty(chapter);
}

// ============================================================================
// Pass 1: Vacuum (Structural Whitespace Culling)
// ============================================================================

/// Remove whitespace-only Text nodes that are structurally irrelevant.
///
/// HTML parsers treat indentation between tags as Text nodes:
/// ```html
/// <div>
///     <p>Text</p>
///     \n    <-- This becomes a Node!
/// </div>
/// ```
///
/// These nodes waste memory and can cause ghost elements in TUI rendering.
/// We delete them when:
/// - Role is Text
/// - Content is whitespace-only
/// - Parent is a block container (not inline, not preformatted)
fn vacuum(chapter: &mut IRChapter) {
    if chapter.node_count() > 0 {
        vacuum_children(chapter, NodeId::ROOT);
    }
}

fn vacuum_children(chapter: &mut IRChapter, parent_id: NodeId) {
    // 1. Recurse into children first (bottom-up)
    let mut child_opt = chapter.node(parent_id).and_then(|n| n.first_child);
    while let Some(child_id) = child_opt {
        vacuum_children(chapter, child_id);
        child_opt = chapter.node(child_id).and_then(|n| n.next_sibling);
    }

    // 2. Check if parent is a structural container where whitespace is irrelevant
    let parent_role = chapter.node(parent_id).map(|n| n.role);
    if !is_structural_container(parent_role) {
        return;
    }

    // 3. Walk siblings and unlink whitespace-only Text nodes
    let mut prev_opt: Option<NodeId> = None;
    let mut cursor_opt = chapter.node(parent_id).and_then(|n| n.first_child);

    while let Some(current_id) = cursor_opt {
        let next_opt = chapter.node(current_id).and_then(|n| n.next_sibling);

        if should_vacuum(chapter, current_id) {
            // Unlink this node
            if let Some(prev_id) = prev_opt {
                // Middle or end of list: prev.next_sibling = current.next_sibling
                if let Some(prev_node) = chapter.node_mut(prev_id) {
                    prev_node.next_sibling = next_opt;
                }
            } else {
                // First child: parent.first_child = current.next_sibling
                if let Some(parent_node) = chapter.node_mut(parent_id) {
                    parent_node.first_child = next_opt;
                }
            }
            // Don't update prev_opt - we removed current, so prev stays the same
        } else {
            prev_opt = Some(current_id);
        }

        cursor_opt = next_opt;
    }
}

/// Check if a node should be vacuumed (removed as structural whitespace).
fn should_vacuum(chapter: &IRChapter, node_id: NodeId) -> bool {
    let node = match chapter.node(node_id) {
        Some(n) => n,
        None => return false,
    };

    // Only vacuum Text nodes
    if node.role != Role::Text {
        return false;
    }

    // Safety: Never vacuum nodes with children (defensive - Text shouldn't have children)
    if node.first_child.is_some() {
        return false;
    }

    // Safety: Never vacuum nodes with IDs (they might be link targets)
    if chapter.semantics.id(node_id).is_some() {
        return false;
    }

    // Must have text content to check
    if node.text.is_empty() {
        return true; // Empty text nodes can always be vacuumed
    }

    // Check if content is whitespace-only
    let text = chapter.text(node.text);
    text.trim().is_empty()
}

/// Check if a role is a structural container where inter-element whitespace is irrelevant.
///
/// These are containers that should only contain other block elements, not raw text.
/// Whitespace between their children is formatting noise (indentation, newlines).
///
/// Safe: Root, Container (div/section), Table, TableRow, Lists, Figure
/// Unsafe: Paragraph (contains inline content), Heading, Inline, etc.
fn is_structural_container(role: Option<Role>) -> bool {
    matches!(
        role,
        Some(
            Role::Root
                | Role::Container  // Now safe - <p> is Role::Paragraph
                | Role::Figure
                | Role::Sidebar
                | Role::Footnote
                | Role::Table
                | Role::TableRow
                | Role::OrderedList
                | Role::UnorderedList
                | Role::DefinitionList
        )
    )
}

// ============================================================================
// Pass 2: Hoist Nested Inlines (Wrapper Hell Fix)
// ============================================================================

/// Dissolve redundant wrapper containers to expose siblings for merging.
///
/// Legacy formats (MOBI, AZW) emulate "Small Caps" by wrapping each character
/// in a separate `<font>` or `<div>` container:
/// ```html
/// <div><span>T</span></div><div><span>HE</span></div>
/// ```
///
/// This creates "Wrapper Hell" where text nodes aren't siblings, preventing
/// span merge. This pass identifies containers that:
/// 1. Are generic (Container or Inline)
/// 2. Have exactly one child
/// 3. Have no semantic attributes (id, href, etc.)
///
/// These wrappers are dissolved by promoting the child to the wrapper's position.
fn hoist_nested_inlines(chapter: &mut IRChapter) {
    if chapter.node_count() == 0 {
        return;
    }

    // Run multiple passes to handle deeply nested wrappers (Div > Div > Span)
    // In practice, 2-3 passes clear even the worst MOBI soup.
    let mut changed = true;
    let mut attempts = 0;

    while changed && attempts < 5 {
        changed = hoist_pass(chapter, NodeId::ROOT);
        attempts += 1;
    }
}

/// Run one hoisting pass over the tree. Returns true if any changes were made.
fn hoist_pass(chapter: &mut IRChapter, parent_id: NodeId) -> bool {
    let mut changed = false;

    // Recurse into children first (bottom-up for efficiency)
    let mut child_opt = chapter.node(parent_id).and_then(|n| n.first_child);
    while let Some(child_id) = child_opt {
        if hoist_pass(chapter, child_id) {
            changed = true;
        }
        child_opt = chapter.node(child_id).and_then(|n| n.next_sibling);
    }

    // Now check each child for redundant wrappers
    let mut prev_opt: Option<NodeId> = None;
    let mut cursor_opt = chapter.node(parent_id).and_then(|n| n.first_child);

    while let Some(current_id) = cursor_opt {
        let next_opt = chapter.node(current_id).and_then(|n| n.next_sibling);

        if is_redundant_wrapper(chapter, current_id) {
            // Get the single child that we'll promote
            let child_id = chapter
                .node(current_id)
                .and_then(|n| n.first_child)
                .unwrap();

            // 1. Reparent child to grandparent
            if let Some(child_node) = chapter.node_mut(child_id) {
                child_node.parent = Some(parent_id);
                child_node.next_sibling = next_opt;
            }

            // 2. Patch sibling chain: splice child into wrapper's position
            if let Some(prev_id) = prev_opt {
                if let Some(prev_node) = chapter.node_mut(prev_id) {
                    prev_node.next_sibling = Some(child_id);
                }
            } else if let Some(parent_node) = chapter.node_mut(parent_id) {
                parent_node.first_child = Some(child_id);
            }

            // 3. Detach the wrapper (leave it as a dead node)
            if let Some(wrapper_node) = chapter.node_mut(current_id) {
                wrapper_node.first_child = None;
                wrapper_node.next_sibling = None;
            }

            // Continue from the promoted child (it's now in the wrapper's position)
            prev_opt = Some(child_id);
            cursor_opt = next_opt;
            changed = true;
        } else {
            prev_opt = Some(current_id);
            cursor_opt = next_opt;
        }
    }

    changed
}

/// Check if a node is a redundant wrapper that can be dissolved.
fn is_redundant_wrapper(chapter: &IRChapter, node_id: NodeId) -> bool {
    let node = match chapter.node(node_id) {
        Some(n) => n,
        None => return false,
    };

    // 1. Must be a generic container (Container or Inline)
    if !matches!(node.role, Role::Container | Role::Inline) {
        return false;
    }

    // 2. Must have exactly one child
    let first_child = match node.first_child {
        Some(id) => id,
        None => return false,
    };

    // Check that first child has no sibling (exactly one child)
    if chapter
        .node(first_child)
        .and_then(|n| n.next_sibling)
        .is_some()
    {
        return false;
    }

    // 3. Must have no semantic attributes
    if has_semantic_attrs(chapter, node_id) {
        return false;
    }

    // 4. Must not have text content (containers shouldn't, but be defensive)
    if !node.text.is_empty() {
        return false;
    }

    true
}

// ============================================================================
// Pass 3: Span Merge (Adjacent Text Coalescing)
// ============================================================================

/// Merge adjacent inline/text nodes with identical styles.
///
/// This pass walks the tree using the first_child/next_sibling links.
/// When two adjacent siblings have the same role (Text), same style,
/// no semantic attributes, and contiguous text ranges, they are merged
/// by extending the first node's text range and unlinking the second.
///
/// # Why this matters
///
/// MOBI/AZW files often store small-caps as fragmented elements:
/// ```html
/// <font size="5"><b>T</b></font><font size="2"><b>HE </b></font>
/// ```
///
/// Without this pass, the markdown export would produce:
/// ```text
/// **T****HE **
/// ```
///
/// After merging, we get the expected:
/// ```text
/// **THE **
/// ```
fn merge_adjacent_spans(chapter: &mut IRChapter) {
    if chapter.node_count() > 0 {
        merge_children(chapter, NodeId::ROOT);
    }
}

fn merge_children(chapter: &mut IRChapter, parent_id: NodeId) {
    // 1. Recurse into children first (bottom-up)
    let mut child_opt = chapter.node(parent_id).and_then(|n| n.first_child);
    while let Some(child_id) = child_opt {
        merge_children(chapter, child_id);
        child_opt = chapter.node(child_id).and_then(|n| n.next_sibling);
    }

    // 2. Walk the sibling chain and merge where possible
    let mut cursor_opt = chapter.node(parent_id).and_then(|n| n.first_child);

    while let Some(current_id) = cursor_opt {
        let next_opt = chapter.node(current_id).and_then(|n| n.next_sibling);

        if let Some(next_id) = next_opt
            && can_merge_spans(chapter, current_id, next_id)
        {
            // Merge: extend current's text range to include next's text
            let next_len = chapter.node(next_id).map(|n| n.text.len).unwrap_or(0);
            if let Some(current_node) = chapter.node_mut(current_id) {
                current_node.text.len += next_len;
            }

            // Unlink next: current.next_sibling = next.next_sibling
            let new_next = chapter.node(next_id).and_then(|n| n.next_sibling);
            if let Some(current_node) = chapter.node_mut(current_id) {
                current_node.next_sibling = new_next;
            }

            // Don't advance cursor - the new next might also be mergeable
            continue;
        }

        cursor_opt = next_opt;
    }
}

/// Check if two adjacent siblings can be merged.
fn can_merge_spans(chapter: &IRChapter, left_id: NodeId, right_id: NodeId) -> bool {
    let (left, right) = match (chapter.node(left_id), chapter.node(right_id)) {
        (Some(l), Some(r)) => (l, r),
        _ => return false,
    };

    // 1. Both must be Text nodes
    if left.role != Role::Text || right.role != Role::Text {
        return false;
    }

    // 2. Both must have actual text content
    if left.text.is_empty() || right.text.is_empty() {
        return false;
    }

    // 3. Same style
    if left.style != right.style {
        return false;
    }

    // 4. Neither has semantic attributes
    if has_semantic_attrs(chapter, left_id) || has_semantic_attrs(chapter, right_id) {
        return false;
    }

    // 5. Text ranges must be contiguous
    if left.text.end() != right.text.start {
        return false;
    }

    true
}

// ============================================================================
// Pass 4: List Fuser (Fragmented List Repair)
// ============================================================================

/// Fuse adjacent lists of the same type.
///
/// Converters often emit a separate `<ul>` for every `<li>`:
/// ```html
/// <ul><li>Item 1</li></ul>
/// <ul><li>Item 2</li></ul>
/// ```
///
/// This looks fine in browsers but breaks:
/// - Ordered list numbering (resets each time)
/// - Margins (double spacing between items)
/// - Semantic structure
///
/// We fuse adjacent lists by moving children from the second list to the first.
fn fuse_lists(chapter: &mut IRChapter) {
    if chapter.node_count() > 0 {
        fuse_list_children(chapter, NodeId::ROOT);
    }
}

fn fuse_list_children(chapter: &mut IRChapter, parent_id: NodeId) {
    // 1. Recurse into children first (bottom-up)
    let mut child_opt = chapter.node(parent_id).and_then(|n| n.first_child);
    while let Some(child_id) = child_opt {
        fuse_list_children(chapter, child_id);
        child_opt = chapter.node(child_id).and_then(|n| n.next_sibling);
    }

    // 2. Walk siblings and fuse adjacent lists
    let mut cursor_opt = chapter.node(parent_id).and_then(|n| n.first_child);

    while let Some(current_id) = cursor_opt {
        let next_opt = chapter.node(current_id).and_then(|n| n.next_sibling);

        if let Some(next_id) = next_opt
            && can_fuse_lists(chapter, current_id, next_id)
        {
            fuse_list_pair(chapter, current_id, next_id);
            // Don't advance - check if new next is also fuseable
            continue;
        }

        cursor_opt = next_opt;
    }
}

/// Check if two adjacent nodes are lists that can be fused.
fn can_fuse_lists(chapter: &IRChapter, left_id: NodeId, right_id: NodeId) -> bool {
    let (left, right) = match (chapter.node(left_id), chapter.node(right_id)) {
        (Some(l), Some(r)) => (l, r),
        _ => return false,
    };

    // Must be same list type
    matches!(
        (left.role, right.role),
        (Role::OrderedList, Role::OrderedList) | (Role::UnorderedList, Role::UnorderedList)
    )
}

/// Fuse two adjacent lists by moving children from right to left.
fn fuse_list_pair(chapter: &mut IRChapter, left_id: NodeId, right_id: NodeId) {
    // Get right's children
    let right_first = chapter.node(right_id).and_then(|n| n.first_child);

    if right_first.is_none() {
        // Right list is empty, just unlink it
        let right_next = chapter.node(right_id).and_then(|n| n.next_sibling);
        if let Some(left_node) = chapter.node_mut(left_id) {
            left_node.next_sibling = right_next;
        }
        return;
    }

    // 1. Reparent all children of right to left
    let mut child_opt = right_first;
    while let Some(child_id) = child_opt {
        let next_child = chapter.node(child_id).and_then(|n| n.next_sibling);
        if let Some(child_node) = chapter.node_mut(child_id) {
            child_node.parent = Some(left_id);
        }
        child_opt = next_child;
    }

    // 2. Find left's last child
    let mut left_last = chapter.node(left_id).and_then(|n| n.first_child);
    if let Some(mut current) = left_last {
        while let Some(next) = chapter.node(current).and_then(|n| n.next_sibling) {
            current = next;
        }
        left_last = Some(current);
    }

    // 3. Stitch: left_last.next_sibling = right_first
    if let Some(last_id) = left_last {
        if let Some(last_node) = chapter.node_mut(last_id) {
            last_node.next_sibling = right_first;
        }
    } else {
        // Left was empty, right's children become left's children
        if let Some(left_node) = chapter.node_mut(left_id) {
            left_node.first_child = right_first;
        }
    }

    // 4. Unlink right from sibling chain
    let right_next = chapter.node(right_id).and_then(|n| n.next_sibling);
    if let Some(left_node) = chapter.node_mut(left_id) {
        left_node.next_sibling = right_next;
    }
}

// ============================================================================
// Pass 5: Wrap Mixed Content (Inline/Block Normalization)
// ============================================================================

/// Wrap consecutive inline children in a Container when they're siblings to block elements.
///
/// HTML allows mixed inline and block content in some containers:
/// ```html
/// <blockquote>
///   <p>Some verse...</p>
///   <cite>— Author</cite>
/// </blockquote>
/// ```
///
/// In this example, `<cite>` (mapped to `Inline`) is a sibling to `<p>` (a block element).
/// During KFX export, inline children become spans on the parent container, which inverts
/// the content order (inlines appear before blocks).
///
/// This pass detects block containers with mixed inline/block children and wraps
/// consecutive inline runs in a Container node, normalizing the structure:
///
/// Before: BlockQuote > [Paragraph, Inline "cite"]
/// After:  BlockQuote > [Paragraph, Container > [Inline "cite"]]
fn wrap_mixed_content(chapter: &mut IRChapter) {
    if chapter.node_count() > 0 {
        wrap_mixed_children(chapter, NodeId::ROOT);
    }
}

fn wrap_mixed_children(chapter: &mut IRChapter, parent_id: NodeId) {
    // 1. Recurse into children first (bottom-up)
    let mut child_opt = chapter.node(parent_id).and_then(|n| n.first_child);
    while let Some(child_id) = child_opt {
        wrap_mixed_children(chapter, child_id);
        child_opt = chapter.node(child_id).and_then(|n| n.next_sibling);
    }

    // 2. Check if parent is a block container that might have mixed content
    let parent_role = chapter.node(parent_id).map(|n| n.role);
    if !is_block_container(parent_role) {
        return;
    }

    // 3. Analyze children: do we have both inline and block children?
    let (has_inline, has_block) = analyze_children(chapter, parent_id);
    if !has_inline || !has_block {
        return; // No mixed content
    }

    // 4. Find runs of consecutive inline children and wrap them
    wrap_inline_runs(chapter, parent_id);
}

/// Check if a role is a block container that can have mixed content.
fn is_block_container(role: Option<Role>) -> bool {
    matches!(
        role,
        Some(
            Role::Root
                | Role::Container
                | Role::BlockQuote
                | Role::Figure
                | Role::Sidebar
                | Role::Footnote
                | Role::ListItem
                | Role::TableCell
        )
    )
}

/// Check if a role represents inline content.
fn is_inline_role(role: Role) -> bool {
    matches!(
        role,
        Role::Text | Role::Inline | Role::Link | Role::Image | Role::Break
    )
}

/// Analyze children to detect if we have mixed inline/block content.
fn analyze_children(chapter: &IRChapter, parent_id: NodeId) -> (bool, bool) {
    let mut has_inline = false;
    let mut has_block = false;

    let mut child_opt = chapter.node(parent_id).and_then(|n| n.first_child);
    while let Some(child_id) = child_opt {
        if let Some(child) = chapter.node(child_id) {
            if is_inline_role(child.role) {
                has_inline = true;
            } else {
                has_block = true;
            }
        }
        child_opt = chapter.node(child_id).and_then(|n| n.next_sibling);
    }

    (has_inline, has_block)
}

/// Find and wrap consecutive runs of inline children.
fn wrap_inline_runs(chapter: &mut IRChapter, parent_id: NodeId) {
    // Collect child info to avoid borrow issues
    let mut children_info: Vec<(NodeId, bool)> = Vec::new();
    let mut child_opt = chapter.node(parent_id).and_then(|n| n.first_child);
    while let Some(child_id) = child_opt {
        let is_inline = chapter
            .node(child_id)
            .map(|n| is_inline_role(n.role))
            .unwrap_or(false);
        children_info.push((child_id, is_inline));
        child_opt = chapter.node(child_id).and_then(|n| n.next_sibling);
    }

    // Find inline runs (consecutive inline children)
    let mut runs: Vec<(usize, usize)> = Vec::new(); // (start_idx, end_idx) inclusive
    let mut run_start: Option<usize> = None;

    for (idx, &(_, is_inline)) in children_info.iter().enumerate() {
        if is_inline {
            if run_start.is_none() {
                run_start = Some(idx);
            }
        } else if let Some(start) = run_start {
            runs.push((start, idx - 1));
            run_start = None;
        }
    }
    // Handle trailing run
    if let Some(start) = run_start {
        runs.push((start, children_info.len() - 1));
    }

    // Wrap runs in reverse order to preserve indices
    for (start_idx, end_idx) in runs.into_iter().rev() {
        wrap_run(chapter, parent_id, &children_info, start_idx, end_idx);
    }
}

/// Wrap a single run of inline children in a Container.
fn wrap_run(
    chapter: &mut IRChapter,
    parent_id: NodeId,
    children_info: &[(NodeId, bool)],
    start_idx: usize,
    end_idx: usize,
) {
    use crate::ir::Node;

    // Create wrapper Container
    let wrapper_id = chapter.alloc_node(Node::new(Role::Container));

    // Set wrapper's parent
    if let Some(wrapper) = chapter.node_mut(wrapper_id) {
        wrapper.parent = Some(parent_id);
    }

    // Get the last node in this run
    let last_inline_id = children_info[end_idx].0;

    // Get next sibling after the run (if any)
    let after_run = chapter.node(last_inline_id).and_then(|n| n.next_sibling);

    // Reparent inline nodes to wrapper
    let mut prev_in_wrapper: Option<NodeId> = None;
    for (child_id, _) in &children_info[start_idx..=end_idx] {
        let child_id = *child_id;

        // Set new parent
        if let Some(child) = chapter.node_mut(child_id) {
            child.parent = Some(wrapper_id);
        }

        // Link within wrapper
        if let Some(prev_id) = prev_in_wrapper {
            if let Some(prev) = chapter.node_mut(prev_id) {
                prev.next_sibling = Some(child_id);
            }
        } else {
            // First child of wrapper
            if let Some(wrapper) = chapter.node_mut(wrapper_id) {
                wrapper.first_child = Some(child_id);
            }
        }
        prev_in_wrapper = Some(child_id);
    }

    // Clear next_sibling of last inline node
    if let Some(last) = chapter.node_mut(last_inline_id) {
        last.next_sibling = None;
    }

    // Set wrapper's next_sibling
    if let Some(wrapper) = chapter.node_mut(wrapper_id) {
        wrapper.next_sibling = after_run;
    }

    // Link wrapper into parent's child chain
    if start_idx == 0 {
        // Wrapper becomes first child
        if let Some(parent) = chapter.node_mut(parent_id) {
            parent.first_child = Some(wrapper_id);
        }
    } else {
        // Link previous sibling to wrapper
        let prev_sibling_id = children_info[start_idx - 1].0;
        if let Some(prev) = chapter.node_mut(prev_sibling_id) {
            prev.next_sibling = Some(wrapper_id);
        }
    }
}

// ============================================================================
// Pass 6: Pruner (Empty Container Removal)
// ============================================================================

/// Remove empty containers in post-order (cascading).
///
/// "Div soup" from old converters leaves empty containers:
/// ```html
/// <div class="clear"></div>
/// <span id="ad-placeholder"></span>
/// ```
///
/// Post-order traversal enables cascading:
/// - `<div><span></span></div>`
/// - Step 1: Visit span, it's empty, delete
/// - Step 2: Visit div, now empty, delete
/// - Result: Entire dead subtree vanishes
fn prune_empty(chapter: &mut IRChapter) {
    if chapter.node_count() > 0 {
        prune_children(chapter, NodeId::ROOT);
    }
}

fn prune_children(chapter: &mut IRChapter, parent_id: NodeId) {
    // 1. Recurse into children first (post-order - children before parent)
    let mut child_opt = chapter.node(parent_id).and_then(|n| n.first_child);
    while let Some(child_id) = child_opt {
        prune_children(chapter, child_id);
        child_opt = chapter.node(child_id).and_then(|n| n.next_sibling);
    }

    // 2. Walk siblings and prune empty containers
    let mut prev_opt: Option<NodeId> = None;
    let mut cursor_opt = chapter.node(parent_id).and_then(|n| n.first_child);

    while let Some(current_id) = cursor_opt {
        let next_opt = chapter.node(current_id).and_then(|n| n.next_sibling);

        if should_prune(chapter, current_id) {
            // Unlink this node
            if let Some(prev_id) = prev_opt {
                if let Some(prev_node) = chapter.node_mut(prev_id) {
                    prev_node.next_sibling = next_opt;
                }
            } else if let Some(parent_node) = chapter.node_mut(parent_id) {
                parent_node.first_child = next_opt;
            }
            // Don't update prev_opt
        } else {
            prev_opt = Some(current_id);
        }

        cursor_opt = next_opt;
    }
}

/// Check if a node should be pruned (empty container).
fn should_prune(chapter: &IRChapter, node_id: NodeId) -> bool {
    let node = match chapter.node(node_id) {
        Some(n) => n,
        None => return false,
    };

    // Only prune containers (never Text, Image, Break, Rule)
    if !is_prunable_role(node.role) {
        return false;
    }

    // Must have no children
    if node.first_child.is_some() {
        return false;
    }

    // Must have no text content
    if !node.text.is_empty() {
        return false;
    }

    // Safety: Don't prune if it has an ID (might be a link target)
    if chapter.semantics.id(node_id).is_some() {
        return false;
    }

    // Safety: Don't prune if it has src (might be loading content)
    if chapter.semantics.src(node_id).is_some() {
        return false;
    }

    true
}

/// Check if a role can be pruned when empty.
fn is_prunable_role(role: Role) -> bool {
    matches!(
        role,
        Role::Container
            | Role::Inline
            | Role::Figure
            | Role::Sidebar
            | Role::Footnote
            | Role::BlockQuote
            | Role::OrderedList
            | Role::UnorderedList
            | Role::DefinitionList
            | Role::Table
            | Role::TableRow
    )
}

// ============================================================================
// Shared Helpers
// ============================================================================

/// Check if a node has any semantic attributes that prevent optimization.
fn has_semantic_attrs(chapter: &IRChapter, node_id: NodeId) -> bool {
    let s = &chapter.semantics;
    s.href(node_id).is_some()
        || s.src(node_id).is_some()
        || s.alt(node_id).is_some()
        || s.id(node_id).is_some()
        || s.title(node_id).is_some()
        || s.lang(node_id).is_some()
        || s.epub_type(node_id).is_some()
        || s.aria_role(node_id).is_some()
        || s.datetime(node_id).is_some()
        || s.language(node_id).is_some()
        || s.list_start(node_id).is_some()
        || s.row_span(node_id).is_some()
        || s.col_span(node_id).is_some()
        || s.is_header_cell(node_id)
}

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

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

    // ------------------------------------------------------------------------
    // Vacuum Tests
    // ------------------------------------------------------------------------

    #[test]
    fn test_vacuum_removes_whitespace_in_structural_container() {
        let mut chapter = IRChapter::new();

        // Create: Root > UnorderedList > [whitespace, ListItem, whitespace]
        // Lists are structural containers - whitespace between items is noise
        let list = chapter.alloc_node(Node::new(Role::UnorderedList));
        chapter.append_child(NodeId::ROOT, list);

        let ws1 = chapter.append_text("\n    ");
        let ws1_node = chapter.alloc_node(Node::text(ws1));
        chapter.append_child(list, ws1_node);

        let item = chapter.alloc_node(Node::new(Role::ListItem));
        chapter.append_child(list, item);

        let ws2 = chapter.append_text("\n  ");
        let ws2_node = chapter.alloc_node(Node::text(ws2));
        chapter.append_child(list, ws2_node);

        // Before: 3 children
        assert_eq!(chapter.children(list).count(), 3);

        vacuum(&mut chapter);

        // After: 1 child (just the ListItem)
        let children: Vec<_> = chapter.children(list).collect();
        assert_eq!(children.len(), 1);
        assert_eq!(chapter.node(children[0]).unwrap().role, Role::ListItem);
    }

    #[test]
    fn test_vacuum_preserves_whitespace_in_inline() {
        let mut chapter = IRChapter::new();

        // Create: Root > Inline > [whitespace, Text]
        // Whitespace inside Inline should be preserved
        let inline = chapter.alloc_node(Node::new(Role::Inline));
        chapter.append_child(NodeId::ROOT, inline);

        let ws = chapter.append_text(" ");
        let ws_node = chapter.alloc_node(Node::text(ws));
        chapter.append_child(inline, ws_node);

        let text = chapter.append_text("word");
        let text_node = chapter.alloc_node(Node::text(text));
        chapter.append_child(inline, text_node);

        vacuum(&mut chapter);

        // Both should still be there
        assert_eq!(chapter.children(inline).count(), 2);
    }

    #[test]
    fn test_vacuum_preserves_whitespace_in_paragraph() {
        let mut chapter = IRChapter::new();

        // Create: Root > Paragraph > [Inline "Hello", whitespace " ", Inline "World"]
        // This simulates: <p><span>Hello</span> <span>World</span></p>
        // The space is significant!
        let para = chapter.alloc_node(Node::new(Role::Paragraph));
        chapter.append_child(NodeId::ROOT, para);

        let span1 = chapter.alloc_node(Node::new(Role::Inline));
        chapter.append_child(para, span1);
        let text1 = chapter.append_text("Hello");
        let text1_node = chapter.alloc_node(Node::text(text1));
        chapter.append_child(span1, text1_node);

        let ws = chapter.append_text(" ");
        let ws_node = chapter.alloc_node(Node::text(ws));
        chapter.append_child(para, ws_node);

        let span2 = chapter.alloc_node(Node::new(Role::Inline));
        chapter.append_child(para, span2);
        let text2 = chapter.append_text("World");
        let text2_node = chapter.alloc_node(Node::text(text2));
        chapter.append_child(span2, text2_node);

        // Before: 3 children (span, space, span)
        assert_eq!(chapter.children(para).count(), 3);

        vacuum(&mut chapter);

        // After: Still 3 children - space is preserved!
        assert_eq!(chapter.children(para).count(), 3);
    }

    #[test]
    fn test_vacuum_preserves_node_with_id() {
        let mut chapter = IRChapter::new();

        // Create: Root > UnorderedList > [whitespace with ID, ListItem]
        // Even in a structural container, nodes with IDs should be preserved
        let list = chapter.alloc_node(Node::new(Role::UnorderedList));
        chapter.append_child(NodeId::ROOT, list);

        let ws = chapter.append_text(" ");
        let ws_node = chapter.alloc_node(Node::text(ws));
        chapter.append_child(list, ws_node);
        chapter.semantics.set_id(ws_node, "anchor".to_string());

        let item = chapter.alloc_node(Node::new(Role::ListItem));
        chapter.append_child(list, item);

        vacuum(&mut chapter);

        // Whitespace should be preserved because it has an ID (link target)
        assert_eq!(chapter.children(list).count(), 2);
    }

    // ------------------------------------------------------------------------
    // Hoist Tests
    // ------------------------------------------------------------------------

    #[test]
    fn test_hoist_dissolves_single_child_wrapper() {
        let mut chapter = IRChapter::new();

        // Create: Root > Container > Inline > Text "Hello"
        // Both Container and Inline are redundant wrappers (single child each)
        let container = chapter.alloc_node(Node::new(Role::Container));
        chapter.append_child(NodeId::ROOT, container);

        let inline = chapter.alloc_node(Node::new(Role::Inline));
        chapter.append_child(container, inline);

        let text_range = chapter.append_text("Hello");
        let text_node = chapter.alloc_node(Node::text(text_range));
        chapter.append_child(inline, text_node);

        // Before: Root > Container > Inline > Text
        assert_eq!(chapter.children(NodeId::ROOT).count(), 1);
        let root_child = chapter.children(NodeId::ROOT).next().unwrap();
        assert_eq!(chapter.node(root_child).unwrap().role, Role::Container);

        hoist_nested_inlines(&mut chapter);

        // After: Root > Text (both Container and Inline dissolved)
        // Multiple passes dissolve the nested wrappers
        let root_children: Vec<_> = chapter.children(NodeId::ROOT).collect();
        assert_eq!(root_children.len(), 1);
        assert_eq!(chapter.node(root_children[0]).unwrap().role, Role::Text);
    }

    #[test]
    fn test_hoist_enables_span_merge() {
        let mut chapter = IRChapter::new();

        // Create "Wrapper Hell" structure (like MOBI small caps):
        // Root > [Container > Inline > Text "T", Container > Inline > Text "HE"]
        let c1 = chapter.alloc_node(Node::new(Role::Container));
        chapter.append_child(NodeId::ROOT, c1);
        let i1 = chapter.alloc_node(Node::new(Role::Inline));
        chapter.append_child(c1, i1);
        let t1 = chapter.append_text("T");
        let t1_node = chapter.alloc_node(Node::text(t1));
        chapter.append_child(i1, t1_node);

        let c2 = chapter.alloc_node(Node::new(Role::Container));
        chapter.append_child(NodeId::ROOT, c2);
        let i2 = chapter.alloc_node(Node::new(Role::Inline));
        chapter.append_child(c2, i2);
        let t2 = chapter.append_text("HE");
        let t2_node = chapter.alloc_node(Node::text(t2));
        chapter.append_child(i2, t2_node);

        // Before: 2 containers at root
        assert_eq!(chapter.children(NodeId::ROOT).count(), 2);

        // Full optimization pipeline
        optimize(&mut chapter);

        // After: Should have a single text node with "THE"
        // (Containers dissolved, Inlines dissolved, Text merged)
        let mut found_the = false;
        for id in chapter.iter_dfs() {
            let node = chapter.node(id).unwrap();
            if node.role == Role::Text && !node.text.is_empty() {
                let text = chapter.text(node.text);
                if text == "THE" {
                    found_the = true;
                }
            }
        }
        assert!(found_the, "Expected merged text 'THE' not found");
    }

    #[test]
    fn test_hoist_preserves_multi_child_container() {
        let mut chapter = IRChapter::new();

        // Create: Root > Container > [Inline "A", Inline "B"]
        // Container has 2 children, so it's NOT redundant
        let container = chapter.alloc_node(Node::new(Role::Container));
        chapter.append_child(NodeId::ROOT, container);

        let i1 = chapter.alloc_node(Node::new(Role::Inline));
        chapter.append_child(container, i1);
        let t1 = chapter.append_text("A");
        let t1_node = chapter.alloc_node(Node::text(t1));
        chapter.append_child(i1, t1_node);

        let i2 = chapter.alloc_node(Node::new(Role::Inline));
        chapter.append_child(container, i2);
        let t2 = chapter.append_text("B");
        let t2_node = chapter.alloc_node(Node::text(t2));
        chapter.append_child(i2, t2_node);

        hoist_nested_inlines(&mut chapter);

        // Container should still be there (has 2 children)
        let root_children: Vec<_> = chapter.children(NodeId::ROOT).collect();
        assert_eq!(root_children.len(), 1);
        assert_eq!(
            chapter.node(root_children[0]).unwrap().role,
            Role::Container
        );
    }

    #[test]
    fn test_hoist_preserves_container_with_id() {
        let mut chapter = IRChapter::new();

        // Create: Root > Container[id="anchor"] > Inline > Text
        // Container has semantic attribute, so it's NOT redundant
        let container = chapter.alloc_node(Node::new(Role::Container));
        chapter.append_child(NodeId::ROOT, container);
        chapter.semantics.set_id(container, "anchor".to_string());

        let inline = chapter.alloc_node(Node::new(Role::Inline));
        chapter.append_child(container, inline);

        let text_range = chapter.append_text("Hello");
        let text_node = chapter.alloc_node(Node::text(text_range));
        chapter.append_child(inline, text_node);

        hoist_nested_inlines(&mut chapter);

        // Container should still be there (has ID)
        let root_children: Vec<_> = chapter.children(NodeId::ROOT).collect();
        assert_eq!(root_children.len(), 1);
        assert_eq!(
            chapter.node(root_children[0]).unwrap().role,
            Role::Container
        );
    }

    // ------------------------------------------------------------------------
    // Span Merge Tests
    // ------------------------------------------------------------------------

    #[test]
    fn test_merge_adjacent_text_nodes() {
        let mut chapter = IRChapter::new();

        // Use Paragraph - it contains inline content where spaces matter
        let para = chapter.alloc_node(Node::new(Role::Paragraph));
        chapter.append_child(NodeId::ROOT, para);

        // Add "THE " as three separate text nodes
        let range1 = chapter.append_text("T");
        let node1 = chapter.alloc_node(Node::text(range1));
        chapter.append_child(para, node1);

        let range2 = chapter.append_text("HE");
        let node2 = chapter.alloc_node(Node::text(range2));
        chapter.append_child(para, node2);

        let range3 = chapter.append_text(" ");
        let node3 = chapter.alloc_node(Node::text(range3));
        chapter.append_child(para, node3);

        assert_eq!(chapter.children(para).count(), 3);

        optimize(&mut chapter);

        let children: Vec<_> = chapter.children(para).collect();
        assert_eq!(children.len(), 1);
        assert_eq!(
            chapter.text(chapter.node(children[0]).unwrap().text),
            "THE "
        );
    }

    #[test]
    fn test_no_merge_different_styles() {
        let mut chapter = IRChapter::new();

        // Use Paragraph - it contains inline content
        let para = chapter.alloc_node(Node::new(Role::Paragraph));
        chapter.append_child(NodeId::ROOT, para);

        let range1 = chapter.append_text("Hello");
        let mut node1 = Node::text(range1);
        let bold = chapter.styles.intern(crate::ir::ComputedStyle {
            font_weight: crate::ir::FontWeight::BOLD,
            ..Default::default()
        });
        node1.style = bold;
        let id1 = chapter.alloc_node(node1);
        chapter.append_child(para, id1);

        let range2 = chapter.append_text(" World");
        let node2 = Node::text(range2);
        let id2 = chapter.alloc_node(node2);
        chapter.append_child(para, id2);

        optimize(&mut chapter);

        assert_eq!(chapter.children(para).count(), 2);
    }

    // ------------------------------------------------------------------------
    // List Fuser Tests
    // ------------------------------------------------------------------------

    #[test]
    fn test_fuse_adjacent_unordered_lists() {
        let mut chapter = IRChapter::new();

        // Create two adjacent ul elements
        let ul1 = chapter.alloc_node(Node::new(Role::UnorderedList));
        chapter.append_child(NodeId::ROOT, ul1);

        let li1 = chapter.alloc_node(Node::new(Role::ListItem));
        chapter.append_child(ul1, li1);

        let ul2 = chapter.alloc_node(Node::new(Role::UnorderedList));
        chapter.append_child(NodeId::ROOT, ul2);

        let li2 = chapter.alloc_node(Node::new(Role::ListItem));
        chapter.append_child(ul2, li2);

        // Before: 2 lists at root
        assert_eq!(chapter.children(NodeId::ROOT).count(), 2);

        fuse_lists(&mut chapter);

        // After: 1 list with 2 items
        let root_children: Vec<_> = chapter.children(NodeId::ROOT).collect();
        assert_eq!(root_children.len(), 1);

        let list_children: Vec<_> = chapter.children(root_children[0]).collect();
        assert_eq!(list_children.len(), 2);
    }

    #[test]
    fn test_no_fuse_different_list_types() {
        let mut chapter = IRChapter::new();

        let ul = chapter.alloc_node(Node::new(Role::UnorderedList));
        chapter.append_child(NodeId::ROOT, ul);

        let ol = chapter.alloc_node(Node::new(Role::OrderedList));
        chapter.append_child(NodeId::ROOT, ol);

        fuse_lists(&mut chapter);

        // Should still be 2 lists
        assert_eq!(chapter.children(NodeId::ROOT).count(), 2);
    }

    // ------------------------------------------------------------------------
    // Pruner Tests
    // ------------------------------------------------------------------------

    #[test]
    fn test_prune_empty_container() {
        let mut chapter = IRChapter::new();

        let container = chapter.alloc_node(Node::new(Role::Container));
        chapter.append_child(NodeId::ROOT, container);

        // Empty container should be pruned
        prune_empty(&mut chapter);

        assert_eq!(chapter.children(NodeId::ROOT).count(), 0);
    }

    #[test]
    fn test_prune_cascades() {
        let mut chapter = IRChapter::new();

        // Create: Root > Container > Inline (empty)
        let container = chapter.alloc_node(Node::new(Role::Container));
        chapter.append_child(NodeId::ROOT, container);

        let inline = chapter.alloc_node(Node::new(Role::Inline));
        chapter.append_child(container, inline);

        // Before: Container has 1 child
        assert_eq!(chapter.children(container).count(), 1);

        prune_empty(&mut chapter);

        // After: Both should be gone (cascading)
        assert_eq!(chapter.children(NodeId::ROOT).count(), 0);
    }

    #[test]
    fn test_prune_preserves_id() {
        let mut chapter = IRChapter::new();

        let container = chapter.alloc_node(Node::new(Role::Container));
        chapter.append_child(NodeId::ROOT, container);
        chapter.semantics.set_id(container, "anchor".to_string());

        prune_empty(&mut chapter);

        // Should NOT be pruned (has ID, might be link target)
        assert_eq!(chapter.children(NodeId::ROOT).count(), 1);
    }

    #[test]
    fn test_prune_preserves_content() {
        let mut chapter = IRChapter::new();

        let container = chapter.alloc_node(Node::new(Role::Container));
        chapter.append_child(NodeId::ROOT, container);

        let text_range = chapter.append_text("Content");
        let text = chapter.alloc_node(Node::text(text_range));
        chapter.append_child(container, text);

        prune_empty(&mut chapter);

        // Container has content, should NOT be pruned
        assert_eq!(chapter.children(NodeId::ROOT).count(), 1);
    }

    // ------------------------------------------------------------------------
    // Pipeline Integration Tests
    // ------------------------------------------------------------------------

    #[test]
    fn test_full_pipeline() {
        let mut chapter = IRChapter::new();

        // Create a structure with adjacent lists:
        // Root > Container > [ul1, ul2]
        let container = chapter.alloc_node(Node::new(Role::Container));
        chapter.append_child(NodeId::ROOT, container);

        let ul1 = chapter.alloc_node(Node::new(Role::UnorderedList));
        chapter.append_child(container, ul1);
        let li1 = chapter.alloc_node(Node::new(Role::ListItem));
        chapter.append_child(ul1, li1);

        let ul2 = chapter.alloc_node(Node::new(Role::UnorderedList));
        chapter.append_child(container, ul2);
        let li2 = chapter.alloc_node(Node::new(Role::ListItem));
        chapter.append_child(ul2, li2);

        // Before: 2 lists under container
        assert_eq!(chapter.children(container).count(), 2);

        optimize(&mut chapter);

        // After optimization:
        // - Lists fused into 1
        // = 1 child (the fused list)
        let children: Vec<_> = chapter.children(container).collect();
        assert_eq!(children.len(), 1);

        // The fused list should have 2 items
        let list_items: Vec<_> = chapter.children(children[0]).collect();
        assert_eq!(list_items.len(), 2);
    }

    // ------------------------------------------------------------------------
    // Mixed Content Wrapping Tests
    // ------------------------------------------------------------------------

    #[test]
    fn test_wrap_mixed_content_in_blockquote() {
        let mut chapter = IRChapter::new();

        // Create: BlockQuote > [Paragraph "verse", Inline "cite"]
        // This simulates: <blockquote><p>verse</p><cite>author</cite></blockquote>
        let bq = chapter.alloc_node(Node::new(Role::BlockQuote));
        chapter.append_child(NodeId::ROOT, bq);

        let para = chapter.alloc_node(Node::new(Role::Paragraph));
        chapter.append_child(bq, para);
        let verse_range = chapter.append_text("Some verse...");
        let verse = chapter.alloc_node(Node::text(verse_range));
        chapter.append_child(para, verse);

        let cite = chapter.alloc_node(Node::new(Role::Inline));
        chapter.append_child(bq, cite);
        let author_range = chapter.append_text("— Author");
        let author = chapter.alloc_node(Node::text(author_range));
        chapter.append_child(cite, author);

        // Before: BlockQuote has 2 children (Paragraph, Inline)
        assert_eq!(chapter.children(bq).count(), 2);

        wrap_mixed_content(&mut chapter);

        // After: BlockQuote > [Paragraph, Container > [Inline]]
        // The Inline is wrapped in a Container
        let children: Vec<_> = chapter.children(bq).collect();
        assert_eq!(children.len(), 2);

        // First child is still the Paragraph
        assert_eq!(chapter.node(children[0]).unwrap().role, Role::Paragraph);

        // Second child is now a Container (wrapper)
        assert_eq!(chapter.node(children[1]).unwrap().role, Role::Container);

        // The wrapper contains the Inline
        let wrapper_children: Vec<_> = chapter.children(children[1]).collect();
        assert_eq!(wrapper_children.len(), 1);
        assert_eq!(
            chapter.node(wrapper_children[0]).unwrap().role,
            Role::Inline
        );
    }

    #[test]
    fn test_no_wrap_when_only_block_children() {
        let mut chapter = IRChapter::new();

        // Create: Container > [Paragraph, Paragraph]
        // All children are blocks, no wrapping needed
        let container = chapter.alloc_node(Node::new(Role::Container));
        chapter.append_child(NodeId::ROOT, container);

        let p1 = chapter.alloc_node(Node::new(Role::Paragraph));
        chapter.append_child(container, p1);

        let p2 = chapter.alloc_node(Node::new(Role::Paragraph));
        chapter.append_child(container, p2);

        // Before
        assert_eq!(chapter.children(container).count(), 2);

        wrap_mixed_content(&mut chapter);

        // After: No change
        let children: Vec<_> = chapter.children(container).collect();
        assert_eq!(children.len(), 2);
        assert_eq!(chapter.node(children[0]).unwrap().role, Role::Paragraph);
        assert_eq!(chapter.node(children[1]).unwrap().role, Role::Paragraph);
    }

    #[test]
    fn test_no_wrap_when_only_inline_children() {
        let mut chapter = IRChapter::new();

        // Create: Paragraph > [Text, Inline, Text]
        // All children are inline, no wrapping needed
        let para = chapter.alloc_node(Node::new(Role::Paragraph));
        chapter.append_child(NodeId::ROOT, para);

        let t1_range = chapter.append_text("Hello ");
        let t1 = chapter.alloc_node(Node::text(t1_range));
        chapter.append_child(para, t1);

        let span = chapter.alloc_node(Node::new(Role::Inline));
        chapter.append_child(para, span);

        let t2_range = chapter.append_text(" World");
        let t2 = chapter.alloc_node(Node::text(t2_range));
        chapter.append_child(para, t2);

        // Before
        assert_eq!(chapter.children(para).count(), 3);

        wrap_mixed_content(&mut chapter);

        // After: No change (Paragraph is not a block container in is_block_container)
        let children: Vec<_> = chapter.children(para).collect();
        assert_eq!(children.len(), 3);
    }
}